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-2018 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
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
67 (defvar org-inhibit-highlight-removal nil
) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
71 ;;;; Require other packages
75 (eval-when-compile (require 'gnus-sum
))
79 (require 'format-spec
)
81 (or (eq this-command
'eval-buffer
)
83 (load (concat (file-name-directory load-file-name
)
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
95 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
96 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 ;; In Org buffers, the value of `outline-regexp' is that of
99 ;; `org-outline-regexp'. The only function still directly relying on
100 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
101 ;; job when `orgstruct-mode' is active.
102 (defvar org-outline-regexp
"\\*+ "
103 "Regexp to match Org headlines.")
105 (defvar org-outline-regexp-bol
"^\\*+ "
106 "Regexp to match Org headlines.
107 This is similar to `org-outline-regexp' but additionally makes
108 sure that we are at the beginning of the line.")
110 (defvar org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
111 "Matches a headline, putting stars and text into groups.
112 Stars are put in group 1 and the trimmed body in group 2.")
114 (declare-function calendar-check-holidays
"holidays" (date))
115 (declare-function cdlatex-environment
"ext:cdlatex" (environment item
))
116 (declare-function isearch-no-upper-case-p
"isearch" (string regexp-flag
))
117 (declare-function org-add-archive-files
"org-archive" (files))
118 (declare-function org-agenda-entry-get-agenda-timestamp
"org-agenda" (pom))
119 (declare-function org-agenda-list
"org-agenda" (&optional arg start-day span with-hour
))
120 (declare-function org-agenda-redo
"org-agenda" (&optional all
))
121 (declare-function org-babel-do-in-edit-buffer
"ob-core" (&rest body
) t
)
122 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
123 (declare-function org-beamer-mode
"ox-beamer" (&optional prefix
) t
)
124 (declare-function org-clock-get-last-clock-out-time
"org-clock" ())
125 (declare-function org-clock-out
"org-clock" (&optional switch-to-state fail-quietly at-time
))
126 (declare-function org-clock-remove-overlays
"org-clock" (&optional beg end noremove
))
127 (declare-function org-clock-sum
"org-clock" (&optional tstart tend headline-filter propname
))
128 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
129 (declare-function org-clock-timestamps-down
"org-clock" (&optional n
))
130 (declare-function org-clock-timestamps-up
"org-clock" (&optional n
))
131 (declare-function org-clock-update-time-maybe
"org-clock" ())
132 (declare-function org-clocking-buffer
"org-clock" ())
133 (declare-function org-clocktable-shift
"org-clock" (dir n
))
135 org-duration-from-minutes
"org-duration" (minutes &optional fmt canonical
))
136 (declare-function org-element-at-point
"org-element" ())
137 (declare-function org-element-cache-refresh
"org-element" (pos))
138 (declare-function org-element-cache-reset
"org-element" (&optional all
))
139 (declare-function org-element-contents
"org-element" (element))
140 (declare-function org-element-context
"org-element" (&optional element
))
141 (declare-function org-element-copy
"org-element" (datum))
142 (declare-function org-element-interpret-data
"org-element" (data))
143 (declare-function org-element-lineage
"org-element" (blob &optional types with-self
))
144 (declare-function org-element-link-parser
"org-element" ())
145 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
146 (declare-function org-element-parse-buffer
"org-element" (&optional granularity visible-only
))
147 (declare-function org-element-property
"org-element" (property element
))
148 (declare-function org-element-put-property
"org-element" (element property value
))
149 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
150 (declare-function org-element-type
"org-element" (element))
151 (declare-function org-element-update-syntax
"org-element" ())
152 (declare-function org-id-find-id-file
"org-id" (id))
153 (declare-function org-id-get-create
"org-id" (&optional force
))
154 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
155 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
156 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
157 (declare-function org-plot
/gnuplot
"org-plot" (&optional params
))
158 (declare-function org-table-align
"org-table" ())
159 (declare-function org-table-begin
"org-table" (&optional table-type
))
160 (declare-function org-table-beginning-of-field
"org-table" (&optional n
))
161 (declare-function org-table-blank-field
"org-table" ())
162 (declare-function org-table-calc-current-TBLFM
"org-table" (&optional arg
))
163 (declare-function org-table-copy-region
"org-table" (beg end
&optional cut
))
164 (declare-function org-table-cut-region
"org-table" (beg end
))
165 (declare-function org-table-edit-field
"org-table" (arg))
166 (declare-function org-table-end
"org-table" (&optional table-type
))
167 (declare-function org-table-end-of-field
"org-table" (&optional n
))
168 (declare-function org-table-insert-row
"org-table" (&optional arg
))
169 (declare-function org-table-justify-field-maybe
"org-table" (&optional new
))
170 (declare-function org-table-maybe-eval-formula
"org-table" ())
171 (declare-function org-table-maybe-recalculate-line
"org-table" ())
172 (declare-function org-table-next-row
"org-table" ())
173 (declare-function org-table-paste-rectangle
"org-table" ())
174 (declare-function org-table-recalculate
"org-table" (&optional all noalign
))
176 org-table-sort-lines
"org-table"
177 (&optional with-case sorting-type getkey-func compare-func interactive?
))
178 (declare-function org-table-wrap-region
"org-table" (arg))
179 (declare-function org-tags-view
"org-agenda" (&optional todo-only match
))
180 (declare-function orgtbl-ascii-plot
"org-table" (&optional ask
))
181 (declare-function orgtbl-mode
"org-table" (&optional arg
))
182 (declare-function org-export-get-backend
"ox" (name))
183 (declare-function org-export-get-environment
"ox" (&optional backend subtreep ext-plist
))
184 (declare-function org-latex-make-preamble
"ox-latex" (info &optional template snippet?
))
186 (defvar ffap-url-regexp
)
187 (defvar org-element-paragraph-separate
)
189 (defsubst org-uniquify
(list)
190 "Non-destructively remove duplicate elements from LIST."
191 (let ((res (copy-sequence list
))) (delete-dups res
)))
193 (defsubst org-get-at-bol
(property)
194 "Get text property PROPERTY at the beginning of line."
195 (get-text-property (point-at-bol) property
))
197 (defsubst org-trim
(s &optional keep-lead
)
198 "Remove whitespace at the beginning and the end of string S.
199 When optional argument KEEP-LEAD is non-nil, removing blank lines
200 at the beginning of the string does not affect leading indentation."
201 (replace-regexp-in-string
202 (if keep-lead
"\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
203 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s
)))
205 ;; load languages based on value of `org-babel-load-languages'
206 (defvar org-babel-load-languages
)
209 (defun org-babel-do-load-languages (sym value
)
210 "Load the languages defined in `org-babel-load-languages'."
211 (set-default sym value
)
212 (dolist (pair org-babel-load-languages
)
213 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
215 (require (intern (concat "ob-" lang
)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-execute:" lang
)))
218 (funcall 'fmakunbound
219 (intern (concat "org-babel-expand-body:" lang
)))))))
221 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
223 (defun org-babel-load-file (file &optional compile
)
224 "Load Emacs Lisp source code blocks in the Org FILE.
225 This function exports the source code using `org-babel-tangle'
226 and then loads the resulting file using `load-file'. With prefix
227 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
228 file to byte-code before it is loaded."
229 (interactive "fFile to load: \nP")
230 (let* ((age (lambda (file)
232 (time-subtract (current-time)
233 (nth 5 (or (file-attributes (file-truename file
))
234 (file-attributes file
)))))))
235 (base-name (file-name-sans-extension file
))
236 (exported-file (concat base-name
".el")))
237 ;; tangle if the Org file is newer than the elisp file
238 (unless (and (file-exists-p exported-file
)
239 (> (funcall age file
) (funcall age exported-file
)))
240 ;; Tangle-file traversal returns reversed list of tangled files
241 ;; and we want to evaluate the first target.
243 (car (last (org-babel-tangle-file file exported-file
"emacs-lisp")))))
246 (progn (byte-compile-file exported-file
'load
)
247 "Compiled and loaded")
248 (progn (load-file exported-file
) "Loaded"))
251 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
252 "Languages which can be evaluated in Org buffers.
253 This list can be used to load support for any of the languages
254 below, note that each language will depend on a different set of
255 system executables and/or Emacs modes. When a language is
256 \"loaded\", then code blocks in that language can be evaluated
257 with `org-babel-execute-src-block' bound by default to C-c
258 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
259 be set to remove code block evaluation from the C-c C-c
260 keybinding. By default only Emacs Lisp (which has no
261 requirements) is loaded."
263 :set
'org-babel-do-load-languages
265 :type
'(alist :tag
"Babel Languages"
268 (const :tag
"Awk" awk
)
271 (const :tag
"Asymptote" asymptote
)
272 (const :tag
"Calc" calc
)
273 (const :tag
"Clojure" clojure
)
274 (const :tag
"CSS" css
)
275 (const :tag
"Ditaa" ditaa
)
276 (const :tag
"Dot" dot
)
277 (const :tag
"Ebnf2ps" ebnf2ps
)
278 (const :tag
"Emacs Lisp" emacs-lisp
)
279 (const :tag
"Forth" forth
)
280 (const :tag
"Fortran" fortran
)
281 (const :tag
"Gnuplot" gnuplot
)
282 (const :tag
"Haskell" haskell
)
283 (const :tag
"hledger" hledger
)
286 (const :tag
"Java" java
)
287 (const :tag
"Javascript" js
)
288 (const :tag
"LaTeX" latex
)
289 (const :tag
"Ledger" ledger
)
290 (const :tag
"Lilypond" lilypond
)
291 (const :tag
"Lisp" lisp
)
292 (const :tag
"Makefile" makefile
)
293 (const :tag
"Maxima" maxima
)
294 (const :tag
"Matlab" matlab
)
295 (const :tag
"Mscgen" mscgen
)
296 (const :tag
"Ocaml" ocaml
)
297 (const :tag
"Octave" octave
)
298 (const :tag
"Org" org
)
299 (const :tag
"Perl" perl
)
300 (const :tag
"Pico Lisp" picolisp
)
301 (const :tag
"PlantUML" plantuml
)
302 (const :tag
"Python" python
)
303 (const :tag
"Ruby" ruby
)
304 (const :tag
"Sass" sass
)
305 (const :tag
"Scala" scala
)
306 (const :tag
"Scheme" scheme
)
307 (const :tag
"Screen" screen
)
308 (const :tag
"Shell Script" shell
)
309 (const :tag
"Shen" shen
)
310 (const :tag
"Sql" sql
)
311 (const :tag
"Sqlite" sqlite
)
312 (const :tag
"Stan" stan
)
313 (const :tag
"Vala" vala
))
314 :value-type
(boolean :tag
"Activate" :value t
)))
316 ;;;; Customization variables
317 (defcustom org-clone-delete-id nil
318 "Remove ID property of clones of a subtree.
319 When non-nil, clones of a subtree don't inherit the ID property.
320 Otherwise they inherit the ID property with a new unique
330 (defun org-version (&optional here full message
)
331 "Show the Org version.
332 Interactively, or when MESSAGE is non-nil, show it in echo area.
333 With prefix argument, or when HERE is non-nil, insert it at point.
334 In non-interactive uses, a reduced version string is output unless
336 (interactive (list current-prefix-arg t
(not current-prefix-arg
)))
337 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
338 (save-load-suffixes (when (boundp 'load-suffixes
) load-suffixes
))
339 (load-suffixes (list ".el"))
341 (ignore-errors (org-find-library-dir "org-loaddefs"))))
342 (unless (and (fboundp 'org-release
) (fboundp 'org-git-version
))
343 (org-load-noerror-mustsuffix (concat org-dir
"org-version")))
344 (let* ((load-suffixes save-load-suffixes
)
345 (release (org-release))
346 (git-version (org-git-version))
347 (version (format "Org mode version %s (%s @ %s)"
351 (if (string= org-dir org-install-dir
)
353 (concat "mixed installation! "
357 "org-loaddefs.el can not be found!")))
358 (version1 (if full version release
)))
359 (when here
(insert version1
))
360 (when message
(message "%s" version1
))
363 (defconst org-version
(org-version))
370 (defconst org-block-regexp
371 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
372 "Regular expression for hiding blocks.")
374 (defconst org-dblock-start-re
375 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
376 "Matches the start line of a dynamic block, with parameters.")
378 (defconst org-dblock-end-re
"^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
379 "Matches the end of a dynamic block.")
381 ;;;; Clock and Planning
383 (defconst org-clock-string
"CLOCK:"
384 "String used as prefix for timestamps clocking work hours on an item.")
386 (defvar org-closed-string
"CLOSED:"
387 "String used as the prefix for timestamps logging closing a TODO entry.")
389 (defvar org-deadline-string
"DEADLINE:"
390 "String to mark deadline entries.
392 A deadline is this string, followed by a time stamp. It must be
393 a word, terminated by a colon. You can insert a schedule keyword
394 and a timestamp with `\\[org-deadline]'.")
396 (defvar org-scheduled-string
"SCHEDULED:"
397 "String to mark scheduled TODO entries.
399 A schedule is this string, followed by a time stamp. It must be
400 a word, terminated by a colon. You can insert a schedule keyword
401 and a timestamp with `\\[org-schedule]'.")
403 (defconst org-ds-keyword-length
407 (list org-deadline-string org-scheduled-string
408 org-clock-string org-closed-string
))))
409 "Maximum length of the DEADLINE and SCHEDULED keywords.")
411 (defconst org-planning-line-re
414 (list org-closed-string org-deadline-string org-scheduled-string
)
416 "Matches a line with planning info.
417 Matched keyword is in group 1.")
419 (defconst org-clock-line-re
420 (concat "^[ \t]*" org-clock-string
)
421 "Matches a line with clock info.")
423 (defconst org-deadline-regexp
(concat "\\<" org-deadline-string
)
424 "Matches the DEADLINE keyword.")
426 (defconst org-deadline-time-regexp
427 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
428 "Matches the DEADLINE keyword together with a time stamp.")
430 (defconst org-deadline-time-hour-regexp
431 (concat "\\<" org-deadline-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
435 (defconst org-deadline-line-regexp
436 (concat "\\<\\(" org-deadline-string
"\\).*")
437 "Matches the DEADLINE keyword and the rest of the line.")
439 (defconst org-scheduled-regexp
(concat "\\<" org-scheduled-string
)
440 "Matches the SCHEDULED keyword.")
442 (defconst org-scheduled-time-regexp
443 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
444 "Matches the SCHEDULED keyword together with a time stamp.")
446 (defconst org-scheduled-time-hour-regexp
447 (concat "\\<" org-scheduled-string
448 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
449 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
451 (defconst org-closed-time-regexp
452 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
453 "Matches the CLOSED keyword together with a time stamp.")
455 (defconst org-keyword-time-regexp
458 (list org-scheduled-string org-deadline-string org-closed-string
461 " *[[<]\\([^]>]+\\)[]>]")
462 "Matches any of the 4 keywords, together with the time stamp.")
464 (defconst org-keyword-time-not-clock-regexp
468 (list org-scheduled-string org-deadline-string org-closed-string
) t
)
469 " *[[<]\\([^]>]+\\)[]>]")
470 "Matches any of the 3 keywords, together with the time stamp.")
472 (defconst org-maybe-keyword-time-regexp
475 (list org-scheduled-string org-deadline-string org-closed-string
479 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
482 "Matches a timestamp, possibly preceded by a keyword.")
484 (defconst org-all-time-keywords
485 (mapcar (lambda (w) (substring w
0 -
1))
486 (list org-scheduled-string org-deadline-string
487 org-clock-string org-closed-string
))
488 "List of time keywords.")
492 (defconst org-drawer-regexp
"^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
493 "Matches first or last line of a hidden block.
494 Group 1 contains drawer's name or \"END\".")
496 (defconst org-property-start-re
"^[ \t]*:PROPERTIES:[ \t]*$"
497 "Regular expression matching the first line of a property drawer.")
499 (defconst org-property-end-re
"^[ \t]*:END:[ \t]*$"
500 "Regular expression matching the last line of a property drawer.")
502 (defconst org-clock-drawer-start-re
"^[ \t]*:CLOCK:[ \t]*$"
503 "Regular expression matching the first line of a clock drawer.")
505 (defconst org-clock-drawer-end-re
"^[ \t]*:END:[ \t]*$"
506 "Regular expression matching the last line of a clock drawer.")
508 (defconst org-property-drawer-re
509 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
510 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
511 "[ \t]*:END:[ \t]*$")
512 "Matches an entire property drawer.")
514 (defconst org-clock-drawer-re
515 (concat "\\(" org-clock-drawer-start-re
"\\)[^\000]*?\\("
516 org-clock-drawer-end-re
"\\)\n?")
517 "Matches an entire clock drawer.")
521 (defconst org-heading-keyword-regexp-format
522 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
523 "Printf format for a regexp matching a headline with some keyword.
524 This regexp will match the headline of any node which has the
525 exact keyword that is put into the format. The keyword isn't in
526 any group by default, but the stars and the body are.")
528 (defconst org-heading-keyword-maybe-regexp-format
529 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
530 "Printf format for a regexp matching a headline, possibly with some keyword.
531 This regexp can match any headline with the specified keyword, or
532 without a keyword. The keyword isn't in any group by default,
533 but the stars and the body are.")
535 (defconst org-archive-tag
"ARCHIVE"
536 "The tag that marks a subtree as archived.
537 An archived subtree does not open during visibility cycling, and does
538 not contribute to the agenda listings.")
541 (defconst org-comment-string
"COMMENT"
542 "Entries starting with this keyword will never be exported.
544 An entry can be toggled between COMMENT and normal with
545 `\\[org-toggle-comment]'."))
548 ;;;; LaTeX Environments and Fragments
550 (defconst org-latex-regexps
551 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t
)
552 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
553 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
554 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil
)
555 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil
)
556 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil
)
557 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil
)
558 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil
))
559 "Regular expressions for matching embedded LaTeX.")
563 (defconst org-effort-property
"Effort"
564 "The property that is being used to keep track of effort estimates.
565 Effort estimates given in this property need to have the format H:MM.")
569 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
570 "Detect an org-type or table-type table.")
572 (defconst org-table-line-regexp
"^[ \t]*|"
573 "Detect an org-type table line.")
575 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
576 "Detect an org-type table line.")
578 (defconst org-table-hline-regexp
"^[ \t]*|-"
579 "Detect an org-type table hline.")
581 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
582 "Detect a table-type table hline.")
584 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
585 "Detect the first line outside a table when searching from within it.
586 This works for both table types.")
588 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
589 "Detect a #+TBLFM line.")
593 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
594 "Regular expression for fast time stamp matching.")
596 (defconst org-ts-regexp-inactive
597 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
598 "Regular expression for fast inactive time stamp matching.")
600 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
601 "Regular expression for fast time stamp matching.")
603 (defconst org-ts-regexp0
604 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
605 "Regular expression matching time strings for analysis.
606 This one does not require the space after the date, so it can be used
607 on a string that terminates immediately after the date.")
609 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
610 "Regular expression matching time strings for analysis.")
612 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
613 "Regular expression matching time stamps, with groups.")
615 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
616 "Regular expression matching time stamps (also [..]), with groups.")
618 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tr-regexp-both
622 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
623 "Regular expression matching a time stamp range.")
625 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
626 org-ts-regexp
"\\)?")
627 "Regular expression matching a time stamp or time stamp range.")
629 (defconst org-tsr-regexp-both
630 (concat org-ts-regexp-both
"\\(--?-?"
631 org-ts-regexp-both
"\\)?")
632 "Regular expression matching a time stamp or time stamp range.
633 The time stamps may be either active or inactive.")
635 (defconst org-repeat-re
636 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
637 "Regular expression for specifying repeated events.
638 After a match, group 1 contains the repeat expression.")
640 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
641 "Formats for `format-time-string' which are used for time stamps.")
644 ;;; The custom variables
647 "Outline-based notes management and organizer."
652 (defcustom org-mode-hook nil
653 "Mode hook for Org mode, run after the mode was turned on."
657 (defcustom org-load-hook nil
658 "Hook that is run after org.el has been loaded."
662 (defcustom org-log-buffer-setup-hook nil
663 "Hook that is run after an Org log buffer is created."
668 (defvar org-modules
) ; defined below
669 (defvar org-modules-loaded nil
670 "Have the modules been loaded already?")
672 (defun org-load-modules-maybe (&optional force
)
673 "Load all extensions listed in `org-modules'."
674 (when (or force
(not org-modules-loaded
))
675 (dolist (ext org-modules
)
676 (condition-case nil
(require ext
)
677 (error (message "Problems while trying to load feature `%s'" ext
))))
678 (setq org-modules-loaded t
)))
680 (defun org-set-modules (var value
)
681 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
683 (when (featurep 'org
)
684 (org-load-modules-maybe 'force
)
685 (org-element-cache-reset 'all
)))
687 (defcustom org-modules
'(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail
)
688 "Modules that should always be loaded together with org.el.
690 If a description starts with <C>, the file is not part of Emacs
691 and loading it will require that you have downloaded and properly
692 installed the Org mode distribution.
694 You can also use this system to load external packages (i.e. neither Org
695 core modules, nor modules from the CONTRIB directory). Just add symbols
696 to the end of the list. If the package is called org-xyz.el, then you need
697 to add the symbol `xyz', and the package must have a call to:
699 (provide \\='org-xyz)
701 For export specific modules, see also `org-export-backends'."
703 :set
'org-set-modules
705 :package-version
'(Org .
"8.0")
708 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
709 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
710 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
711 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
712 (const :tag
" docview: Links to doc-view buffers" org-docview
)
713 (const :tag
" eww: Store link to url of eww" org-eww
)
714 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
715 (const :tag
" habit: Track your consistency with habits" org-habit
)
716 (const :tag
" id: Global IDs for identifying entries" org-id
)
717 (const :tag
" info: Links to Info nodes" org-info
)
718 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
719 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
720 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
721 (const :tag
" mouse: Additional mouse support" org-mouse
)
722 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
723 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
724 (const :tag
" w3m: Special cut/paste from w3m to Org mode." org-w3m
)
726 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
727 (const :tag
"C bookmark: Org links to bookmarks" org-bookmark
)
728 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
729 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
730 (const :tag
"C collector: Collect properties into tables" org-collector
)
731 (const :tag
"C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
732 (const :tag
"C drill: Flashcards and spaced repetition for Org mode" org-drill
)
733 (const :tag
"C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol
)
734 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
735 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
736 (const :tag
"C eval: Include command output as text" org-eval
)
737 (const :tag
"C expiry: Expiry mechanism for Org entries" org-expiry
)
738 (const :tag
"C favtable: Lookup table of favorite references and links" org-favtable
)
739 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
740 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
741 (const :tag
"C invoice: Help manage client invoices in Org mode" org-invoice
)
742 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
743 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
744 (const :tag
"C mac-link: Grab links and url from various mac Applications" org-mac-link
)
745 (const :tag
"C mairix: Hook mairix search into Org for different MUAs" org-mairix
)
746 (const :tag
"C man: Support for links to manpages in Org mode" org-man
)
747 (const :tag
"C mew: Links to Mew folders/messages" org-mew
)
748 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
749 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
750 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
751 (const :tag
"C registry: A registry for Org links" org-registry
)
752 (const :tag
"C screen: Visit screen sessions through Org links" org-screen
)
753 (const :tag
"C secretary: Team management with Org" org-secretary
)
754 (const :tag
"C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert
)
755 (const :tag
"C toc: Table of contents for Org buffer" org-toc
)
756 (const :tag
"C track: Keep up with Org mode development" org-track
)
757 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
758 (const :tag
"C vm: Links to VM folders/messages" org-vm
)
759 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
760 (const :tag
"C wl: Links to Wanderlust folders/messages" org-wl
)
761 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
763 (defvar org-export-registered-backends
) ; From ox.el.
764 (declare-function org-export-derived-backend-p
"ox" (backend &rest backends
))
765 (declare-function org-export-backend-name
"ox" (backend) t
)
766 (defcustom org-export-backends
'(ascii html icalendar latex odt
)
767 "List of export back-ends that should be always available.
769 If a description starts with <C>, the file is not part of Emacs
770 and loading it will require that you have downloaded and properly
771 installed the Org mode distribution.
773 Unlike to `org-modules', libraries in this list will not be
774 loaded along with Org, but only once the export framework is
777 This variable needs to be set before org.el is loaded. If you
778 need to make a change while Emacs is running, use the customize
779 interface or run the following code, where VAL stands for the new
780 value of the variable, after updating it:
783 (setq org-export-registered-backends
786 (let ((name (org-export-backend-name backend)))
790 (and (org-export-derived-backend-p b name)
791 (throw \\='parentp t)))))))
792 org-export-registered-backends))
793 (let ((new-list (mapcar #\\='org-export-backend-name
794 org-export-registered-backends)))
795 (dolist (backend val)
797 ((not (load (format \"ox-%s\" backend) t t))
798 (message \"Problems while trying to load export back-end \\=`%s\\='\"
800 ((not (memq backend new-list)) (push backend new-list))))
801 (set-default \\='org-export-backends new-list)))
803 Adding a back-end to this list will also pull the back-end it
808 :package-version
'(Org .
"9.0")
809 :initialize
'custom-initialize-set
810 :set
(lambda (var val
)
811 (if (not (featurep 'ox
)) (set-default var val
)
812 ;; Any back-end not required anymore (not present in VAL and not
813 ;; a parent of any back-end in the new value) is removed from the
814 ;; list of registered back-ends.
815 (setq org-export-registered-backends
818 (let ((name (org-export-backend-name backend
)))
822 (and (org-export-derived-backend-p b name
)
823 (throw 'parentp t
)))))))
824 org-export-registered-backends
))
825 ;; Now build NEW-LIST of both new back-ends and required
827 (let ((new-list (mapcar #'org-export-backend-name
828 org-export-registered-backends
)))
829 (dolist (backend val
)
831 ((not (load (format "ox-%s" backend
) t t
))
832 (message "Problems while trying to load export back-end `%s'"
834 ((not (memq backend new-list
)) (push backend new-list
))))
835 ;; Set VAR to that list with fixed dependencies.
836 (set-default var new-list
))))
837 :type
'(set :greedy t
838 (const :tag
" ascii Export buffer to ASCII format" ascii
)
839 (const :tag
" beamer Export buffer to Beamer presentation" beamer
)
840 (const :tag
" html Export buffer to HTML format" html
)
841 (const :tag
" icalendar Export buffer to iCalendar format" icalendar
)
842 (const :tag
" latex Export buffer to LaTeX format" latex
)
843 (const :tag
" man Export buffer to MAN format" man
)
844 (const :tag
" md Export buffer to Markdown format" md
)
845 (const :tag
" odt Export buffer to ODT format" odt
)
846 (const :tag
" org Export buffer to Org format" org
)
847 (const :tag
" texinfo Export buffer to Texinfo format" texinfo
)
848 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
849 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
850 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
851 (const :tag
"C groff Export buffer to Groff format" groff
)
852 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
853 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
854 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
855 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
858 '(dolist (backend org-export-backends
)
859 (condition-case nil
(require (intern (format "ox-%s" backend
)))
860 (error (message "Problems while trying to load export back-end `%s'"
863 (defcustom org-support-shift-select nil
864 "Non-nil means make shift-cursor commands select text when possible.
867 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
868 start selecting a region, or enlarge regions started in this way.
869 In Org mode, in special contexts, these same keys are used for
870 other purposes, important enough to compete with shift selection.
871 Org tries to balance these needs by supporting `shift-select-mode'
872 outside these special contexts, under control of this variable.
874 The default of this variable is nil, to avoid confusing behavior. Shifted
875 cursor keys will then execute Org commands in the following contexts:
876 - on a headline, changing TODO state (left/right) and priority (up/down)
877 - on a time stamp, changing the time
878 - in a plain list item, changing the bullet type
879 - in a property definition line, switching between allowed values
880 - in the BEGIN line of a clock table (changing the time block).
881 Outside these contexts, the commands will throw an error.
883 When this variable is t and the cursor is not in a special
884 context, Org mode will support shift-selection for making and
885 enlarging regions. To make this more effective, the bullet
886 cycling will no longer happen anywhere in an item line, but only
887 if the cursor is exactly on the bullet.
889 If you set this variable to the symbol `always', then the keys
890 will not be special in headlines, property lines, and item lines,
891 to make shift selection work there as well. If this is what you
892 want, you can use the following alternative commands:
893 `\\[org-todo]' and `\\[org-priority]' \
894 to change TODO state and priority,
895 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
896 can be used to switch TODO sets,
897 `\\[org-ctrl-c-minus]' to cycle item bullet types,
898 and properties can be edited by hand or in column view.
900 However, when the cursor is on a timestamp, shift-cursor commands
901 will still edit the time stamp - this is just too good to give up."
904 (const :tag
"Never" nil
)
905 (const :tag
"When outside special context" t
)
906 (const :tag
"Everywhere except timestamps" always
)))
908 (defcustom org-loop-over-headlines-in-active-region nil
909 "Shall some commands act upon headlines in the active region?
911 When set to t, some commands will be performed in all headlines
912 within the active region.
914 When set to `start-level', some commands will be performed in all
915 headlines within the active region, provided that these headlines
916 are of the same level than the first one.
918 When set to a string, those commands will be performed on the
919 matching headlines within the active region. Such string must be
920 a tags/property/todo match as it is used in the agenda tags view.
922 The list of commands is: `org-schedule', `org-deadline',
923 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
924 `org-archive-to-archive-sibling'. The archiving commands skip
925 already archived entries."
926 :type
'(choice (const :tag
"Don't loop" nil
)
927 (const :tag
"All headlines in active region" t
)
928 (const :tag
"In active region, headlines at the same level than the first one" start-level
)
929 (string :tag
"Tags/Property/Todo matcher"))
934 (defgroup org-startup nil
935 "Options concerning startup of Org mode."
939 (defcustom org-startup-folded t
940 "Non-nil means entering Org mode will switch to OVERVIEW.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
945 #+STARTUP: fold (or `overview', this is equivalent)
946 #+STARTUP: nofold (or `showall', this is equivalent)
948 #+STARTUP: showeverything
950 Set `org-agenda-inhibit-startup' to a non-nil value if you want
951 to ignore this option when Org opens agenda files for the first
955 (const :tag
"nofold: show all" nil
)
956 (const :tag
"fold: overview" t
)
957 (const :tag
"content: all headlines" content
)
958 (const :tag
"show everything, even drawers" showeverything
)))
960 (defcustom org-startup-truncated t
961 "Non-nil means entering Org mode will set `truncate-lines'.
962 This is useful since some lines containing links can be very long and
963 uninteresting. Also tables look terrible when wrapped.
965 The variable `org-startup-truncated' allows to configure
966 truncation for Org mode different to the other modes that use the
967 variable `truncate-lines' and as a shortcut instead of putting
968 the variable `truncate-lines' into the `org-mode-hook'. If one
969 wants to configure truncation for Org mode not statically but
970 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
971 the variable `truncate-lines' has to be used because in such a
972 case it is too late to set the variable `org-startup-truncated'."
976 (defcustom org-startup-indented nil
977 "Non-nil means turn on `org-indent-mode' on startup.
978 This can also be configured on a per-file basis by adding one of
979 the following lines anywhere in the buffer:
983 :group
'org-structure
985 (const :tag
"Not" nil
)
986 (const :tag
"Globally (slow on startup in large files)" t
)))
988 (defcustom org-use-sub-superscripts t
989 "Non-nil means interpret \"_\" and \"^\" for display.
991 If you want to control how Org exports those characters, see
992 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
993 used to be an alias for `org-export-with-sub-superscripts' in
994 Org <8.0, it is not anymore.
996 When this option is turned on, you can use TeX-like syntax for
997 sub- and superscripts within the buffer. Several characters after
998 \"_\" or \"^\" will be considered as a single item - so grouping
999 with {} is normally not needed. For example, the following things
1000 will be parsed as single sub- or superscripts:
1002 10^24 or 10^tau several digits will be considered 1 item.
1003 10^-12 or 10^-tau a leading sign with digits or a word
1004 x^2-y^3 will be read as x^2 - y^3, because items are
1005 terminated by almost any nonword/nondigit char.
1006 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1008 Still, ambiguity is possible. So when in doubt, use {} to enclose
1009 the sub/superscript. If you set this variable to the symbol `{}',
1010 the braces are *required* in order to trigger interpretations as
1011 sub/superscript. This can be helpful in documents that need \"_\"
1012 frequently in plain text."
1015 :package-version
'(Org .
"8.0")
1017 (const :tag
"Always interpret" t
)
1018 (const :tag
"Only with braces" {})
1019 (const :tag
"Never interpret" nil
)))
1021 (defcustom org-startup-with-beamer-mode nil
1022 "Non-nil means turn on `org-beamer-mode' on startup.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1031 (defcustom org-startup-align-all-tables nil
1032 "Non-nil means align all tables when visiting a file.
1033 This is useful when the column width in tables is forced with <N> cookies
1034 in table fields. Such tables will look correct only after the first re-align.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1042 (defcustom org-startup-with-inline-images nil
1043 "Non-nil means show inline images when loading a new Org file.
1044 This can also be configured on a per-file basis by adding one of
1045 the following lines anywhere in the buffer:
1046 #+STARTUP: inlineimages
1047 #+STARTUP: noinlineimages"
1052 (defcustom org-startup-with-latex-preview nil
1053 "Non-nil means preview LaTeX fragments when loading a new Org file.
1055 This can also be configured on a per-file basis by adding one of
1056 the following lines anywhere in the buffer:
1057 #+STARTUP: latexpreview
1058 #+STARTUP: nolatexpreview"
1061 :package-version
'(Org .
"8.0")
1064 (defcustom org-insert-mode-line-in-empty-file nil
1065 "Non-nil means insert the first line setting Org mode in empty files.
1066 When the function `org-mode' is called interactively in an empty file, this
1067 normally means that the file name does not automatically trigger Org mode.
1068 To ensure that the file will always be in Org mode in the future, a
1069 line enforcing Org mode will be inserted into the buffer, if this option
1074 (defcustom org-replace-disputed-keys nil
1075 "Non-nil means use alternative key bindings for some keys.
1076 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1077 These keys are also used by other packages like shift-selection-mode'
1078 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1079 If you want to use Org mode together with one of these other modes,
1080 or more generally if you would like to move some Org mode commands to
1081 other keys, set this variable and configure the keys with the variable
1082 `org-disputed-keys'.
1084 This option is only relevant at load-time of Org mode, and must be set
1085 *before* org.el is loaded. Changing it requires a restart of Emacs to
1090 (defcustom org-use-extra-keys nil
1091 "Non-nil means use extra key sequence definitions for certain commands.
1092 This happens automatically if `window-system' is nil. This
1093 variable lets you do the same manually. You must set it before
1098 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
1100 (defcustom org-disputed-keys
1101 '(([(shift up
)] .
[(meta p
)])
1102 ([(shift down
)] .
[(meta n
)])
1103 ([(shift left
)] .
[(meta -
)])
1104 ([(shift right
)] .
[(meta +)])
1105 ([(control shift right
)] .
[(meta shift
+)])
1106 ([(control shift left
)] .
[(meta shift -
)]))
1107 "Keys for which Org mode and other modes compete.
1108 This is an alist, cars are the default keys, second element specifies
1109 the alternative to use when `org-replace-disputed-keys' is t.
1111 Keys can be specified in any syntax supported by `define-key'.
1112 The value of this option takes effect only at Org mode startup,
1113 therefore you'll have to restart Emacs to apply it after changing."
1117 (defun org-key (key)
1118 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1119 Or return the original if not disputed."
1120 (when org-replace-disputed-keys
1121 (let* ((nkey (key-description key
))
1122 (x (cl-find-if (lambda (x) (equal (key-description (car x
)) nkey
))
1123 org-disputed-keys
)))
1124 (setq key
(if x
(cdr x
) key
))))
1127 (defun org-defkey (keymap key def
)
1128 "Define a key, possibly translated, as returned by `org-key'."
1129 (define-key keymap
(org-key key
) def
))
1131 (defcustom org-ellipsis nil
1132 "The ellipsis to use in the Org mode outline.
1134 When nil, just use the standard three dots. When a non-empty string,
1135 use that string instead.
1137 The change affects only Org mode (which will then use its own display table).
1138 Changing this requires executing `\\[org-mode]' in a buffer to become
1141 :type
'(choice (const :tag
"Default" nil
)
1142 (string :tag
"String" :value
"...#"))
1143 :safe
(lambda (v) (and (string-or-null-p v
) (not (equal "" v
)))))
1145 (defvar org-display-table nil
1146 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1148 (defgroup org-keywords nil
1149 "Keywords in Org mode."
1153 (defcustom org-closed-keep-when-no-todo nil
1154 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1156 :group
'org-keywords
1158 :package-version
'(Org .
"8.0")
1161 (defgroup org-structure nil
1162 "Options concerning the general structure of Org files."
1163 :tag
"Org Structure"
1166 (defgroup org-reveal-location nil
1167 "Options about how to make context of a location visible."
1168 :tag
"Org Reveal Location"
1169 :group
'org-structure
)
1171 (defcustom org-show-context-detail
'((agenda . local
)
1172 (bookmark-jump . lineage
)
1174 (default . ancestors
))
1175 "Alist between context and visibility span when revealing a location.
1177 \\<org-mode-map>Some actions may move point into invisible
1178 locations. As a consequence, Org always expose a neighborhood
1179 around point. How much is shown depends on the initial action,
1180 or context. Valid contexts are
1182 agenda when exposing an entry from the agenda
1183 org-goto when using the command `org-goto' (`\\[org-goto]')
1184 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1185 tags-tree when constructing a sparse tree based on tags matches
1186 link-search when exposing search matches associated with a link
1187 mark-goto when exposing the jump goal of a mark
1188 bookmark-jump when exposing a bookmark location
1189 isearch when exiting from an incremental search
1190 default default for all contexts not set explicitly
1192 Allowed visibility spans are
1194 minimal show current headline; if point is not on headline,
1197 local show current headline, entry and next headline
1199 ancestors show current headline and its direct ancestors; if
1200 point is not on headline, also show entry
1202 lineage show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and first child
1206 tree show current headline, its direct ancestors and all
1207 their children; if point is not on headline, also show
1208 entry and all children
1210 canonical show current headline, its direct ancestors along with
1211 their entries and children; if point is not located on
1212 the headline, also show current entry and all children
1214 As special cases, a nil or t value means show all contexts in
1215 `minimal' or `canonical' view, respectively.
1217 Some views can make displayed information very compact, but also
1218 make it harder to edit the location of the match. In such
1219 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1221 :group
'org-reveal-location
1223 :package-version
'(Org .
"9.0")
1225 (const :tag
"Canonical" t
)
1226 (const :tag
"Minimal" nil
)
1227 (repeat :greedy t
:tag
"Individual contexts"
1229 (choice :tag
"Context"
1236 (const bookmark-jump
)
1239 (choice :tag
"Detail level"
1245 (const canonical
))))))
1247 (defcustom org-indirect-buffer-display
'other-window
1248 "How should indirect tree buffers be displayed?
1250 This applies to indirect buffers created with the commands
1251 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1254 current-window Display in the current window
1255 other-window Just display in another window.
1256 dedicated-frame Create one new frame, and re-use it each time.
1257 new-frame Make a new frame each time. Note that in this case
1258 previously-made indirect buffers are kept, and you need to
1259 kill these buffers yourself."
1260 :group
'org-structure
1261 :group
'org-agenda-windows
1263 (const :tag
"In current window" current-window
)
1264 (const :tag
"In current frame, other window" other-window
)
1265 (const :tag
"Each time a new frame" new-frame
)
1266 (const :tag
"One dedicated frame" dedicated-frame
)))
1268 (defcustom org-use-speed-commands nil
1269 "Non-nil means activate single letter commands at beginning of a headline.
1270 This may also be a function to test for appropriate locations where speed
1271 commands should be active.
1273 For example, to activate speed commands when the point is on any
1274 star at the beginning of the headline, you can do this:
1276 (setq org-use-speed-commands
1277 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1278 :group
'org-structure
1280 (const :tag
"Never" nil
)
1281 (const :tag
"At beginning of headline stars" t
)
1284 (defcustom org-speed-commands-user nil
1285 "Alist of additional speed commands.
1286 This list will be checked before `org-speed-commands-default'
1287 when the variable `org-use-speed-commands' is non-nil
1288 and when the cursor is at the beginning of a headline.
1289 The car of each entry is a string with a single letter, which must
1290 be assigned to `self-insert-command' in the global map.
1291 The cdr is either a command to be called interactively, a function
1292 to be called, or a form to be evaluated.
1293 An entry that is just a list with a single string will be interpreted
1294 as a descriptive headline that will be added when listing the speed
1295 commands in the Help buffer using the `?' speed command."
1296 :group
'org-structure
1297 :type
'(repeat :value
("k" . ignore
)
1298 (choice :value
("k" . ignore
)
1299 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
1300 (cons :tag
"Letter and Command"
1301 (string :tag
"Command letter")
1306 (defcustom org-bookmark-names-plist
1307 '(:last-capture
"org-capture-last-stored"
1308 :last-refile
"org-refile-last-stored"
1309 :last-capture-marker
"org-capture-last-stored-marker")
1310 "Names for bookmarks automatically set by some Org commands.
1311 This can provide strings as names for a number of bookmarks Org sets
1312 automatically. The following keys are currently implemented:
1314 :last-capture-marker
1316 When a key does not show up in the property list, the corresponding bookmark
1318 :group
'org-structure
1321 (defgroup org-cycle nil
1322 "Options concerning visibility cycling in Org mode."
1324 :group
'org-structure
)
1326 (defcustom org-cycle-skip-children-state-if-no-children t
1327 "Non-nil means skip CHILDREN state in entries that don't have any."
1331 (defcustom org-cycle-max-level nil
1332 "Maximum level which should still be subject to visibility cycling.
1333 Levels higher than this will, for cycling, be treated as text, not a headline.
1334 When `org-odd-levels-only' is set, a value of N in this variable actually
1335 means 2N-1 stars as the limiting headline.
1336 When nil, cycle all levels.
1337 Note that the limiting level of cycling is also influenced by
1338 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1339 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1343 (const :tag
"No limit" nil
)
1344 (integer :tag
"Maximum level")))
1346 (defcustom org-hide-block-startup nil
1347 "Non-nil means entering Org mode will fold all blocks.
1348 This can also be set in on a per-file basis with
1350 #+STARTUP: hideblocks
1351 #+STARTUP: showblocks"
1356 (defcustom org-cycle-global-at-bob nil
1357 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1359 This makes it possible to do global cycling without having to use `S-TAB'
1360 or `\\[universal-argument] TAB'. For this special case to work, the first \
1362 must not be a headline -- it may be empty or some other text.
1364 When used in this way, `org-cycle-hook' is disabled temporarily to make
1365 sure the cursor stays at the beginning of the buffer.
1367 When this option is nil, don't do anything special at the beginning of
1372 (defcustom org-cycle-level-after-item
/entry-creation t
1373 "Non-nil means cycle entry level or item indentation in new empty entries.
1375 When the cursor is at the end of an empty headline, i.e., with only stars
1376 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1377 and then all possible ancestor states, before returning to the original state.
1378 This makes data entry extremely fast: M-RET to create a new headline,
1379 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1381 When the cursor is at the end of an empty plain list item, one TAB will
1382 make it a subitem, two or more tabs will back up to make this an item
1383 higher up in the item hierarchy."
1387 (defcustom org-cycle-emulate-tab t
1388 "Where should `org-cycle' emulate TAB.
1390 white Only in completely white lines
1391 whitestart Only at the beginning of lines, before the first non-white char
1392 t Everywhere except in headlines
1393 exc-hl-bol Everywhere except at the start of a headline
1394 If TAB is used in a place where it does not emulate TAB, the current subtree
1395 visibility is cycled."
1397 :type
'(choice (const :tag
"Never" nil
)
1398 (const :tag
"Only in completely white lines" white
)
1399 (const :tag
"Before first char in a line" whitestart
)
1400 (const :tag
"Everywhere except in headlines" t
)
1401 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)))
1403 (defcustom org-cycle-separator-lines
2
1404 "Number of empty lines needed to keep an empty line between collapsed trees.
1405 If you leave an empty line between the end of a subtree and the following
1406 headline, this empty line is hidden when the subtree is folded.
1407 Org mode will leave (exactly) one empty line visible if the number of
1408 empty lines is equal or larger to the number given in this variable.
1409 So the default 2 means at least 2 empty lines after the end of a subtree
1410 are needed to produce free space between a collapsed subtree and the
1413 If the number is negative, and the number of empty lines is at least -N,
1414 all empty lines are shown.
1416 Special case: when 0, never leave empty lines in collapsed view."
1419 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1421 (defcustom org-pre-cycle-hook nil
1422 "Hook that is run before visibility cycling is happening.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that will be set right after running this hook. The
1425 argument is a symbol. Before a global state change, it can have the values
1426 `overview', `content', or `all'. Before a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1431 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1432 org-cycle-hide-drawers
1433 org-cycle-show-empty-lines
1434 org-optimize-window-after-visibility-change
)
1435 "Hook that is run after `org-cycle' has changed the buffer visibility.
1436 The function(s) in this hook must accept a single argument which indicates
1437 the new state that was set by the most recent `org-cycle' command. The
1438 argument is a symbol. After a global state change, it can have the values
1439 `overview', `contents', or `all'. After a local state change, it can have
1440 the values `folded', `children', or `subtree'."
1444 :package-version
'(Org .
"8.3"))
1446 (defgroup org-edit-structure nil
1447 "Options concerning structure editing in Org mode."
1448 :tag
"Org Edit Structure"
1449 :group
'org-structure
)
1451 (defcustom org-odd-levels-only nil
1452 "Non-nil means skip even levels and only use odd levels for the outline.
1453 This has the effect that two stars are being added/taken away in
1454 promotion/demotion commands. It also influences how levels are
1455 handled by the exporters.
1456 Changing it requires restart of `font-lock-mode' to become effective
1457 for fontification also in regions already fontified.
1458 You may also set this on a per-file basis by adding one of the following
1459 lines to the buffer:
1463 :group
'org-edit-structure
1464 :group
'org-appearance
1467 (defcustom org-adapt-indentation t
1468 "Non-nil means adapt indentation to outline node level.
1470 When this variable is set, Org assumes that you write outlines by
1471 indenting text in each node to align with the headline (after the
1472 stars). The following issues are influenced by this variable:
1474 - The indentation is increased by one space in a demotion
1475 command, and decreased by one in a promotion command. However,
1476 in the latter case, if shifting some line in the entry body
1477 would alter document structure (e.g., insert a new headline),
1478 indentation is not changed at all.
1480 - Property drawers and planning information is inserted indented
1481 when this variable is set. When nil, they will not be indented.
1483 - TAB indents a line relative to current level. The lines below
1484 a headline will be indented when this variable is set.
1486 Note that this is all about true indentation, by adding and
1487 removing space characters. See also `org-indent.el' which does
1488 level-dependent indentation in a virtual way, i.e. at display
1490 :group
'org-edit-structure
1493 (defcustom org-special-ctrl-a
/e nil
1494 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1496 When t, `C-a' will bring back the cursor to the beginning of the
1497 headline text, i.e. after the stars and after a possible TODO
1498 keyword. In an item, this will be the position after bullet and
1499 check-box, if any. When the cursor is already at that position,
1500 another `C-a' will bring it to the beginning of the line.
1502 `C-e' will jump to the end of the headline, ignoring the presence
1503 of tags in the headline. A second `C-e' will then jump to the
1504 true end of the line, after any tags. This also means that, when
1505 this variable is non-nil, `C-e' also will never jump beyond the
1506 end of the heading of a folded section, i.e. not after the
1509 When set to the symbol `reversed', the first `C-a' or `C-e' works
1510 normally, going to the true line boundary first. Only a directly
1511 following, identical keypress will bring the cursor to the
1514 This may also be a cons cell where the behavior for `C-a' and
1515 `C-e' is set separately."
1516 :group
'org-edit-structure
1518 (const :tag
"off" nil
)
1519 (const :tag
"on: after stars/bullet and before tags first" t
)
1520 (const :tag
"reversed: true line boundary first" reversed
)
1521 (cons :tag
"Set C-a and C-e separately"
1522 (choice :tag
"Special C-a"
1523 (const :tag
"off" nil
)
1524 (const :tag
"on: after stars/bullet first" t
)
1525 (const :tag
"reversed: before stars/bullet first" reversed
))
1526 (choice :tag
"Special C-e"
1527 (const :tag
"off" nil
)
1528 (const :tag
"on: before tags first" t
)
1529 (const :tag
"reversed: after tags first" reversed
)))))
1530 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1532 (defcustom org-special-ctrl-k nil
1533 "Non-nil means `C-k' will behave specially in headlines.
1534 When nil, `C-k' will call the default `kill-line' command.
1535 When t, the following will happen while the cursor is in the headline:
1537 - When the cursor is at the beginning of a headline, kill the entire
1538 line and possible the folded subtree below the line.
1539 - When in the middle of the headline text, kill the headline up to the tags.
1540 - When after the headline text, kill the tags."
1541 :group
'org-edit-structure
1544 (defcustom org-ctrl-k-protect-subtree nil
1545 "Non-nil means, do not delete a hidden subtree with C-k.
1546 When set to the symbol `error', simply throw an error when C-k is
1547 used to kill (part-of) a headline that has hidden text behind it.
1548 Any other non-nil value will result in a query to the user, if it is
1549 OK to kill that hidden subtree. When nil, kill without remorse."
1550 :group
'org-edit-structure
1553 (const :tag
"Do not protect hidden subtrees" nil
)
1554 (const :tag
"Protect hidden subtrees with a security query" t
)
1555 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1557 (defcustom org-special-ctrl-o t
1558 "Non-nil means, make `C-o' insert a row in tables."
1559 :group
'org-edit-structure
1562 (defcustom org-catch-invisible-edits nil
1563 "Check if in invisible region before inserting or deleting a character.
1566 nil Do not check, so just do invisible edits.
1567 error Throw an error and do nothing.
1568 show Make point visible, and do the requested edit.
1569 show-and-error Make point visible, then throw an error and abort the edit.
1570 smart Make point visible, and do insertion/deletion if it is
1571 adjacent to visible text and the change feels predictable.
1572 Never delete a previously invisible character or add in the
1573 middle or right after an invisible region. Basically, this
1574 allows insertion and backward-delete right before ellipses.
1575 FIXME: maybe in this case we should not even show?"
1576 :group
'org-edit-structure
1579 (const :tag
"Do not check" nil
)
1580 (const :tag
"Throw error when trying to edit" error
)
1581 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1582 (const :tag
"Show invisible part and do the edit" show
)
1583 (const :tag
"Be smart and do the right thing" smart
)))
1585 (defcustom org-yank-folded-subtrees t
1586 "Non-nil means when yanking subtrees, fold them.
1587 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1588 it starts with a heading and all other headings in it are either children
1589 or siblings, then fold all the subtrees. However, do this only if no
1590 text after the yank would be swallowed into a folded tree by this action."
1591 :group
'org-edit-structure
1594 (defcustom org-yank-adjusted-subtrees nil
1595 "Non-nil means when yanking subtrees, adjust the level.
1596 With this setting, `org-paste-subtree' is used to insert the subtree, see
1597 this function for details."
1598 :group
'org-edit-structure
1601 (defcustom org-M-RET-may-split-line
'((default . t
))
1602 "Non-nil means M-RET will split the line at the cursor position.
1603 When nil, it will go to the end of the line before making a
1605 You may also set this option in a different way for different
1606 contexts. Valid contexts are:
1608 headline when creating a new headline
1609 item when creating a new item
1610 table in a table field
1611 default the value to be used for all contexts not explicitly
1613 :group
'org-structure
1616 (const :tag
"Always" t
)
1617 (const :tag
"Never" nil
)
1618 (repeat :greedy t
:tag
"Individual contexts"
1620 (choice :tag
"Context"
1628 (defcustom org-insert-heading-respect-content nil
1629 "Non-nil means insert new headings after the current subtree.
1631 When nil, the new heading is created directly after the current line.
1632 The commands `\\[org-insert-heading-respect-content]' and \
1633 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1634 for the duration of the command."
1635 :group
'org-structure
1638 (defcustom org-blank-before-new-entry
'((heading . auto
)
1639 (plain-list-item . auto
))
1640 "Should `org-insert-heading' leave a blank line before new heading/item?
1641 The value is an alist, with `heading' and `plain-list-item' as CAR,
1642 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1643 which case Org will look at the surrounding headings/items and try to
1644 make an intelligent decision whether to insert a blank line or not."
1645 :group
'org-edit-structure
1647 (cons (const heading
)
1648 (choice (const :tag
"Never" nil
)
1649 (const :tag
"Always" t
)
1650 (const :tag
"Auto" auto
)))
1651 (cons (const plain-list-item
)
1652 (choice (const :tag
"Never" nil
)
1653 (const :tag
"Always" t
)
1654 (const :tag
"Auto" auto
)))))
1656 (defcustom org-insert-heading-hook nil
1657 "Hook being run after inserting a new heading."
1658 :group
'org-edit-structure
1661 (defcustom org-enable-fixed-width-editor t
1662 "Non-nil means lines starting with \":\" are treated as fixed-width.
1663 This currently only means they are never auto-wrapped.
1664 When nil, such lines will be treated like ordinary lines."
1665 :group
'org-edit-structure
1668 (defcustom org-goto-auto-isearch t
1669 "Non-nil means typing characters in `org-goto' starts incremental search.
1670 When nil, you can use these keybindings to navigate the buffer:
1672 q Quit the org-goto interface
1673 n Go to the next visible heading
1674 p Go to the previous visible heading
1675 f Go one heading forward on same level
1676 b Go one heading backward on same level
1677 u Go one heading up"
1678 :group
'org-edit-structure
1681 (defgroup org-sparse-trees nil
1682 "Options concerning sparse trees in Org mode."
1683 :tag
"Org Sparse Trees"
1684 :group
'org-structure
)
1686 (defcustom org-highlight-sparse-tree-matches t
1687 "Non-nil means highlight all matches that define a sparse tree.
1688 The highlights will automatically disappear the next time the buffer is
1689 changed by an edit command."
1690 :group
'org-sparse-trees
1693 (defcustom org-remove-highlights-with-change t
1694 "Non-nil means any change to the buffer will remove temporary highlights.
1696 Such highlights are created by `org-occur' and `org-clock-display'.
1697 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1698 to get rid of the highlights.
1699 The highlights created by `org-toggle-latex-fragment' always need
1700 `\\[org-toggle-latex-fragment]' to be removed."
1701 :group
'org-sparse-trees
1705 (defcustom org-occur-case-fold-search t
1706 "Non-nil means `org-occur' should be case-insensitive.
1707 If set to `smart' the search will be case-insensitive only if it
1708 doesn't specify any upper case character."
1709 :group
'org-sparse-trees
1712 (const :tag
"Case-sensitive" nil
)
1713 (const :tag
"Case-insensitive" t
)
1714 (const :tag
"Case-insensitive for lower case searches only" smart
)))
1716 (defcustom org-occur-hook
'(org-first-headline-recenter)
1717 "Hook that is run after `org-occur' has constructed a sparse tree.
1718 This can be used to recenter the window to show as much of the structure
1720 :group
'org-sparse-trees
1723 (defgroup org-imenu-and-speedbar nil
1724 "Options concerning imenu and speedbar in Org mode."
1725 :tag
"Org Imenu and Speedbar"
1726 :group
'org-structure
)
1728 (defcustom org-imenu-depth
2
1729 "The maximum level for Imenu access to Org headlines.
1730 This also applied for speedbar access."
1731 :group
'org-imenu-and-speedbar
1734 (defgroup org-table nil
1735 "Options concerning tables in Org mode."
1739 (defcustom org-self-insert-cluster-for-undo nil
1740 "Non-nil means cluster self-insert commands for undo when possible.
1741 If this is set, then, like in the Emacs command loop, 20 consecutive
1742 characters will be undone together.
1743 This is configurable, because there is some impact on typing performance."
1747 (defcustom org-table-tab-recognizes-table.el t
1748 "Non-nil means TAB will automatically notice a table.el table.
1749 When it sees such a table, it moves point into it and - if necessary -
1750 calls `table-recognize-table'."
1751 :group
'org-table-editing
1754 (defgroup org-link nil
1755 "Options concerning links in Org mode."
1759 (defvar-local org-link-abbrev-alist-local nil
1760 "Buffer-local version of `org-link-abbrev-alist', which see.
1761 The value of this is taken from the #+LINK lines.")
1763 (defcustom org-link-parameters
1764 '(("doi" :follow org--open-doi-link
)
1765 ("elisp" :follow org--open-elisp-link
)
1766 ("file" :complete org-file-complete-link
)
1767 ("ftp" :follow
(lambda (path) (browse-url (concat "ftp:" path
))))
1768 ("help" :follow org--open-help-link
)
1769 ("http" :follow
(lambda (path) (browse-url (concat "http:" path
))))
1770 ("https" :follow
(lambda (path) (browse-url (concat "https:" path
))))
1771 ("mailto" :follow
(lambda (path) (browse-url (concat "mailto:" path
))))
1772 ("news" :follow
(lambda (path) (browse-url (concat "news:" path
))))
1773 ("shell" :follow org--open-shell-link
))
1774 "An alist of properties that defines all the links in Org mode.
1775 The key in each association is a string of the link type.
1776 Subsequent optional elements make up a p-list of link properties.
1778 :follow - A function that takes the link path as an argument.
1780 :export - A function that takes the link path, description and
1781 export-backend as arguments.
1783 :store - A function responsible for storing the link. See the
1784 function `org-store-link-functions'.
1786 :complete - A function that inserts a link with completion. The
1787 function takes one optional prefix arg.
1789 :face - A face for the link, or a function that returns a face.
1790 The function takes one argument which is the link path. The
1791 default face is `org-link'.
1793 :mouse-face - The mouse-face. The default is `highlight'.
1795 :display - `full' will not fold the link in descriptive
1796 display. Default is `org-link'.
1798 :help-echo - A string or function that takes (window object position)
1799 as arguments and returns a string.
1801 :keymap - A keymap that is active on the link. The default is
1804 :htmlize-link - A function for the htmlize-link. Defaults
1805 to (list :uri \"type:path\")
1807 :activate-func - A function to run at the end of font-lock
1808 activation. The function must accept (link-start link-end path bracketp)
1811 :type
'(alist :tag
"Link display parameters"
1814 :package-version
'(Org .
"9.1"))
1816 (defun org-link-get-parameter (type key
)
1817 "Get TYPE link property for KEY.
1818 TYPE is a string and KEY is a plist keyword."
1820 (cdr (assoc type org-link-parameters
))
1823 (defun org-link-set-parameters (type &rest parameters
)
1824 "Set link TYPE properties to PARAMETERS.
1825 PARAMETERS should be :key val pairs."
1826 (let ((data (assoc type org-link-parameters
)))
1827 (if data
(setcdr data
(org-combine-plists (cdr data
) parameters
))
1828 (push (cons type parameters
) org-link-parameters
)
1829 (org-make-link-regexps)
1830 (org-element-update-syntax))))
1832 (defun org-link-types ()
1833 "Return a list of known link types."
1834 (mapcar #'car org-link-parameters
))
1836 (defcustom org-link-abbrev-alist nil
1837 "Alist of link abbreviations.
1838 The car of each element is a string, to be replaced at the start of a link.
1839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1840 links in Org buffers can have an optional tag after a double colon, e.g.,
1842 [[linkkey:tag][description]]
1844 The `linkkey' must be a single word, starting with a letter, followed
1845 by letters, numbers, `-' or `_'.
1847 If REPLACE is a string, the tag will simply be appended to create the link.
1848 If the string contains \"%s\", the tag will be inserted there. If the string
1849 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1850 at that point (see the function `url-hexify-string'). If the string contains
1851 the specifier \"%(my-function)\", then the custom function `my-function' will
1852 be invoked: this function takes the tag as its only argument and must return
1855 REPLACE may also be a function that will be called with the tag as the
1856 only argument to create the link, which should be returned as a string.
1858 See the manual for examples."
1862 (string :tag
"Protocol")
1864 (string :tag
"Format")
1867 (defcustom org-descriptive-links t
1868 "Non-nil means Org will display descriptive links.
1869 E.g. [[http://orgmode.org][Org website]] will be displayed as
1870 \"Org Website\", hiding the link itself and just displaying its
1871 description. When set to nil, Org will display the full links
1874 You can interactively set the value of this variable by calling
1875 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1879 (defcustom org-link-file-path-type
'adaptive
1880 "How the path name in file links should be stored.
1883 relative Relative to the current directory, i.e. the directory of the file
1884 into which the link is being inserted.
1885 absolute Absolute path, if possible with ~ for home directory.
1886 noabbrev Absolute path, no abbreviation of home directory.
1887 adaptive Use relative path for files in the current directory and sub-
1888 directories of it. For other files, use an absolute path."
1896 (defvaralias 'org-activate-links
'org-highlight-links
)
1897 (defcustom org-highlight-links
'(bracket angle plain radio tag date footnote
)
1898 "Types of links that should be highlighted in Org files.
1900 This is a list of symbols, each one of them leading to the
1901 highlighting of a certain link type.
1903 You can still open links that are not highlighted.
1905 In principle, it does not hurt to turn on highlighting for all
1906 link types. There may be a small gain when turning off unused
1907 link types. The types are:
1909 bracket The recommended [[link][description]] or [[link]] links with hiding.
1910 angle Links in angular brackets that may contain whitespace like
1911 <bbdb:Carsten Dominik>.
1912 plain Plain links in normal text, no whitespace, like http://google.com.
1913 radio Text that is matched by a radio target, see manual for details.
1914 tag Tag settings in a headline (link to tag search).
1915 date Time stamps (link to calendar).
1916 footnote Footnote labels.
1918 If you set this variable during an Emacs session, use `org-mode-restart'
1919 in the Org buffer so that the change takes effect."
1921 :group
'org-appearance
1922 :type
'(set :greedy t
1923 (const :tag
"Double bracket links" bracket
)
1924 (const :tag
"Angular bracket links" angle
)
1925 (const :tag
"Plain text links" plain
)
1926 (const :tag
"Radio target matches" radio
)
1927 (const :tag
"Tags" tag
)
1928 (const :tag
"Timestamps" date
)
1929 (const :tag
"Footnotes" footnote
)))
1931 (defcustom org-make-link-description-function nil
1932 "Function to use for generating link descriptions from links.
1933 This function must take two parameters: the first one is the
1934 link, the second one is the description generated by
1935 `org-insert-link'. The function should return the description to
1938 :type
'(choice (const nil
) (function)))
1940 (defgroup org-link-store nil
1941 "Options concerning storing links in Org mode."
1942 :tag
"Org Store Link"
1945 (defcustom org-url-hexify-p t
1946 "When non-nil, hexify URL when creating a link."
1949 :group
'org-link-store
)
1951 (defcustom org-email-link-description-format
"Email %c: %.30s"
1952 "Format of the description part of a link to an email or usenet message.
1953 The following %-escapes will be replaced by corresponding information:
1955 %F full \"From\" field
1956 %f name, taken from \"From\" field, address if no name
1957 %T full \"To\" field
1958 %t first name in \"To\" field, address if no name
1959 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1960 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1965 You may use normal field width specification between the % and the letter.
1966 This is for example useful to limit the length of the subject.
1968 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1969 :group
'org-link-store
1972 (defcustom org-from-is-user-regexp
1974 (when (and user-mail-address
(not (string= user-mail-address
"")))
1975 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1976 (when (and user-full-name
(not (string= user-full-name
"")))
1977 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1978 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1979 "Regexp matched against the \"From:\" header of an email or usenet message.
1980 It should match if the message is from the user him/herself."
1981 :group
'org-link-store
1984 (defcustom org-context-in-file-links t
1985 "Non-nil means file links from `org-store-link' contain context.
1987 A search string will be added to the file name with :: as separator
1988 and used to find the context when the link is activated by the command
1989 `org-open-at-point'. When this option is t, the entire active region
1990 will be placed in the search string of the file link. If set to a
1991 positive integer, only the first n lines of context will be stored.
1993 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1994 \\[org-store-link]')
1995 negates this setting for the duration of the command."
1996 :group
'org-link-store
1997 :type
'(choice boolean integer
))
1999 (defcustom org-keep-stored-link-after-insertion nil
2000 "Non-nil means keep link in list for entire session.
2002 The command `org-store-link' adds a link pointing to the current
2003 location to an internal list. These links accumulate during a session.
2004 The command `org-insert-link' can be used to insert links into any
2005 Org file (offering completion for all stored links).
2007 When this option is nil, every link which has been inserted once using
2008 `\\[org-insert-link]' will be removed from the list, to make completing the \
2010 links more efficient."
2011 :group
'org-link-store
2014 (defgroup org-link-follow nil
2015 "Options concerning following links in Org mode."
2016 :tag
"Org Follow Link"
2019 (defcustom org-link-translation-function nil
2020 "Function to translate links with different syntax to Org syntax.
2021 This can be used to translate links created for example by the Planner
2022 or emacs-wiki packages to Org syntax.
2023 The function must accept two parameters, a TYPE containing the link
2024 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2025 which is everything after the link protocol. It should return a cons
2026 with possibly modified values of type and path.
2027 Org contains a function for this, so if you set this variable to
2028 `org-translate-link-from-planner', you should be able follow many
2029 links created by planner."
2030 :group
'org-link-follow
2031 :type
'(choice (const nil
) (function)))
2033 (defcustom org-follow-link-hook nil
2034 "Hook that is run after a link has been followed."
2035 :group
'org-link-follow
2038 (defcustom org-tab-follows-link nil
2039 "Non-nil means on links TAB will follow the link.
2040 Needs to be set before org.el is loaded.
2041 This really should not be used, it does not make sense, and the
2042 implementation is bad."
2043 :group
'org-link-follow
2046 (defcustom org-return-follows-link nil
2047 "Non-nil means on links RET will follow the link.
2048 In tables, the special behavior of RET has precedence."
2049 :group
'org-link-follow
2052 (defcustom org-mouse-1-follows-link
2053 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
2054 "Non-nil means mouse-1 on a link will follow the link.
2055 A longer mouse click will still set point. Needs to be set
2056 before org.el is loaded."
2057 :group
'org-link-follow
2059 :package-version
'(Org .
"8.3")
2061 (const :tag
"A double click follows the link" double
)
2062 (const :tag
"Unconditionally follow the link with mouse-1" t
)
2063 (integer :tag
"mouse-1 click does not follow the link if longer than N ms" 450)))
2065 (defcustom org-mark-ring-length
4
2066 "Number of different positions to be recorded in the ring.
2067 Changing this requires a restart of Emacs to work correctly."
2068 :group
'org-link-follow
2071 (defcustom org-link-search-must-match-exact-headline
'query-to-create
2072 "Non-nil means internal fuzzy links can only match headlines.
2074 When nil, the a fuzzy link may point to a target or a named
2075 construct in the document. When set to the special value
2076 `query-to-create', offer to create a new headline when none
2079 Spaces and statistics cookies are ignored during heading searches."
2080 :group
'org-link-follow
2083 (const :tag
"Use fuzzy text search" nil
)
2084 (const :tag
"Match only exact headline" t
)
2085 (const :tag
"Match exact headline or query to create it"
2089 (defcustom org-link-frame-setup
2090 '((vm . vm-visit-folder-other-frame
)
2091 (vm-imap . vm-visit-imap-folder-other-frame
)
2092 (gnus . org-gnus-no-new-news
)
2093 (file . find-file-other-window
)
2094 (wl . wl-other-frame
))
2095 "Setup the frame configuration for following links.
2096 When following a link with Emacs, it may often be useful to display
2097 this link in another window or frame. This variable can be used to
2098 set this up for the different types of links.
2101 `vm-visit-folder-other-window'
2102 `vm-visit-folder-other-frame'
2103 For Gnus, use any of
2106 `org-gnus-no-new-news'
2107 For FILE, use any of
2109 `find-file-other-window'
2110 `find-file-other-frame'
2111 For Wanderlust use any of
2114 For the calendar, use the variable `calendar-setup'.
2115 For BBDB, it is currently only possible to display the matches in
2117 :group
'org-link-follow
2121 (const vm-visit-folder
)
2122 (const vm-visit-folder-other-window
)
2123 (const vm-visit-folder-other-frame
)))
2124 (cons (const vm-imap
)
2126 (const vm-visit-imap-folder
)
2127 (const vm-visit-imap-folder-other-window
)
2128 (const vm-visit-imap-folder-other-frame
)))
2132 (const gnus-other-frame
)
2133 (const org-gnus-no-new-news
)))
2137 (const find-file-other-window
)
2138 (const find-file-other-frame
)))
2142 (const wl-other-frame
)))))
2144 (defcustom org-display-internal-link-with-indirect-buffer nil
2145 "Non-nil means use indirect buffer to display infile links.
2146 Activating internal links (from one location in a file to another location
2147 in the same file) normally just jumps to the location. When the link is
2148 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2150 another window. When this option is set, the other window actually displays
2151 an indirect buffer clone of the current buffer, to avoid any visibility
2152 changes to the current buffer."
2153 :group
'org-link-follow
2156 (defcustom org-open-non-existing-files nil
2157 "Non-nil means `org-open-file' will open non-existing files.
2158 When nil, an error will be generated.
2159 This variable applies only to external applications because they
2160 might choke on non-existing files. If the link is to a file that
2161 will be opened in Emacs, the variable is ignored."
2162 :group
'org-link-follow
2165 (defcustom org-open-directory-means-index-dot-org nil
2166 "Non-nil means a link to a directory really means to index.org.
2167 When nil, following a directory link will run dired or open a finder/explorer
2168 window on that directory."
2169 :group
'org-link-follow
2172 (defcustom org-confirm-shell-link-function
'yes-or-no-p
2173 "Non-nil means ask for confirmation before executing shell links.
2174 Shell links can be dangerous: just think about a link
2176 [[shell:rm -rf ~/*][Google Search]]
2178 This link would show up in your Org document as \"Google Search\",
2179 but really it would remove your entire home directory.
2180 Therefore we advise against setting this variable to nil.
2181 Just change it to `y-or-n-p' if you want to confirm with a
2182 single keystroke rather than having to type \"yes\"."
2183 :group
'org-link-follow
2185 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2186 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2187 (const :tag
"no confirmation (dangerous)" nil
)))
2188 (put 'org-confirm-shell-link-function
2189 'safe-local-variable
2190 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2192 (defcustom org-confirm-shell-link-not-regexp
""
2193 "A regexp to skip confirmation for shell links."
2194 :group
'org-link-follow
2198 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
2199 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2200 Elisp links can be dangerous: just think about a link
2202 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2204 This link would show up in your Org document as \"Google Search\",
2205 but really it would remove your entire home directory.
2206 Therefore we advise against setting this variable to nil.
2207 Just change it to `y-or-n-p' if you want to confirm with a
2208 single keystroke rather than having to type \"yes\"."
2209 :group
'org-link-follow
2211 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2212 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2213 (const :tag
"no confirmation (dangerous)" nil
)))
2214 (put 'org-confirm-shell-link-function
2215 'safe-local-variable
2216 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2218 (defcustom org-confirm-elisp-link-not-regexp
""
2219 "A regexp to skip confirmation for Elisp links."
2220 :group
'org-link-follow
2224 (defconst org-file-apps-defaults-gnu
2228 "Default file applications on a UNIX or GNU/Linux system.
2229 See `org-file-apps'.")
2231 (defconst org-file-apps-defaults-macosx
2233 (system .
"open %s")
2235 ("eps.gz" .
"gv %s")
2239 "Default file applications on a macOS system.
2240 The system \"open\" is known as a default, but we use X11 applications
2241 for some files for which the OS does not have a good default.
2242 See `org-file-apps'.")
2244 (defconst org-file-apps-defaults-windowsnt
2245 (list '(remote . emacs
)
2246 (cons 'system
(lambda (file _path
)
2247 (with-no-warnings (w32-shell-execute "open" file
))))
2248 (cons t
(lambda (file _path
)
2249 (with-no-warnings (w32-shell-execute "open" file
)))))
2250 "Default file applications on a Windows NT system.
2251 The system \"open\" is used for most files.
2252 See `org-file-apps'.")
2254 (defcustom org-file-apps
2255 '((auto-mode . emacs
)
2256 ("\\.mm\\'" . default
)
2257 ("\\.x?html?\\'" . default
)
2258 ("\\.pdf\\'" . default
))
2259 "External applications for opening `file:path' items in a document.
2262 Org mode uses system defaults for different file types, but
2263 you can use this variable to set the application for a given file
2264 extension. The entries in this list are cons cells where the car identifies
2265 files and the cdr the corresponding command.
2267 Possible values for the file identifier are:
2269 \"string\" A string as a file identifier can be interpreted in different
2270 ways, depending on its contents:
2272 - Alphanumeric characters only:
2273 Match links with this file extension.
2274 Example: (\"pdf\" . \"evince %s\")
2275 to open PDFs with evince.
2277 - Regular expression: Match links where the
2278 filename matches the regexp. If you want to
2279 use groups here, use shy groups.
2281 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2282 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2283 to open *.html and *.xhtml with firefox.
2285 - Regular expression which contains (non-shy) groups:
2286 Match links where the whole link, including \"::\", and
2287 anything after that, matches the regexp.
2288 In a custom command string, %1, %2, etc. are replaced with
2289 the parts of the link that were matched by the groups.
2290 For backwards compatibility, if a command string is given
2291 that does not use any of the group matches, this case is
2292 handled identically to the second one (i.e. match against
2294 In a custom function, you can access the group matches with
2295 (match-string n link).
2297 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2298 \"evince -p %1 %s\")
2299 to open [[file:document.pdf::5]] with evince at page 5.
2301 `directory' Matches a directory
2302 `remote' Matches a remote file, accessible through tramp or efs.
2303 Remote files most likely should be visited through Emacs
2304 because external applications cannot handle such paths.
2305 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2306 so all files Emacs knows how to handle. Using this with
2307 command `emacs' will open most files in Emacs. Beware that this
2308 will also open html files inside Emacs, unless you add
2309 (\"html\" . default) to the list as well.
2310 `system' The system command to open files, like `open' on Windows
2311 and macOS, and mailcap under GNU/Linux. This is the command
2312 that will be selected if you call `org-open-at-point' with a
2313 double prefix argument (`\\[universal-argument] \
2314 \\[universal-argument] \\[org-open-at-point]').
2315 t Default for files not matched by any of the other options.
2317 Possible values for the command are:
2319 `emacs' The file will be visited by the current Emacs process.
2320 `default' Use the default application for this file type, which is the
2321 association for t in the list, most likely in the system-specific
2322 part. This can be used to overrule an unwanted setting in the
2323 system-specific variable.
2324 `system' Use the system command for opening files, like \"open\".
2325 This command is specified by the entry whose car is `system'.
2326 Most likely, the system-specific version of this variable
2327 does define this command, but you can overrule/replace it
2329 `mailcap' Use command specified in the mailcaps.
2330 string A command to be executed by a shell; %s will be replaced
2331 by the path to the file.
2332 function A Lisp function, which will be called with two arguments:
2333 the file path and the original link string, without the
2336 For more examples, see the system specific constants
2337 `org-file-apps-defaults-macosx'
2338 `org-file-apps-defaults-windowsnt'
2339 `org-file-apps-defaults-gnu'."
2340 :group
'org-link-follow
2342 (cons (choice :value
""
2343 (string :tag
"Extension")
2344 (const :tag
"System command to open files" system
)
2345 (const :tag
"Default for unrecognized files" t
)
2346 (const :tag
"Remote file" remote
)
2347 (const :tag
"Links to a directory" directory
)
2348 (const :tag
"Any files that have Emacs modes"
2351 (const :tag
"Visit with Emacs" emacs
)
2352 (const :tag
"Use default" default
)
2353 (const :tag
"Use the system command" system
)
2354 (string :tag
"Command")
2355 (function :tag
"Function")))))
2357 (defcustom org-doi-server-url
"http://dx.doi.org/"
2358 "The URL of the DOI server."
2361 :group
'org-link-follow
)
2363 (defgroup org-refile nil
2364 "Options concerning refiling entries in Org mode."
2368 (defcustom org-directory
"~/org"
2369 "Directory with Org files.
2370 This is just a default location to look for Org files. There is no need
2371 at all to put your files into this directory. It is used in the
2372 following situations:
2374 1. When a capture template specifies a target file that is not an
2375 absolute path. The path will then be interpreted relative to
2377 2. When the value of variable `org-agenda-files' is a single file, any
2378 relative paths in this file will be taken as relative to
2384 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2385 "Default target for storing notes.
2386 Used as a fall back file for org-capture.el, for templates that
2387 do not specify a target file."
2392 (defcustom org-goto-interface
'outline
2393 "The default interface to be used for `org-goto'.
2395 outline The interface shows an outline of the relevant file
2396 and the correct heading is found by moving through
2397 the outline or by searching with incremental search.
2398 outline-path-completion Headlines in the current buffer are offered via
2399 completion. This is the interface also used by
2400 the refile command."
2403 (const :tag
"Outline" outline
)
2404 (const :tag
"Outline-path-completion" outline-path-completion
)))
2406 (defcustom org-goto-max-level
5
2407 "Maximum target level when running `org-goto' with refile interface."
2411 (defcustom org-reverse-note-order nil
2412 "Non-nil means store new notes at the beginning of a file or entry.
2413 When nil, new notes will be filed to the end of a file or entry.
2414 This can also be a list with cons cells of regular expressions that
2415 are matched against file names, and values."
2419 (const :tag
"Reverse always" t
)
2420 (const :tag
"Reverse never" nil
)
2421 (repeat :tag
"By file name regexp"
2422 (cons regexp boolean
))))
2424 (defcustom org-log-refile nil
2425 "Information to record when a task is refiled.
2427 Possible values are:
2429 nil Don't add anything
2430 time Add a time stamp to the task
2431 note Prompt for a note and add it with template `org-log-note-headings'
2433 This option can also be set with on a per-file-basis with
2435 #+STARTUP: nologrefile
2436 #+STARTUP: logrefile
2437 #+STARTUP: lognoterefile
2439 You can have local logging settings for a subtree by setting the LOGGING
2440 property to one or more of these keywords.
2442 When bulk-refiling from the agenda, the value `note' is forbidden and
2443 will temporarily be changed to `time'."
2445 :group
'org-progress
2448 (const :tag
"No logging" nil
)
2449 (const :tag
"Record timestamp" time
)
2450 (const :tag
"Record timestamp with note." note
)))
2452 (defcustom org-refile-targets nil
2453 "Targets for refiling entries with `\\[org-refile]'.
2454 This is a list of cons cells. Each cell contains:
2455 - a specification of the files to be considered, either a list of files,
2456 or a symbol whose function or variable value will be used to retrieve
2457 a file name or a list of file names. If you use `org-agenda-files' for
2458 that, all agenda files will be scanned for targets. Nil means consider
2459 headings in the current buffer.
2460 - A specification of how to find candidate refile targets. This may be
2462 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2463 This tag has to be present in all target headlines, inheritance will
2465 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2467 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2468 headlines that are refiling targets.
2469 - a cons cell (:level . N). Any headline of level N is considered a target.
2470 Note that, when `org-odd-levels-only' is set, level corresponds to
2471 order in hierarchy, not to the number of stars.
2472 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2473 Note that, when `org-odd-levels-only' is set, level corresponds to
2474 order in hierarchy, not to the number of stars.
2476 Each element of this list generates a set of possible targets.
2477 The union of these sets is presented (with completion) to
2478 the user by `org-refile'.
2480 You can set the variable `org-refile-target-verify-function' to a function
2481 to verify each headline found by the simple criteria above.
2483 When this variable is nil, all top-level headlines in the current buffer
2484 are used, equivalent to the value `((nil . (:level . 1))'."
2488 (choice :value org-agenda-files
2489 (const :tag
"All agenda files" org-agenda-files
)
2490 (const :tag
"Current buffer" nil
)
2491 (function) (variable) (file))
2492 (choice :tag
"Identify target headline by"
2493 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2494 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2495 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2496 (cons :tag
"Level number" (const :value
:level
) (integer))
2497 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2499 (defcustom org-refile-target-verify-function nil
2500 "Function to verify if the headline at point should be a refile target.
2501 The function will be called without arguments, with point at the
2502 beginning of the headline. It should return t and leave point
2503 where it is if the headline is a valid target for refiling.
2505 If the target should not be selected, the function must return nil.
2506 In addition to this, it may move point to a place from where the search
2507 should be continued. For example, the function may decide that the entire
2508 subtree of the current entry should be excluded and move point to the end
2515 (defcustom org-refile-use-cache nil
2516 "Non-nil means cache refile targets to speed up the process.
2518 The cache for a particular file will be updated automatically when
2519 the buffer has been killed, or when any of the marker used for flagging
2520 refile targets no longer points at a live buffer.
2521 If you have added new entries to a buffer that might themselves be targets,
2522 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2523 if you find that easier, \
2524 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2530 (defcustom org-refile-use-outline-path nil
2531 "Non-nil means provide refile targets as paths.
2532 So a level 3 headline will be available as level1/level2/level3.
2534 When the value is `file', also include the file name (without directory)
2535 into the path. In this case, you can also stop the completion after
2536 the file name, to get entries inserted as top level in the file.
2538 When `full-file-path', include the full file path.
2540 When `buffer-name', use the buffer name."
2543 (const :tag
"Not" nil
)
2544 (const :tag
"Yes" t
)
2545 (const :tag
"Start with file name" file
)
2546 (const :tag
"Start with full file path" full-file-path
)
2547 (const :tag
"Start with buffer name" buffer-name
)))
2549 (defcustom org-outline-path-complete-in-steps t
2550 "Non-nil means complete the outline path in hierarchical steps.
2551 When Org uses the refile interface to select an outline path (see
2552 `org-refile-use-outline-path'), the completion of the path can be
2553 done in a single go, or it can be done in steps down the headline
2554 hierarchy. Going in steps is probably the best if you do not use
2555 a special completion package like `ido' or `icicles'. However,
2556 when using these packages, going in one step can be very fast,
2557 while still showing the whole path to the entry."
2561 (defcustom org-refile-allow-creating-parent-nodes nil
2562 "Non-nil means allow the creation of new nodes as refile targets.
2563 New nodes are then created by adding \"/new node name\" to the completion
2564 of an existing node. When the value of this variable is `confirm',
2565 new node creation must be confirmed by the user (recommended).
2566 When nil, the completion must match an existing entry.
2568 Note that, if the new heading is not seen by the criteria
2569 listed in `org-refile-targets', multiple instances of the same
2570 heading would be created by trying again to file under the new
2574 (const :tag
"Never" nil
)
2575 (const :tag
"Always" t
)
2576 (const :tag
"Prompt for confirmation" confirm
)))
2578 (defcustom org-refile-active-region-within-subtree nil
2579 "Non-nil means also refile active region within a subtree.
2581 By default `org-refile' doesn't allow refiling regions if they
2582 don't contain a set of subtrees, but it might be convenient to
2583 do so sometimes: in that case, the first line of the region is
2584 converted to a headline before refiling."
2589 (defgroup org-todo nil
2590 "Options concerning TODO items in Org mode."
2594 (defgroup org-progress nil
2595 "Options concerning Progress logging in Org mode."
2599 (defvar org-todo-interpretation-widgets
2600 '((:tag
"Sequence (cycling hits every state)" sequence
)
2601 (:tag
"Type (cycling directly to DONE)" type
))
2602 "The available interpretation symbols for customizing `org-todo-keywords'.
2603 Interested libraries should add to this list.")
2605 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2606 "List of TODO entry keyword sequences and their interpretation.
2607 \\<org-mode-map>This is a list of sequences.
2609 Each sequence starts with a symbol, either `sequence' or `type',
2610 indicating if the keywords should be interpreted as a sequence of
2611 action steps, or as different types of TODO items. The first
2612 keywords are states requiring action - these states will select a headline
2613 for inclusion into the global TODO list Org produces. If one of the
2614 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2615 signify that no further action is necessary. If \"|\" is not found,
2616 the last keyword is treated as the only DONE state of the sequence.
2618 The command `\\[org-todo]' cycles an entry through these states, and one
2619 additional state where no keyword is present. For details about this
2620 cycling, see the manual.
2622 TODO keywords and interpretation can also be set on a per-file basis with
2623 the special #+SEQ_TODO and #+TYP_TODO lines.
2625 Each keyword can optionally specify a character for fast state selection
2626 \(in combination with the variable `org-use-fast-todo-selection')
2627 and specifiers for state change logging, using the same syntax that
2628 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2629 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2630 indicates to record a time stamp each time this state is selected.
2632 Each keyword may also specify if a timestamp or a note should be
2633 recorded when entering or leaving the state, by adding additional
2634 characters in the parenthesis after the keyword. This looks like this:
2635 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2636 record only the time of the state change. With X and Y being either
2637 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2638 Y when leaving the state if and only if the *target* state does not
2639 define X. You may omit any of the fast-selection key or X or /Y,
2640 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2642 For backward compatibility, this variable may also be just a list
2643 of keywords. In this case the interpretation (sequence or type) will be
2644 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2646 :group
'org-keywords
2648 (repeat :tag
"Old syntax, just keywords"
2649 (string :tag
"Keyword"))
2650 (repeat :tag
"New syntax"
2653 :tag
"Interpretation"
2654 ;;Quick and dirty way to see
2655 ;;`org-todo-interpretations'. This takes the
2656 ;;place of item arguments
2664 org-todo-interpretation-widgets
))
2667 (string :tag
"Keyword"))))))
2669 (defvar-local org-todo-keywords-1 nil
2670 "All TODO and DONE keywords active in a buffer.")
2671 (defvar org-todo-keywords-for-agenda nil
)
2672 (defvar org-done-keywords-for-agenda nil
)
2673 (defvar org-todo-keyword-alist-for-agenda nil
)
2674 (defvar org-tag-alist-for-agenda nil
2675 "Alist of all tags from all agenda files.")
2676 (defvar org-tag-groups-alist-for-agenda nil
2677 "Alist of all groups tags from all current agenda files.")
2678 (defvar-local org-tag-groups-alist nil
)
2679 (defvar org-agenda-contributing-files nil
)
2680 (defvar-local org-current-tag-alist nil
2681 "Alist of all tag groups in current buffer.
2682 This variable takes into consideration `org-tag-alist',
2683 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2684 (defvar-local org-not-done-keywords nil
)
2685 (defvar-local org-done-keywords nil
)
2686 (defvar-local org-todo-heads nil
)
2687 (defvar-local org-todo-sets nil
)
2688 (defvar-local org-todo-log-states nil
)
2689 (defvar-local org-todo-kwd-alist nil
)
2690 (defvar-local org-todo-key-alist nil
)
2691 (defvar-local org-todo-key-trigger nil
)
2693 (defcustom org-todo-interpretation
'sequence
2694 "Controls how TODO keywords are interpreted.
2695 This variable is in principle obsolete and is only used for
2696 backward compatibility, if the interpretation of todo keywords is
2697 not given already in `org-todo-keywords'. See that variable for
2700 :group
'org-keywords
2701 :type
'(choice (const sequence
)
2704 (defcustom org-use-fast-todo-selection t
2706 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2707 This variable describes if and under what circumstances the cycling
2708 mechanism for TODO keywords will be replaced by a single-key, direct
2711 When nil, fast selection is never used.
2713 When the symbol `prefix', it will be used when `org-todo' is called
2714 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2715 in an Org buffer, and
2716 `\\[universal-argument] t' in an agenda buffer.
2718 When t, fast selection is used by default. In this case, the prefix
2719 argument forces cycling instead.
2721 In all cases, the special interface is only used if access keys have
2722 actually been assigned by the user, i.e. if keywords in the configuration
2723 are followed by a letter in parenthesis, like TODO(t)."
2726 (const :tag
"Never" nil
)
2727 (const :tag
"By default" t
)
2728 (const :tag
"Only with C-u C-c C-t" prefix
)))
2730 (defcustom org-provide-todo-statistics t
2731 "Non-nil means update todo statistics after insert and toggle.
2732 ALL-HEADLINES means update todo statistics by including headlines
2733 with no TODO keyword as well, counting them as not done.
2734 A list of TODO keywords means the same, but skip keywords that are
2736 When set to a list of two lists, the first list contains keywords
2737 to consider as TODO keywords, the second list contains keywords
2738 to consider as DONE keywords.
2740 When this is set, todo statistics is updated in the parent of the
2741 current entry each time a todo state is changed."
2744 (const :tag
"Yes, only for TODO entries" t
)
2745 (const :tag
"Yes, including all entries" all-headlines
)
2746 (repeat :tag
"Yes, for TODOs in this list"
2747 (string :tag
"TODO keyword"))
2748 (list :tag
"Yes, for TODOs and DONEs in these lists"
2749 (repeat (string :tag
"TODO keyword"))
2750 (repeat (string :tag
"DONE keyword")))
2751 (other :tag
"No TODO statistics" nil
)))
2753 (defcustom org-hierarchical-todo-statistics t
2754 "Non-nil means TODO statistics covers just direct children.
2755 When nil, all entries in the subtree are considered.
2756 This has only an effect if `org-provide-todo-statistics' is set.
2757 To set this to nil for only a single subtree, use a COOKIE_DATA
2758 property and include the word \"recursive\" into the value."
2762 (defcustom org-after-todo-state-change-hook nil
2763 "Hook which is run after the state of a TODO item was changed.
2764 The new state (a string with a TODO keyword, or nil) is available in the
2765 Lisp variable `org-state'."
2769 (defvar org-blocker-hook nil
2770 "Hook for functions that are allowed to block a state change.
2772 Functions in this hook should not modify the buffer.
2773 Each function gets as its single argument a property list,
2774 see `org-trigger-hook' for more information about this list.
2776 If any of the functions in this hook returns nil, the state change
2779 (defvar org-trigger-hook nil
2780 "Hook for functions that are triggered by a state change.
2782 Each function gets as its single argument a property list with at
2783 least the following elements:
2785 (:type type-of-change :position pos-at-entry-start
2786 :from old-state :to new-state)
2788 Depending on the type, more properties may be present.
2790 This mechanism is currently implemented for:
2794 :type todo-state-change
2795 :from previous state (keyword as a string), or nil, or a symbol
2796 `todo' or `done', to indicate the general type of state.
2797 :to new state, like in :from")
2799 (defcustom org-enforce-todo-dependencies nil
2800 "Non-nil means undone TODO entries will block switching the parent to DONE.
2801 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2802 be blocked if any prior sibling is not yet done.
2803 Finally, if the parent is blocked because of ordered siblings of its own,
2804 the child will also be blocked."
2805 :set
(lambda (var val
)
2808 (add-hook 'org-blocker-hook
2809 'org-block-todo-from-children-or-siblings-or-parent
)
2810 (remove-hook 'org-blocker-hook
2811 'org-block-todo-from-children-or-siblings-or-parent
)))
2815 (defcustom org-enforce-todo-checkbox-dependencies nil
2816 "Non-nil means unchecked boxes will block switching the parent to DONE.
2817 When this is nil, checkboxes have no influence on switching TODO states.
2818 When non-nil, you first need to check off all check boxes before the TODO
2819 entry can be switched to DONE.
2820 This variable needs to be set before org.el is loaded, and you need to
2821 restart Emacs after a change to make the change effective. The only way
2822 to change is while Emacs is running is through the customize interface."
2823 :set
(lambda (var val
)
2826 (add-hook 'org-blocker-hook
2827 'org-block-todo-from-checkboxes
)
2828 (remove-hook 'org-blocker-hook
2829 'org-block-todo-from-checkboxes
)))
2833 (defcustom org-treat-insert-todo-heading-as-state-change nil
2834 "Non-nil means inserting a TODO heading is treated as state change.
2835 So when the command `\\[org-insert-todo-heading]' is used, state change
2836 logging will apply if appropriate. When nil, the new TODO item will
2837 be inserted directly, and no logging will take place."
2841 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2842 "Non-nil means switching TODO states with S-cursor counts as state change.
2843 This is the default behavior. However, setting this to nil allows a
2844 convenient way to select a TODO state and bypass any logging associated
2849 (defcustom org-todo-state-tags-triggers nil
2850 "Tag changes that should be triggered by TODO state changes.
2851 This is a list. Each entry is
2853 (state-change (tag . flag) .......)
2855 State-change can be a string with a state, and empty string to indicate the
2856 state that has no TODO keyword, or it can be one of the symbols `todo'
2857 or `done', meaning any not-done or done state, respectively."
2861 (cons (choice :tag
"When changing to"
2862 (const :tag
"Not-done state" todo
)
2863 (const :tag
"Done state" done
)
2864 (string :tag
"State"))
2866 (cons :tag
"Tag action"
2868 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2870 (defcustom org-log-done nil
2871 "Information to record when a task moves to the DONE state.
2873 Possible values are:
2875 nil Don't add anything, just change the keyword
2876 time Add a time stamp to the task
2877 note Prompt for a note and add it with template `org-log-note-headings'
2879 This option can also be set with on a per-file-basis with
2881 #+STARTUP: nologdone
2883 #+STARTUP: lognotedone
2885 You can have local logging settings for a subtree by setting the LOGGING
2886 property to one or more of these keywords."
2888 :group
'org-progress
2890 (const :tag
"No logging" nil
)
2891 (const :tag
"Record CLOSED timestamp" time
)
2892 (const :tag
"Record CLOSED timestamp with note." note
)))
2894 ;; Normalize old uses of org-log-done.
2896 ((eq org-log-done t
) (setq org-log-done
'time
))
2897 ((and (listp org-log-done
) (memq 'done org-log-done
))
2898 (setq org-log-done
'note
)))
2900 (defcustom org-log-reschedule nil
2901 "Information to record when the scheduling date of a tasks is modified.
2903 Possible values are:
2905 nil Don't add anything, just change the date
2906 time Add a time stamp to the task
2907 note Prompt for a note and add it with template `org-log-note-headings'
2909 This option can also be set with on a per-file-basis with
2911 #+STARTUP: nologreschedule
2912 #+STARTUP: logreschedule
2913 #+STARTUP: lognotereschedule"
2915 :group
'org-progress
2917 (const :tag
"No logging" nil
)
2918 (const :tag
"Record timestamp" time
)
2919 (const :tag
"Record timestamp with note." note
)))
2921 (defcustom org-log-redeadline nil
2922 "Information to record when the deadline date of a tasks is modified.
2924 Possible values are:
2926 nil Don't add anything, just change the date
2927 time Add a time stamp to the task
2928 note Prompt for a note and add it with template `org-log-note-headings'
2930 This option can also be set with on a per-file-basis with
2932 #+STARTUP: nologredeadline
2933 #+STARTUP: logredeadline
2934 #+STARTUP: lognoteredeadline
2936 You can have local logging settings for a subtree by setting the LOGGING
2937 property to one or more of these keywords."
2939 :group
'org-progress
2941 (const :tag
"No logging" nil
)
2942 (const :tag
"Record timestamp" time
)
2943 (const :tag
"Record timestamp with note." note
)))
2945 (defcustom org-log-note-clock-out nil
2946 "Non-nil means record a note when clocking out of an item.
2947 This can also be configured on a per-file basis by adding one of
2948 the following lines anywhere in the buffer:
2950 #+STARTUP: lognoteclock-out
2951 #+STARTUP: nolognoteclock-out"
2953 :group
'org-progress
2956 (defcustom org-log-done-with-time t
2957 "Non-nil means the CLOSED time stamp will contain date and time.
2958 When nil, only the date will be recorded."
2959 :group
'org-progress
2962 (defcustom org-log-note-headings
2963 '((done .
"CLOSING NOTE %t")
2964 (state .
"State %-12s from %-12S %t")
2965 (note .
"Note taken on %t")
2966 (reschedule .
"Rescheduled from %S on %t")
2967 (delschedule .
"Not scheduled, was %S on %t")
2968 (redeadline .
"New deadline from %S on %t")
2969 (deldeadline .
"Removed deadline, was %S on %t")
2970 (refile .
"Refiled on %t")
2972 "Headings for notes added to entries.
2974 The value is an alist, with the car being a symbol indicating the
2975 note context, and the cdr is the heading to be used. The heading
2976 may also be the empty string. The following placeholders can be
2980 %T an active time stamp instead the default inactive one
2981 %d a short-format time stamp.
2982 %D an active short-format time stamp.
2983 %s the new TODO state or time stamp (inactive), in double quotes.
2984 %S the old TODO state or time stamp (inactive), in double quotes.
2988 In fact, it is not a good idea to change the `state' entry,
2989 because Agenda Log mode depends on the format of these entries."
2991 :group
'org-progress
2992 :type
'(list :greedy t
2993 (cons (const :tag
"Heading when closing an item" done
) string
)
2995 "Heading when changing todo state (todo sequence only)"
2997 (cons (const :tag
"Heading when just taking a note" note
) string
)
2998 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2999 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
3000 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
3001 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
3002 (cons (const :tag
"Heading when refiling" refile
) string
)
3003 (cons (const :tag
"Heading when clocking out" clock-out
) string
)))
3005 (unless (assq 'note org-log-note-headings
)
3006 (push '(note .
"%t") org-log-note-headings
))
3008 (defcustom org-log-into-drawer nil
3009 "Non-nil means insert state change notes and time stamps into a drawer.
3010 When nil, state changes notes will be inserted after the headline and
3011 any scheduling and clock lines, but not inside a drawer.
3013 The value of this variable should be the name of the drawer to use.
3014 LOGBOOK is proposed as the default drawer for this purpose, you can
3015 also set this to a string to define the drawer of your choice.
3017 A value of t is also allowed, representing \"LOGBOOK\".
3019 A value of t or nil can also be set with on a per-file-basis with
3021 #+STARTUP: logdrawer
3022 #+STARTUP: nologdrawer
3024 If this variable is set, `org-log-state-notes-insert-after-drawers'
3027 You can set the property LOG_INTO_DRAWER to overrule this setting for
3030 Do not check directly this variable in a Lisp program. Call
3031 function `org-log-into-drawer' instead."
3033 :group
'org-progress
3035 (const :tag
"Not into a drawer" nil
)
3036 (const :tag
"LOGBOOK" t
)
3037 (string :tag
"Other")))
3039 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
3041 (defun org-log-into-drawer ()
3042 "Name of the log drawer, as a string, or nil.
3043 This is the value of `org-log-into-drawer'. However, if the
3044 current entry has or inherits a LOG_INTO_DRAWER property, it will
3045 be used instead of the default value."
3046 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
3047 (cond ((equal p
"nil") nil
)
3048 ((equal p
"t") "LOGBOOK")
3051 ((stringp org-log-into-drawer
) org-log-into-drawer
)
3052 (org-log-into-drawer "LOGBOOK"))))
3054 (defcustom org-log-state-notes-insert-after-drawers nil
3055 "Non-nil means insert state change notes after any drawers in entry.
3056 Only the drawers that *immediately* follow the headline and the
3057 deadline/scheduled line are skipped.
3058 When nil, insert notes right after the heading and perhaps the line
3059 with deadline/scheduling if present.
3061 This variable will have no effect if `org-log-into-drawer' is
3064 :group
'org-progress
3067 (defcustom org-log-states-order-reversed t
3068 "Non-nil means the latest state note will be directly after heading.
3069 When nil, the state change notes will be ordered according to time.
3071 This option can also be set with on a per-file-basis with
3073 #+STARTUP: logstatesreversed
3074 #+STARTUP: nologstatesreversed"
3076 :group
'org-progress
3079 (defcustom org-todo-repeat-to-state nil
3080 "The TODO state to which a repeater should return the repeating task.
3081 By default this is the first task in a TODO sequence, or the previous state
3082 in a TODO_TYP set. But you can specify another task here.
3083 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3086 :type
'(choice (const :tag
"Head of sequence" nil
)
3087 (string :tag
"Specific state")))
3089 (defcustom org-log-repeat
'time
3090 "Non-nil means record moving through the DONE state when triggering repeat.
3091 An auto-repeating task is immediately switched back to TODO when
3092 marked DONE. If you are not logging state changes (by adding \"@\"
3093 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3094 record a closing note, there will be no record of the task moving
3095 through DONE. This variable forces taking a note anyway.
3097 nil Don't force a record
3098 time Record a time stamp
3099 note Prompt for a note and add it with template `org-log-note-headings'
3101 This option can also be set with on a per-file-basis with
3103 #+STARTUP: nologrepeat
3104 #+STARTUP: logrepeat
3105 #+STARTUP: lognoterepeat
3107 You can have local logging settings for a subtree by setting the LOGGING
3108 property to one or more of these keywords."
3110 :group
'org-progress
3112 (const :tag
"Don't force a record" nil
)
3113 (const :tag
"Force recording the DONE state" time
)
3114 (const :tag
"Force recording a note with the DONE state" note
)))
3117 (defgroup org-priorities nil
3118 "Priorities in Org mode."
3119 :tag
"Org Priorities"
3122 (defcustom org-enable-priority-commands t
3123 "Non-nil means priority commands are active.
3124 When nil, these commands will be disabled, so that you never accidentally
3126 :group
'org-priorities
3129 (defcustom org-highest-priority ?A
3130 "The highest priority of TODO items. A character like ?A, ?B etc.
3131 Must have a smaller ASCII number than `org-lowest-priority'."
3132 :group
'org-priorities
3135 (defcustom org-lowest-priority ?C
3136 "The lowest priority of TODO items. A character like ?A, ?B etc.
3137 Must have a larger ASCII number than `org-highest-priority'."
3138 :group
'org-priorities
3141 (defcustom org-default-priority ?B
3142 "The default priority of TODO items.
3143 This is the priority an item gets if no explicit priority is given.
3144 When starting to cycle on an empty priority the first step in the cycle
3145 depends on `org-priority-start-cycle-with-default'. The resulting first
3146 step priority must not exceed the range from `org-highest-priority' to
3147 `org-lowest-priority' which means that `org-default-priority' has to be
3148 in this range exclusive or inclusive the range boundaries. Else the
3149 first step refuses to set the default and the second will fall back
3150 to (depending on the command used) the highest or lowest priority."
3151 :group
'org-priorities
3154 (defcustom org-priority-start-cycle-with-default t
3155 "Non-nil means start with default priority when starting to cycle.
3156 When this is nil, the first step in the cycle will be (depending on the
3157 command used) one higher or lower than the default priority.
3158 See also `org-default-priority'."
3159 :group
'org-priorities
3162 (defcustom org-get-priority-function nil
3163 "Function to extract the priority from a string.
3164 The string is normally the headline. If this is nil Org computes the
3165 priority from the priority cookie like [#A] in the headline. It returns
3166 an integer, increasing by 1000 for each priority level.
3167 The user can set a different function here, which should take a string
3168 as an argument and return the numeric priority."
3169 :group
'org-priorities
3175 (defgroup org-time nil
3176 "Options concerning time stamps and deadlines in Org mode."
3180 (defcustom org-time-stamp-rounding-minutes
'(0 5)
3181 "Number of minutes to round time stamps to.
3183 These are two values, the first applies when first creating a time stamp.
3184 The second applies when changing it with the commands `S-up' and `S-down'.
3185 When changing the time stamp, this means that it will change in steps
3186 of N minutes, as given by the second value.
3188 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3189 numbers should be factors of 60, so for example 5, 10, 15.
3191 When this is larger than 1, you can still force an exact time stamp by using
3192 a double prefix argument to a time stamp command like \
3193 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3194 and by using a prefix arg to `S-up/down' to specify the exact number
3195 of minutes to shift."
3197 :get
(lambda (var) ; Make sure both elements are there
3198 (if (integerp (default-value var
))
3199 (list (default-value var
) 5)
3200 (default-value var
)))
3202 (integer :tag
"when inserting times")
3203 (integer :tag
"when modifying times")))
3205 ;; Normalize old customizations of this variable.
3206 (when (integerp org-time-stamp-rounding-minutes
)
3207 (setq org-time-stamp-rounding-minutes
3208 (list org-time-stamp-rounding-minutes
3209 org-time-stamp-rounding-minutes
)))
3211 (defcustom org-display-custom-times nil
3212 "Non-nil means overlay custom formats over all time stamps.
3213 The formats are defined through the variable `org-time-stamp-custom-formats'.
3214 To turn this on on a per-file basis, insert anywhere in the file:
3215 #+STARTUP: customtime"
3219 (make-variable-buffer-local 'org-display-custom-times
)
3221 (defcustom org-time-stamp-custom-formats
3222 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
3223 "Custom formats for time stamps. See `format-time-string' for the syntax.
3224 These are overlaid over the default ISO format if the variable
3225 `org-display-custom-times' is set. Time like %H:%M should be at the
3226 end of the second format. The custom formats are also honored by export
3227 commands, if custom time display is turned on at the time of export."
3231 (defun org-time-stamp-format (&optional long inactive
)
3232 "Get the right format for a time string."
3233 (let ((f (if long
(cdr org-time-stamp-formats
)
3234 (car org-time-stamp-formats
))))
3236 (concat "[" (substring f
1 -
1) "]")
3239 (defcustom org-deadline-warning-days
14
3240 "Number of days before expiration during which a deadline becomes active.
3241 This variable governs the display in sparse trees and in the agenda.
3242 When 0 or negative, it means use this number (the absolute value of it)
3243 even if a deadline has a different individual lead time specified.
3245 Custom commands can set this variable in the options section."
3247 :group
'org-agenda-daily
/weekly
3250 (defcustom org-scheduled-delay-days
0
3251 "Number of days before a scheduled item becomes active.
3252 This variable governs the display in sparse trees and in the agenda.
3253 The default value (i.e. 0) means: don't delay scheduled item.
3254 When negative, it means use this number (the absolute value of it)
3255 even if a scheduled item has a different individual delay time
3258 Custom commands can set this variable in the options section."
3260 :group
'org-agenda-daily
/weekly
3262 :package-version
'(Org .
"8.0")
3265 (defcustom org-read-date-prefer-future t
3266 "Non-nil means assume future for incomplete date input from user.
3267 This affects the following situations:
3268 1. The user gives a month but not a year.
3269 For example, if it is April and you enter \"feb 2\", this will be read
3270 as Feb 2, *next* year. \"May 5\", however, will be this year.
3271 2. The user gives a day, but no month.
3272 For example, if today is the 15th, and you enter \"3\", Org will read
3273 this as the third of *next* month. However, if you enter \"17\",
3274 it will be considered as *this* month.
3276 If you set this variable to the symbol `time', then also the following
3279 3. If the user gives a time.
3280 If the time is before now, it will be interpreted as tomorrow.
3282 Currently none of this works for ISO week specifications.
3284 When this option is nil, the current day, month and year will always be
3287 See also `org-agenda-jump-prefer-future'."
3290 (const :tag
"Never" nil
)
3291 (const :tag
"Check month and day" t
)
3292 (const :tag
"Check month, day, and time" time
)))
3294 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3295 "Should the agenda jump command prefer the future for incomplete dates?
3296 The default is to do the same as configured in `org-read-date-prefer-future'.
3297 But you can also set a deviating value here.
3298 This may t or nil, or the symbol `org-read-date-prefer-future'."
3303 (const :tag
"Use org-read-date-prefer-future"
3304 org-read-date-prefer-future
)
3305 (const :tag
"Never" nil
)
3306 (const :tag
"Always" t
)))
3308 (defcustom org-read-date-force-compatible-dates t
3309 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3311 Depending on the system Emacs is running on, certain dates cannot
3312 be represented with the type used internally to represent time.
3313 Dates between 1970-1-1 and 2038-1-1 can always be represented
3314 correctly. Some systems allow for earlier dates, some for later,
3315 some for both. One way to find out it to insert any date into an
3316 Org buffer, putting the cursor on the year and hitting S-up and
3317 S-down to test the range.
3319 When this variable is set to t, the date/time prompt will not let
3320 you specify dates outside the 1970-2037 range, so it is certain that
3321 these dates will work in whatever version of Emacs you are
3322 running, and also that you can move a file from one Emacs implementation
3323 to another. WHenever Org is forcing the year for you, it will display
3326 When this variable is nil, Org will check if the date is
3327 representable in the specific Emacs implementation you are using.
3328 If not, it will force a year, usually the current year, and beep
3329 to remind you. Currently this setting is not recommended because
3330 the likelihood that you will open your Org files in an Emacs that
3331 has limited date range is not negligible.
3333 A workaround for this problem is to use diary sexp dates for time
3334 stamps outside of this range."
3339 (defcustom org-read-date-display-live t
3340 "Non-nil means display current interpretation of date prompt live.
3341 This display will be in an overlay, in the minibuffer."
3345 (defcustom org-read-date-popup-calendar t
3346 "Non-nil means pop up a calendar when prompting for a date.
3347 In the calendar, the date can be selected with mouse-1. However, the
3348 minibuffer will also be active, and you can simply enter the date as well.
3349 When nil, only the minibuffer will be available."
3352 (defvaralias 'org-popup-calendar-for-date-prompt
3353 'org-read-date-popup-calendar
)
3355 (defcustom org-extend-today-until
0
3356 "The hour when your day really ends. Must be an integer.
3357 This has influence for the following applications:
3358 - When switching the agenda to \"today\". It it is still earlier than
3359 the time given here, the day recognized as TODAY is actually yesterday.
3360 - When a date is read from the user and it is still before the time given
3361 here, the current date and time will be assumed to be yesterday, 23:59.
3362 Also, timestamps inserted in capture templates follow this rule.
3364 IMPORTANT: This is a feature whose implementation is and likely will
3365 remain incomplete. Really, it is only here because past midnight seems to
3366 be the favorite working time of John Wiegley :-)"
3370 (defcustom org-use-effective-time nil
3371 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3372 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3373 \"effective time\" of any timestamps between midnight and 8am will be
3374 23:59 of the previous day."
3379 (defcustom org-use-last-clock-out-time-as-effective-time nil
3380 "When non-nil, use the last clock out time for `org-todo'.
3381 Note that this option has precedence over the combined use of
3382 `org-use-effective-time' and `org-extend-today-until'."
3385 :package-version
'(Org .
"8.0")
3388 (defcustom org-edit-timestamp-down-means-later nil
3389 "Non-nil means S-down will increase the time in a time stamp.
3390 When nil, S-up will increase."
3394 (defcustom org-calendar-follow-timestamp-change t
3395 "Non-nil means make the calendar window follow timestamp changes.
3396 When a timestamp is modified and the calendar window is visible, it will be
3397 moved to the new date."
3401 (defgroup org-tags nil
3402 "Options concerning tags in Org mode."
3406 (defcustom org-tag-alist nil
3407 "Default tags available in Org files.
3409 The value of this variable is an alist. Associations either:
3415 where TAG is a tag as a string, SELECT is character, used to
3416 select that tag through the fast tag selection interface, and
3417 SPECIAL is one of the following keywords: `:startgroup',
3418 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3419 `:newline'. These keywords are used to define a hierarchy of
3420 tags. See manual for details.
3422 When this variable is nil, Org mode bases tag input on what is
3423 already in the buffer. The value can be overridden locally by
3424 using a TAGS keyword, e.g.,
3428 See also `org-tag-persistent-alist' to sidestep this behavior."
3432 (cons :tag
"Tag with key"
3433 (string :tag
"Tag name")
3434 (character :tag
"Access char"))
3435 (list :tag
"Tag" (string :tag
"Tag name"))
3436 (const :tag
"Start radio group" (:startgroup
))
3437 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3438 (const :tag
"Group tags delimiter" (:grouptags
))
3439 (const :tag
"End radio group" (:endgroup
))
3440 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3441 (const :tag
"New line" (:newline
)))))
3443 (defcustom org-tag-persistent-alist nil
3444 "Tags always available in Org files.
3446 The value of this variable is an alist. Associations either:
3452 where TAG is a tag as a string, SELECT is a character, used to
3453 select that tag through the fast tag selection interface, and
3454 SPECIAL is one of the following keywords: `:startgroup',
3455 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3456 `:newline'. These keywords are used to define a hierarchy of
3457 tags. See manual for details.
3459 Unlike to `org-tag-alist', tags defined in this variable do not
3460 depend on a local TAGS keyword. Instead, to disable these tags
3461 on a per-file basis, insert anywhere in the file:
3467 (cons :tag
"Tag with key"
3468 (string :tag
"Tag name")
3469 (character :tag
"Access char"))
3470 (list :tag
"Tag" (string :tag
"Tag name"))
3471 (const :tag
"Start radio group" (:startgroup
))
3472 (const :tag
"Start tag group, non distinct" (:startgrouptag
))
3473 (const :tag
"Group tags delimiter" (:grouptags
))
3474 (const :tag
"End radio group" (:endgroup
))
3475 (const :tag
"End tag group, non distinct" (:endgrouptag
))
3476 (const :tag
"New line" (:newline
)))))
3478 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3479 "If non-nil, always offer completion for all tags of all agenda files.
3480 Instead of customizing this variable directly, you might want to
3481 set it locally for capture buffers, because there no list of
3482 tags in that file can be created dynamically (there are none).
3484 (add-hook \\='org-capture-mode-hook
3486 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3491 (defvar org-file-tags nil
3492 "List of tags that can be inherited by all entries in the file.
3493 The tags will be inherited if the variable `org-use-tag-inheritance'
3494 says they should be.
3495 This variable is populated from #+FILETAGS lines.")
3497 (defcustom org-use-fast-tag-selection
'auto
3498 "Non-nil means use fast tag selection scheme.
3499 This is a special interface to select and deselect tags with single keys.
3500 When nil, fast selection is never used.
3501 When the symbol `auto', fast selection is used if and only if selection
3502 characters for tags have been configured, either through the variable
3503 `org-tag-alist' or through a #+TAGS line in the buffer.
3504 When t, fast selection is always used and selection keys are assigned
3505 automatically if necessary."
3508 (const :tag
"Always" t
)
3509 (const :tag
"Never" nil
)
3510 (const :tag
"When selection characters are configured" auto
)))
3512 (defcustom org-fast-tag-selection-single-key nil
3513 "Non-nil means fast tag selection exits after first change.
3514 When nil, you have to press RET to exit it.
3515 During fast tag selection, you can toggle this flag with `C-c'.
3516 This variable can also have the value `expert'. In this case, the window
3517 displaying the tags menu is not even shown, until you press C-c again."
3520 (const :tag
"No" nil
)
3521 (const :tag
"Yes" t
)
3522 (const :tag
"Expert" expert
)))
3524 (defvar org-fast-tag-selection-include-todo nil
3525 "Non-nil means fast tags selection interface will also offer TODO states.
3526 This is an undocumented feature, you should not rely on it.")
3528 (defcustom org-tags-column -
77
3529 "The column to which tags should be indented in a headline.
3530 If this number is positive, it specifies the column. If it is negative,
3531 it means that the tags should be flushright to that column. For example,
3532 -80 works well for a normal 80 character screen.
3533 When 0, place tags directly after headline text, with only one space in
3538 (defcustom org-auto-align-tags t
3539 "Non-nil keeps tags aligned when modifying headlines.
3540 Some operations (i.e. demoting) change the length of a headline and
3541 therefore shift the tags around. With this option turned on, after
3542 each such operation the tags are again aligned to `org-tags-column'."
3546 (defcustom org-use-tag-inheritance t
3547 "Non-nil means tags in levels apply also for sublevels.
3548 When nil, only the tags directly given in a specific line apply there.
3549 This may also be a list of tags that should be inherited, or a regexp that
3550 matches tags that should be inherited. Additional control is possible
3551 with the variable `org-tags-exclude-from-inheritance' which gives an
3552 explicit list of tags to be excluded from inheritance, even if the value of
3553 `org-use-tag-inheritance' would select it for inheritance.
3555 If this option is t, a match early-on in a tree can lead to a large
3556 number of matches in the subtree when constructing the agenda or creating
3557 a sparse tree. If you only want to see the first match in a tree during
3558 a search, check out the variable `org-tags-match-list-sublevels'."
3561 (const :tag
"Not" nil
)
3562 (const :tag
"Always" t
)
3563 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3564 (regexp :tag
"Tags matched by regexp")))
3566 (defcustom org-tags-exclude-from-inheritance nil
3567 "List of tags that should never be inherited.
3568 This is a way to exclude a few tags from inheritance. For way to do
3569 the opposite, to actively allow inheritance for selected tags,
3570 see the variable `org-use-tag-inheritance'."
3572 :type
'(repeat (string :tag
"Tag")))
3574 (defun org-tag-inherit-p (tag)
3575 "Check if TAG is one that should be inherited."
3577 ((member tag org-tags-exclude-from-inheritance
) nil
)
3578 ((eq org-use-tag-inheritance t
) t
)
3579 ((not org-use-tag-inheritance
) nil
)
3580 ((stringp org-use-tag-inheritance
)
3581 (string-match org-use-tag-inheritance tag
))
3582 ((listp org-use-tag-inheritance
)
3583 (member tag org-use-tag-inheritance
))
3584 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3586 (defcustom org-tags-match-list-sublevels t
3587 "Non-nil means list also sublevels of headlines matching a search.
3588 This variable applies to tags/property searches, and also to stuck
3589 projects because this search is based on a tags match as well.
3591 When set to the symbol `indented', sublevels are indented with
3594 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3595 the sublevels of a headline matching a tag search often also match
3596 the same search. Listing all of them can create very long lists.
3597 Setting this variable to nil causes subtrees of a match to be skipped.
3599 This variable is semi-obsolete and probably should always be true. It
3600 is better to limit inheritance to certain tags using the variables
3601 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3604 (const :tag
"No, don't list them" nil
)
3605 (const :tag
"Yes, do list them" t
)
3606 (const :tag
"List them, indented with leading dots" indented
)))
3608 (defcustom org-tags-sort-function nil
3609 "When set, tags are sorted using this function as a comparator."
3612 (const :tag
"No sorting" nil
)
3613 (const :tag
"Alphabetical" string
<)
3614 (const :tag
"Reverse alphabetical" string
>)
3615 (function :tag
"Custom function" nil
)))
3617 (defvar org-tags-history nil
3618 "History of minibuffer reads for tags.")
3619 (defvar org-last-tags-completion-table nil
3620 "The last used completion table for tags.")
3621 (defvar org-after-tags-change-hook nil
3622 "Hook that is run after the tags in a line have changed.")
3624 (defgroup org-properties nil
3625 "Options concerning properties in Org mode."
3626 :tag
"Org Properties"
3629 (defcustom org-property-format
"%-10s %s"
3630 "How property key/value pairs should be formatted by `indent-line'.
3631 When `indent-line' hits a property definition, it will format the line
3632 according to this format, mainly to make sure that the values are
3633 lined-up with respect to each other."
3634 :group
'org-properties
3637 (defcustom org-properties-postprocess-alist nil
3638 "Alist of properties and functions to adjust inserted values.
3639 Elements of this alist must be of the form
3641 ([string] [function])
3643 where [string] must be a property name and [function] must be a
3644 lambda expression: this lambda expression must take one argument,
3645 the value to adjust, and return the new value as a string.
3647 For example, this element will allow the property \"Remaining\"
3648 to be updated wrt the relation between the \"Effort\" property
3649 and the clock summary:
3651 ((\"Remaining\" (lambda(value)
3652 (let ((clocksum (org-clock-sum-current-item))
3653 (effort (org-duration-to-minutes
3654 (org-entry-get (point) \"Effort\"))))
3655 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3656 :group
'org-properties
3658 :type
'(alist :key-type
(string :tag
"Property")
3659 :value-type
(function :tag
"Function")))
3661 (defcustom org-use-property-inheritance nil
3662 "Non-nil means properties apply also for sublevels.
3664 This setting is chiefly used during property searches. Turning it on can
3665 cause significant overhead when doing a search, which is why it is not
3668 When nil, only the properties directly given in the current entry count.
3669 When t, every property is inherited. The value may also be a list of
3670 properties that should have inheritance, or a regular expression matching
3671 properties that should be inherited.
3673 However, note that some special properties use inheritance under special
3674 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3675 and the properties ending in \"_ALL\" when they are used as descriptor
3676 for valid values of a property.
3678 Note for programmers:
3679 When querying an entry with `org-entry-get', you can control if inheritance
3680 should be used. By default, `org-entry-get' looks only at the local
3681 properties. You can request inheritance by setting the inherit argument
3682 to t (to force inheritance) or to `selective' (to respect the setting
3684 :group
'org-properties
3686 (const :tag
"Not" nil
)
3687 (const :tag
"Always" t
)
3688 (repeat :tag
"Specific properties" (string :tag
"Property"))
3689 (regexp :tag
"Properties matched by regexp")))
3691 (defun org-property-inherit-p (property)
3692 "Return a non-nil value if PROPERTY should be inherited."
3694 ((eq org-use-property-inheritance t
) t
)
3695 ((not org-use-property-inheritance
) nil
)
3696 ((stringp org-use-property-inheritance
)
3697 (string-match org-use-property-inheritance property
))
3698 ((listp org-use-property-inheritance
)
3699 (member-ignore-case property org-use-property-inheritance
))
3700 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3702 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3703 "The default column format, if no other format has been defined.
3704 This variable can be set on the per-file basis by inserting a line
3706 #+COLUMNS: %25ITEM ....."
3707 :group
'org-properties
3710 (defcustom org-columns-ellipses
".."
3711 "The ellipses to be used when a field in column view is truncated.
3712 When this is the empty string, as many characters as possible are shown,
3713 but then there will be no visual indication that the field has been truncated.
3714 When this is a string of length N, the last N characters of a truncated
3715 field are replaced by this string. If the column is narrower than the
3716 ellipses string, only part of the ellipses string will be shown."
3717 :group
'org-properties
3720 (defconst org-global-properties-fixed
3721 '(("VISIBILITY_ALL" .
"folded children content all")
3722 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3723 "List of property/value pairs that can be inherited by any entry.
3725 These are fixed values, for the preset properties. The user variable
3726 that can be used to add to this list is `org-global-properties'.
3728 The entries in this list are cons cells where the car is a property
3729 name and cdr is a string with the value. If the value represents
3730 multiple items like an \"_ALL\" property, separate the items by
3733 (defcustom org-global-properties nil
3734 "List of property/value pairs that can be inherited by any entry.
3736 This list will be combined with the constant `org-global-properties-fixed'.
3738 The entries in this list are cons cells where the car is a property
3739 name and cdr is a string with the value.
3741 You can set buffer-local values for the same purpose in the variable
3742 `org-file-properties' this by adding lines like
3744 #+PROPERTY: NAME VALUE"
3745 :group
'org-properties
3747 (cons (string :tag
"Property")
3748 (string :tag
"Value"))))
3750 (defvar-local org-file-properties nil
3751 "List of property/value pairs that can be inherited by any entry.
3752 Valid for the current buffer.
3753 This variable is populated from #+PROPERTY lines.")
3755 (defgroup org-agenda nil
3756 "Options concerning agenda views in Org mode."
3760 (defvar-local org-category nil
3761 "Variable used by org files to set a category for agenda display.
3762 Such files should use a file variable to set it, for example
3764 # -*- mode: org; org-category: \"ELisp\"
3766 or contain a special line
3770 If the file does not specify a category, then file's base name
3772 (put 'org-category
'safe-local-variable
(lambda (x) (or (symbolp x
) (stringp x
))))
3774 (defcustom org-agenda-files nil
3775 "The files to be used for agenda display.
3777 If an entry is a directory, all files in that directory that are matched
3778 by `org-agenda-file-regexp' will be part of the file list.
3780 If the value of the variable is not a list but a single file name, then
3781 the list of agenda files is actually stored and maintained in that file,
3782 one agenda file per line. In this file paths can be given relative to
3783 `org-directory'. Tilde expansion and environment variable substitution
3786 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3787 and removed with `\\[org-remove-file]'."
3790 (repeat :tag
"List of files and directories" file
)
3791 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3793 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3794 "Regular expression to match files for `org-agenda-files'.
3795 If any element in the list in that variable contains a directory instead
3796 of a normal file, all files in that directory that are matched by this
3797 regular expression will be included."
3801 (defcustom org-agenda-text-search-extra-files nil
3802 "List of extra files to be searched by text search commands.
3803 These files will be searched in addition to the agenda files by the
3804 commands `org-search-view' (`\\[org-agenda] s') \
3805 and `org-occur-in-agenda-files'.
3806 Note that these files will only be searched for text search commands,
3807 not for the other agenda views like todo lists, tag searches or the weekly
3808 agenda. This variable is intended to list notes and possibly archive files
3809 that should also be searched by these two commands.
3810 In fact, if the first element in the list is the symbol `agenda-archives',
3811 then all archive files of all agenda files will be added to the search
3814 :type
'(set :greedy t
3815 (const :tag
"Agenda Archives" agenda-archives
)
3816 (repeat :inline t
(file))))
3818 (defvaralias 'org-agenda-multi-occur-extra-files
3819 'org-agenda-text-search-extra-files
)
3821 (defcustom org-agenda-skip-unavailable-files nil
3822 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3823 A nil value means to remove them, after a query, from the list."
3827 (defcustom org-calendar-to-agenda-key
[?c
]
3828 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3829 The command `org-calendar-goto-agenda' will be bound to this key. The
3830 default is the character `c' because then `c' can be used to switch back and
3831 forth between agenda and calendar."
3835 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3836 "The key to be installed in `calendar-mode-map' for adding diary entries.
3837 This option is irrelevant until `org-agenda-diary-file' has been configured
3838 to point to an Org file. When that is the case, the command
3839 `org-agenda-diary-entry' will be bound to the key given here, by default
3840 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3841 if you want to continue doing this, you need to change this to a different
3846 (defcustom org-agenda-diary-file
'diary-file
3847 "File to which to add new entries with the `i' key in agenda and calendar.
3848 When this is the symbol `diary-file', the functionality in the Emacs
3849 calendar will be used to add entries to the `diary-file'. But when this
3850 points to a file, `org-agenda-diary-entry' will be used instead."
3853 (const :tag
"The standard Emacs diary file" diary-file
)
3854 (file :tag
"Special Org file diary entries")))
3856 (eval-after-load "calendar"
3858 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3859 'org-calendar-goto-agenda
)
3860 (add-hook 'calendar-mode-hook
3862 (unless (eq org-agenda-diary-file
'diary-file
)
3863 (define-key calendar-mode-map
3864 org-calendar-insert-diary-entry-key
3865 'org-agenda-diary-entry
))))))
3867 (defgroup org-latex nil
3868 "Options for embedding LaTeX code into Org mode."
3872 (defcustom org-format-latex-options
3873 '(:foreground default
:background default
:scale
1.0
3874 :html-foreground
"Black" :html-background
"Transparent"
3875 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3876 "Options for creating images from LaTeX fragments.
3877 This is a property list with the following properties:
3878 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3879 `default' means use the foreground of the default face.
3880 `auto' means use the foreground from the text face.
3881 :background the background color, or \"Transparent\".
3882 `default' means use the background of the default face.
3883 `auto' means use the background from the text face.
3884 :scale a scaling factor for the size of the images, to get more pixels
3885 :html-foreground, :html-background, :html-scale
3886 the same numbers for HTML export.
3887 :matchers a list indicating which matchers should be used to
3888 find LaTeX fragments. Valid members of this list are:
3889 \"begin\" find environments
3890 \"$1\" find single characters surrounded by $.$
3891 \"$\" find math expressions surrounded by $...$
3892 \"$$\" find math expressions surrounded by $$....$$
3893 \"\\(\" find math expressions surrounded by \\(...\\)
3894 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3898 (defcustom org-format-latex-signal-error t
3899 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3900 When nil, just push out a message."
3905 (defcustom org-latex-to-mathml-jar-file nil
3906 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3907 Use this to specify additional executable file say a jar file.
3909 When using MathToWeb as the converter, specify the full-path to
3910 your mathtoweb.jar file."
3914 (const :tag
"None" nil
)
3915 (file :tag
"JAR file" :must-match t
)))
3917 (defcustom org-latex-to-mathml-convert-command nil
3918 "Command to convert LaTeX fragments to MathML.
3919 Replace format-specifiers in the command as noted below and use
3920 `shell-command' to convert LaTeX to MathML.
3921 %j: Executable file in fully expanded form as specified by
3922 `org-latex-to-mathml-jar-file'.
3923 %I: Input LaTeX file in fully expanded form.
3924 %i: The latex fragment to be converted.
3925 %o: Output MathML file.
3927 This command is used by `org-create-math-formula'.
3929 When using MathToWeb as the converter, set this option to
3930 \"java -jar %j -unicode -force -df %o %I\".
3932 When using LaTeXML set this option to
3933 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3937 (const :tag
"None" nil
)
3938 (string :tag
"\nShell command")))
3940 (defcustom org-preview-latex-default-process
'dvipng
3941 "The default process to convert LaTeX fragments to image files.
3942 All available processes and theirs documents can be found in
3943 `org-preview-latex-process-alist', which see."
3946 :package-version
'(Org .
"9.0")
3949 (defcustom org-preview-latex-process-alist
3951 :programs
("latex" "dvipng")
3952 :description
"dvi > png"
3953 :message
"you need to install the programs: latex and dvipng."
3954 :image-input-type
"dvi"
3955 :image-output-type
"png"
3956 :image-size-adjust
(1.0 .
1.0)
3957 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
3958 :image-converter
("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3960 :programs
("latex" "dvisvgm")
3961 :description
"dvi > svg"
3962 :message
"you need to install the programs: latex and dvisvgm."
3964 :image-input-type
"dvi"
3965 :image-output-type
"svg"
3966 :image-size-adjust
(1.7 .
1.5)
3967 :latex-compiler
("latex -interaction nonstopmode -output-directory %o %f")
3968 :image-converter
("dvisvgm %f -n -b min -c %S -o %O"))
3970 :programs
("latex" "convert")
3971 :description
"pdf > png"
3972 :message
"you need to install the programs: latex and imagemagick."
3974 :image-input-type
"pdf"
3975 :image-output-type
"png"
3976 :image-size-adjust
(1.0 .
1.0)
3977 :latex-compiler
("pdflatex -interaction nonstopmode -output-directory %o %f")
3979 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3980 "Definitions of external processes for LaTeX previewing.
3981 Org mode can use some external commands to generate TeX snippet's images for
3982 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3983 `org-create-formula-image' how to call them.
3985 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3986 PROPERTIES accepts the following attributes:
3988 :programs list of strings, required programs.
3989 :description string, describe the process.
3990 :message string, message it when required programs cannot be found.
3991 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3992 :image-output-type string, output file type of image converter (e.g., \"png\").
3993 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3994 deal with background and foreground color of image.
3995 Otherwise, dvipng style background and foreground color
3996 format are generated. You may then refer to them in
3997 command options with \"%F\" and \"%B\".
3998 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3999 image size showed in buffer and the cdr element is for
4000 HTML file. This option is only useful for process
4001 developers, users should use variable
4002 `org-format-latex-options' instead.
4003 :post-clean list of strings, files matched are to be cleaned up once
4004 the image is generated. When nil, the files with \".dvi\",
4005 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4006 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4008 :latex-header list of strings, the LaTeX header of the snippet file.
4009 When nil, the fallback value is used instead, which is
4010 controlled by `org-format-latex-header',
4011 `org-latex-default-packages-alist' and
4012 `org-latex-packages-alist', which see.
4013 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4014 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4015 replaced with values defined below.
4016 :image-converter list of image converter commands strings. Each of them is
4017 given to the shell and supports any of the following
4018 place-holders defined below.
4020 Place-holders used by `:image-converter' and `:latex-compiler':
4023 %b base name of input file
4024 %o base directory of input file
4025 %O absolute output file name
4027 Place-holders only used by `:image-converter':
4029 %F foreground of image
4030 %B background of image
4031 %D dpi, which is used to adjust image size by some processing commands.
4032 %S the image size scale ratio, which is used to adjust image size by some
4033 processing commands."
4036 :package-version
'(Org .
"9.0")
4037 :type
'(alist :tag
"LaTeX to image backends"
4038 :value-type
(plist)))
4040 (defcustom org-preview-latex-image-directory
"ltximg/"
4041 "Path to store latex preview images.
4042 A relative path here creates many directories relative to the
4043 processed org files paths. An absolute path puts all preview
4044 images at the same place."
4047 :package-version
'(Org .
"9.0")
4050 (defun org-format-latex-mathml-available-p ()
4051 "Return t if `org-latex-to-mathml-convert-command' is usable."
4053 (when (and (boundp 'org-latex-to-mathml-convert-command
)
4054 org-latex-to-mathml-convert-command
)
4055 (let ((executable (car (split-string
4056 org-latex-to-mathml-convert-command
))))
4057 (when (executable-find executable
)
4059 "%j" org-latex-to-mathml-convert-command
)
4060 (file-readable-p org-latex-to-mathml-jar-file
)
4063 (defcustom org-format-latex-header
"\\documentclass{article}
4064 \\usepackage[usenames]{color}
4067 \\pagestyle{empty} % do not remove
4068 % The settings below are copied from fullpage.sty
4069 \\setlength{\\textwidth}{\\paperwidth}
4070 \\addtolength{\\textwidth}{-3cm}
4071 \\setlength{\\oddsidemargin}{1.5cm}
4072 \\addtolength{\\oddsidemargin}{-2.54cm}
4073 \\setlength{\\evensidemargin}{\\oddsidemargin}
4074 \\setlength{\\textheight}{\\paperheight}
4075 \\addtolength{\\textheight}{-\\headheight}
4076 \\addtolength{\\textheight}{-\\headsep}
4077 \\addtolength{\\textheight}{-\\footskip}
4078 \\addtolength{\\textheight}{-3cm}
4079 \\setlength{\\topmargin}{1.5cm}
4080 \\addtolength{\\topmargin}{-2.54cm}"
4081 "The document header used for processing LaTeX fragments.
4082 It is imperative that this header make sure that no page number
4083 appears on the page. The package defined in the variables
4084 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4085 will either replace the placeholder \"[PACKAGES]\" in this
4086 header, or they will be appended."
4090 (defun org-set-packages-alist (var val
)
4091 "Set the packages alist and make sure it has 3 elements per entry."
4092 (set var
(mapcar (lambda (x)
4093 (if (and (consp x
) (= (length x
) 2))
4094 (list (car x
) (nth 1 x
) t
)
4098 (defun org-get-packages-alist (var)
4099 "Get the packages alist and make sure it has 3 elements per entry."
4101 (if (and (consp x
) (= (length x
) 2))
4102 (list (car x
) (nth 1 x
) t
)
4104 (default-value var
)))
4106 (defcustom org-latex-default-packages-alist
4107 '(("AUTO" "inputenc" t
("pdflatex"))
4108 ("T1" "fontenc" t
("pdflatex"))
4111 ("" "longtable" nil
)
4114 ("normalem" "ulem" t
)
4119 ("" "hyperref" nil
))
4120 "Alist of default packages to be inserted in the header.
4122 Change this only if one of the packages here causes an
4123 incompatibility with another package you are using.
4125 The packages in this list are needed by one part or another of
4126 Org mode to function properly:
4128 - inputenc, fontenc: for basic font and character selection
4129 - graphicx: for including images
4130 - grffile: allow periods and spaces in graphics file names
4131 - longtable: For multipage tables
4132 - wrapfig: for figure placement
4133 - rotating: for sideways figures and tables
4134 - ulem: for underline and strike-through
4135 - amsmath: for subscript and superscript and math environments
4136 - textcomp, amssymb: for various symbols used
4137 for interpreting the entities in `org-entities'. You can skip
4138 some of these packages if you don't use any of their symbols.
4139 - capt-of: for captions outside of floats
4140 - hyperref: for cross references
4142 Therefore you should not modify this variable unless you know
4143 what you are doing. The one reason to change it anyway is that
4144 you might be loading some other package that conflicts with one
4145 of the default packages. Each element is either a cell or
4148 A cell is of the format
4150 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4152 If SNIPPET-FLAG is non-nil, the package also needs to be included
4153 when compiling LaTeX snippets into images for inclusion into
4154 non-LaTeX output. COMPILERS is a list of compilers that should
4155 include the package, see `org-latex-compiler'. If the document
4156 compiler is not in the list, and the list is non-nil, the package
4157 will not be inserted in the final document.
4159 A string will be inserted as-is in the header of the document."
4161 :group
'org-export-latex
4162 :set
'org-set-packages-alist
4163 :get
'org-get-packages-alist
4165 :package-version
'(Org .
"8.3")
4168 (list :tag
"options/package pair"
4169 (string :tag
"options")
4170 (string :tag
"package")
4171 (boolean :tag
"Snippet")
4173 (const :tag
"For all compilers" nil
)
4174 (repeat :tag
"Allowed compiler" string
)))
4175 (string :tag
"A line of LaTeX"))))
4177 (defcustom org-latex-packages-alist nil
4178 "Alist of packages to be inserted in every LaTeX header.
4180 These will be inserted after `org-latex-default-packages-alist'.
4181 Each element is either a cell or a string.
4183 A cell is of the format:
4185 (\"options\" \"package\" SNIPPET-FLAG)
4187 SNIPPET-FLAG, when non-nil, indicates that this package is also
4188 needed when turning LaTeX snippets into images for inclusion into
4191 A string will be inserted as-is in the header of the document.
4193 Make sure that you only list packages here which:
4195 - you want in every file;
4196 - do not conflict with the setup in `org-format-latex-header';
4197 - do not conflict with the default packages in
4198 `org-latex-default-packages-alist'."
4200 :group
'org-export-latex
4201 :set
'org-set-packages-alist
4202 :get
'org-get-packages-alist
4205 (list :tag
"options/package pair"
4206 (string :tag
"options")
4207 (string :tag
"package")
4208 (boolean :tag
"Snippet"))
4209 (string :tag
"A line of LaTeX"))))
4211 (defgroup org-appearance nil
4212 "Settings for Org mode appearance."
4213 :tag
"Org Appearance"
4216 (defcustom org-level-color-stars-only nil
4217 "Non-nil means fontify only the stars in each headline.
4218 When nil, the entire headline is fontified.
4219 Changing it requires restart of `font-lock-mode' to become effective
4220 also in regions already fontified."
4221 :group
'org-appearance
4224 (defcustom org-hide-leading-stars nil
4225 "Non-nil means hide the first N-1 stars in a headline.
4226 This works by using the face `org-hide' for these stars. This
4227 face is white for a light background, and black for a dark
4228 background. You may have to customize the face `org-hide' to
4230 Changing it requires restart of `font-lock-mode' to become effective
4231 also in regions already fontified.
4232 You may also set this on a per-file basis by adding one of the following
4233 lines to the buffer:
4235 #+STARTUP: hidestars
4236 #+STARTUP: showstars"
4237 :group
'org-appearance
4240 (defcustom org-hidden-keywords nil
4241 "List of symbols corresponding to keywords to be hidden the org buffer.
4242 For example, a value \\='(title) for this list will make the document's title
4243 appear in the buffer without the initial #+TITLE: keyword."
4244 :group
'org-appearance
4246 :type
'(set (const :tag
"#+AUTHOR" author
)
4247 (const :tag
"#+DATE" date
)
4248 (const :tag
"#+EMAIL" email
)
4249 (const :tag
"#+TITLE" title
)))
4251 (defcustom org-custom-properties nil
4252 "List of properties (as strings) with a special meaning.
4253 The default use of these custom properties is to let the user
4254 hide them with `org-toggle-custom-properties-visibility'."
4255 :group
'org-properties
4256 :group
'org-appearance
4258 :type
'(repeat (string :tag
"Property Name")))
4260 (defcustom org-fontify-done-headline nil
4261 "Non-nil means change the face of a headline if it is marked DONE.
4262 Normally, only the TODO/DONE keyword indicates the state of a headline.
4263 When this is non-nil, the headline after the keyword is set to the
4264 `org-headline-done' as an additional indication."
4265 :group
'org-appearance
4268 (defcustom org-fontify-emphasized-text t
4269 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4270 Changing this variable requires a restart of Emacs to take effect."
4271 :group
'org-appearance
4274 (defcustom org-fontify-whole-heading-line nil
4275 "Non-nil means fontify the whole line for headings.
4276 This is useful when setting a background color for the
4278 :group
'org-appearance
4281 (defcustom org-highlight-latex-and-related nil
4282 "Non-nil means highlight LaTeX related syntax in the buffer.
4283 When non nil, the value should be a list containing any of the
4285 `latex' Highlight LaTeX snippets and environments.
4286 `script' Highlight subscript and superscript.
4287 `entities' Highlight entities."
4288 :group
'org-appearance
4290 :package-version
'(Org .
"8.0")
4292 (const :tag
"No highlighting" nil
)
4293 (set :greedy t
:tag
"Highlight"
4294 (const :tag
"LaTeX snippets and environments" latex
)
4295 (const :tag
"Subscript and superscript" script
)
4296 (const :tag
"Entities" entities
))))
4298 (defcustom org-hide-emphasis-markers nil
4299 "Non-nil mean font-lock should hide the emphasis marker characters."
4300 :group
'org-appearance
4303 (defcustom org-hide-macro-markers nil
4304 "Non-nil mean font-lock should hide the brackets marking macro calls."
4305 :group
'org-appearance
4308 (defcustom org-pretty-entities nil
4309 "Non-nil means show entities as UTF8 characters.
4310 When nil, the \\name form remains in the buffer."
4311 :group
'org-appearance
4315 (defcustom org-pretty-entities-include-sub-superscripts t
4316 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4317 :group
'org-appearance
4321 (defvar org-emph-re nil
4322 "Regular expression for matching emphasis.
4323 After a match, the match groups contain these elements:
4324 0 The match of the full regular expression, including the characters
4325 before and after the proper match
4326 1 The character before the proper match, or empty at beginning of line
4327 2 The proper match, including the leading and trailing markers
4328 3 The leading marker like * or /, indicating the type of highlighting
4329 4 The text between the emphasis markers, not including the markers
4330 5 The character after the match, empty at the end of a line")
4332 (defvar org-verbatim-re nil
4333 "Regular expression for matching verbatim text.")
4335 (defvar org-emphasis-regexp-components
) ; defined just below
4336 (defvar org-emphasis-alist
) ; defined just below
4337 (defun org-set-emph-re (var val
)
4338 "Set variable and compute the emphasis regular expression."
4340 (when (and (boundp 'org-emphasis-alist
)
4341 (boundp 'org-emphasis-regexp-components
)
4342 org-emphasis-alist org-emphasis-regexp-components
)
4344 ((`(,pre
,post
,border
,body
,nl
) org-emphasis-regexp-components
)
4345 (body (if (<= nl
0) body
4346 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl
)))
4348 (format (concat "\\([%s]\\|^\\)" ;before markers
4349 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4350 "\\([%s]\\|$\\)") ;after markers
4351 pre border border body border post
)))
4352 (setq org-emph-re
(format template
"*/_+"))
4353 (setq org-verbatim-re
(format template
"=~")))))
4355 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4356 ;; set this option proved cumbersome. See this message/thread:
4357 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4358 (defvar org-emphasis-regexp-components
4359 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4360 "Components used to build the regular expression for emphasis.
4361 This is a list with five entries. Terminology: In an emphasis string
4362 like \" *strong word* \", we call the initial space PREMATCH, the final
4363 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4364 and \"trong wor\" is the body. The different components in this variable
4365 specify what is allowed/forbidden in each part:
4367 pre Chars allowed as prematch. Beginning of line will be allowed too.
4368 post Chars allowed as postmatch. End of line will be allowed too.
4369 border The chars *forbidden* as border characters.
4370 body-regexp A regexp like \".\" to match a body character. Don't use
4371 non-shy groups here, and don't allow newline here.
4372 newline The maximum number of newlines allowed in an emphasis exp.
4374 You need to reload Org or to restart Emacs after customizing this.")
4376 (defcustom org-emphasis-alist
4380 ("=" org-verbatim verbatim
)
4381 ("~" org-code verbatim
)
4382 ("+" (:strike-through t
)))
4383 "Alist of characters and faces to emphasize text.
4384 Text starting and ending with a special character will be emphasized,
4385 for example *bold*, _underlined_ and /italic/. This variable sets the
4386 marker characters and the face to be used by font-lock for highlighting
4389 You need to reload Org or to restart Emacs after customizing this."
4390 :group
'org-appearance
4391 :set
'org-set-emph-re
4393 :package-version
'(Org .
"8.0")
4396 (string :tag
"Marker character")
4398 (face :tag
"Font-lock-face")
4399 (plist :tag
"Face property list"))
4400 (option (const verbatim
)))))
4402 (defvar org-protecting-blocks
'("src" "example" "export")
4403 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4404 This is needed for font-lock setup.")
4406 ;;; Functions and variables from their packages
4407 ;; Declared here to avoid compiler warnings
4408 (defvar mark-active
)
4411 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4412 (declare-function calendar-forward-day
"cal-move" (arg))
4413 (declare-function calendar-goto-date
"cal-move" (date))
4414 (declare-function calendar-goto-today
"cal-move" ())
4415 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4416 (declare-function calendar-iso-to-absolute
"cal-iso" (date))
4417 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4418 (declare-function cdlatex-tab
"ext:cdlatex" ())
4419 (declare-function dired-get-filename
4421 (&optional localp no-error-if-not-filep
))
4422 (declare-function iswitchb-read-buffer
4425 default require-match _predicate start matches-set
))
4426 (declare-function org-agenda-change-all-lines
4428 (newhead hdmarker
&optional fixface just-this
))
4429 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4432 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4433 (declare-function org-agenda-format-item
4435 (extra txt
&optional level category tags dotime
4437 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4438 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4439 (declare-function org-agenda-save-markers-for-cut-and-paste
4442 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4443 (declare-function org-agenda-skip
"org-agenda" ())
4444 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4445 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4446 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4447 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4448 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4449 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4450 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4451 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4452 (declare-function parse-time-string
"parse-time" (string))
4453 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4455 (defvar align-mode-rules-list
)
4456 (defvar calc-embedded-close-formula
)
4457 (defvar calc-embedded-open-formula
)
4458 (defvar calc-embedded-open-mode
)
4459 (defvar font-lock-unfontify-region-function
)
4460 (defvar iswitchb-temp-buflist
)
4461 (defvar org-agenda-tags-todo-honor-ignore-options
)
4462 (defvar remember-data-file
)
4463 (defvar texmathp-why
)
4466 (defun turn-on-orgtbl ()
4467 "Unconditionally turn on `orgtbl-mode'."
4468 (require 'org-table
)
4471 (defun org-at-table-p (&optional table-type
)
4472 "Non-nil if the cursor is inside an Org table.
4473 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4474 (and (org-match-line (if table-type
"[ \t]*[|+]" "[ \t]*|"))
4475 (or (not (derived-mode-p 'org-mode
))
4476 (let ((e (org-element-lineage (org-element-at-point) '(table) t
)))
4477 (and e
(or table-type
4478 (eq 'org
(org-element-property :type e
))))))))
4480 (defun org-at-table.el-p
()
4481 "Non-nil when point is at a table.el table."
4482 (and (org-match-line "[ \t]*[|+]")
4483 (let ((element (org-element-at-point)))
4484 (and (eq (org-element-type element
) 'table
)
4485 (eq (org-element-property :type element
) 'table.el
)))))
4487 (defun org-at-table-hline-p ()
4488 "Non-nil when point is inside a hline in a table.
4489 Assume point is already in a table."
4490 (org-match-line org-table-hline-regexp
))
4492 (defun org-table-map-tables (function &optional quietly
)
4493 "Apply FUNCTION to the start of all tables in the buffer."
4494 (org-with-wide-buffer
4495 (goto-char (point-min))
4496 (while (re-search-forward org-table-any-line-regexp nil t
)
4498 (message "Mapping tables: %d%%"
4499 (floor (* 100.0 (point)) (buffer-size))))
4500 (beginning-of-line 1)
4501 (when (and (looking-at org-table-line-regexp
)
4502 ;; Exclude tables in src/example/verbatim/clocktable blocks
4503 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4504 (save-excursion (funcall function
))
4505 (or (looking-at org-table-line-regexp
)
4507 (re-search-forward org-table-any-border-regexp nil
1)))
4508 (unless quietly
(message "Mapping tables: done")))
4510 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4511 (declare-function org-clock-update-mode-line
"org-clock" ())
4512 (declare-function org-resolve-clocks
"org-clock"
4513 (&optional also-non-dangling-p prompt last-valid
))
4515 (defun org-at-TBLFM-p (&optional pos
)
4516 "Non-nil when point (or POS) is in #+TBLFM line."
4518 (goto-char (or pos
(point)))
4520 (and (let ((case-fold-search t
)) (looking-at org-TBLFM-regexp
))
4521 (eq (org-element-type (org-element-at-point)) 'table
))))
4523 (defvar org-clock-start-time
)
4524 (defvar org-clock-marker
(make-marker)
4525 "Marker recording the last clock-in.")
4526 (defvar org-clock-hd-marker
(make-marker)
4527 "Marker recording the last clock-in, but the headline position.")
4528 (defvar org-clock-heading
""
4529 "The heading of the current clock entry.")
4530 (defun org-clock-is-active ()
4531 "Return the buffer where the clock is currently running.
4532 Return nil if no clock is running."
4533 (marker-buffer org-clock-marker
))
4535 (defun org-check-running-clock ()
4536 "Check if the current buffer contains the running clock.
4537 If yes, offer to stop it and to save the buffer with the changes."
4538 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4539 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4542 (when (y-or-n-p "Save changed buffer?")
4545 (defun org-clocktable-try-shift (dir n
)
4546 "Check if this line starts a clock table, if yes, shift the time block."
4547 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4548 (org-clocktable-shift dir n
)))
4551 (defun org-clock-persistence-insinuate ()
4552 "Set up hooks for clock persistence."
4553 (require 'org-clock
)
4554 (add-hook 'org-mode-hook
'org-clock-load
)
4555 (add-hook 'kill-emacs-hook
'org-clock-save
))
4557 (defgroup org-archive nil
4558 "Options concerning archiving in Org mode."
4560 :group
'org-structure
)
4562 (defcustom org-archive-location
"%s_archive::"
4563 "The location where subtrees should be archived.
4565 The value of this variable is a string, consisting of two parts,
4566 separated by a double-colon. The first part is a filename and
4567 the second part is a headline.
4569 When the filename is omitted, archiving happens in the same file.
4570 %s in the filename will be replaced by the current file
4571 name (without the directory part). Archiving to a different file
4572 is useful to keep archived entries from contributing to the
4575 The archived entries will be filed as subtrees of the specified
4576 headline. When the headline is omitted, the subtrees are simply
4577 filed away at the end of the file, as top-level entries. Also in
4578 the heading you can use %s to represent the file name, this can be
4579 useful when using the same archive for a number of different files.
4581 Here are a few examples:
4583 If the current file is Projects.org, archive in file
4584 Projects.org_archive, as top-level trees. This is the default.
4586 \"::* Archived Tasks\"
4587 Archive in the current file, under the top-level headline
4588 \"* Archived Tasks\".
4590 \"~/org/archive.org::\"
4591 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4593 \"~/org/archive.org::* From %s\"
4594 Archive in file ~/org/archive.org (absolute path), under headlines
4595 \"From FILENAME\" where file name is the current file name.
4597 \"~/org/datetree.org::datetree/* Finished Tasks\"
4598 The \"datetree/\" string is special, signifying to archive
4599 items to the datetree. Items are placed in either the CLOSED
4600 date of the item, or the current date if there is no CLOSED date.
4601 The heading will be a subentry to the current date. There doesn't
4602 need to be a heading, but there always needs to be a slash after
4603 datetree. For example, to store archived items directly in the
4604 datetree, use \"~/org/datetree.org::datetree/\".
4606 \"basement::** Finished Tasks\"
4607 Archive in file ./basement (relative path), as level 3 trees
4608 below the level 2 heading \"** Finished Tasks\".
4610 You may set this option on a per-file basis by adding to the buffer a
4613 #+ARCHIVE: basement::** Finished Tasks
4615 You may also define it locally for a subtree by setting an ARCHIVE property
4616 in the entry. If such a property is found in an entry, or anywhere up
4617 the hierarchy, it will be used."
4621 (defcustom org-agenda-skip-archived-trees t
4622 "Non-nil means the agenda will skip any items located in archived trees.
4623 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4624 variable is no longer recommended, you should leave it at the value t.
4625 Instead, use the key `v' to cycle the archives-mode in the agenda."
4627 :group
'org-agenda-skip
4630 (defcustom org-columns-skip-archived-trees t
4631 "Non-nil means ignore archived trees when creating column view."
4633 :group
'org-properties
4636 (defcustom org-cycle-open-archived-trees nil
4637 "Non-nil means `org-cycle' will open archived trees.
4638 An archived tree is a tree marked with the tag ARCHIVE.
4639 When nil, archived trees will stay folded. You can still open them with
4640 normal outline commands like `show-all', but not with the cycling commands."
4645 (defcustom org-sparse-tree-open-archived-trees nil
4646 "Non-nil means sparse tree construction shows matches in archived trees.
4647 When nil, matches in these trees are highlighted, but the trees are kept in
4650 :group
'org-sparse-trees
4653 (defcustom org-sparse-tree-default-date-type nil
4654 "The default date type when building a sparse tree.
4655 When this is nil, a date is a scheduled or a deadline timestamp.
4656 Otherwise, these types are allowed:
4659 active: only active timestamps (<...>)
4660 inactive: only inactive timestamps ([...])
4661 scheduled: only scheduled timestamps
4662 deadline: only deadline timestamps"
4663 :type
'(choice (const :tag
"Scheduled or deadline" nil
)
4664 (const :tag
"All timestamps" all
)
4665 (const :tag
"Only active timestamps" active
)
4666 (const :tag
"Only inactive timestamps" inactive
)
4667 (const :tag
"Only scheduled timestamps" scheduled
)
4668 (const :tag
"Only deadline timestamps" deadline
)
4669 (const :tag
"Only closed timestamps" closed
))
4671 :package-version
'(Org .
"8.3")
4672 :group
'org-sparse-trees
)
4674 (defun org-cycle-hide-archived-subtrees (state)
4675 "Re-hide all archived subtrees after a visibility state change.
4676 STATE should be one of the symbols listed in the docstring of
4678 (when (and (not org-cycle-open-archived-trees
)
4679 (not (memq state
'(overview folded
))))
4681 (let* ((globalp (memq state
'(contents all
)))
4682 (beg (if globalp
(point-min) (point)))
4683 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4684 (org-hide-archived-subtrees beg end
)
4686 (when (looking-at-p (concat ".*:" org-archive-tag
":"))
4687 (message "%s" (substitute-command-keys
4688 "Subtree is archived and stays closed. Use \
4689 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4691 (defun org-force-cycle-archived ()
4692 "Cycle subtree even if it is archived."
4694 (setq this-command
'org-cycle
)
4695 (let ((org-cycle-open-archived-trees t
))
4696 (call-interactively 'org-cycle
)))
4698 (defun org-hide-archived-subtrees (beg end
)
4699 "Re-hide all archived subtrees after a visibility state change."
4700 (org-with-wide-buffer
4701 (let ((case-fold-search nil
)
4702 (re (concat org-outline-regexp-bol
".*:" org-archive-tag
":")))
4704 ;; Include headline point is currently on.
4706 (while (and (< (point) end
) (re-search-forward re end t
))
4707 (when (member org-archive-tag
(org-get-tags))
4708 (org-flag-subtree t
)
4709 (org-end-of-subtree t
))))))
4711 (declare-function outline-end-of-heading
"outline" ())
4712 (declare-function outline-flag-region
"outline" (from to flag
))
4713 (defun org-flag-subtree (flag)
4715 (org-back-to-heading t
)
4716 (outline-end-of-heading)
4717 (outline-flag-region (point)
4718 (progn (org-end-of-subtree t
) (point))
4721 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4723 ;; Declare Column View Code
4725 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4726 (declare-function org-columns-compute
"org-colview" (property))
4730 (declare-function org-id-store-link
"org-id")
4731 (declare-function org-id-locations-load
"org-id")
4732 (declare-function org-id-locations-save
"org-id")
4733 (defvar org-id-track-globally
)
4735 ;;; Variables for pre-computed regular expressions, all buffer local
4737 (defvar-local org-todo-regexp nil
4738 "Matches any of the TODO state keywords.
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-not-done-regexp nil
4743 "Matches any of the TODO state keywords except the last one.
4744 Since TODO keywords are case-sensitive, `case-fold-search' is
4745 expected to be bound to nil when matching against this regexp.")
4747 (defvar-local org-not-done-heading-regexp nil
4748 "Matches a TODO headline that is not done.
4749 Since TODO keywords are case-sensitive, `case-fold-search' is
4750 expected to be bound to nil when matching against this regexp.")
4752 (defvar-local org-todo-line-regexp nil
4753 "Matches a headline and puts TODO state into group 2 if present.
4754 Since TODO keywords are case-sensitive, `case-fold-search' is
4755 expected to be bound to nil when matching against this regexp.")
4757 (defvar-local org-complex-heading-regexp nil
4758 "Matches a headline and puts everything into groups:
4761 group 2: The TODO keyword, maybe
4762 group 3: Priority cookie
4763 group 4: True headline
4766 Since TODO keywords are case-sensitive, `case-fold-search' is
4767 expected to be bound to nil when matching against this regexp.")
4769 (defvar-local org-complex-heading-regexp-format nil
4770 "Printf format to make regexp to match an exact headline.
4771 This regexp will match the headline of any node which has the
4772 exact headline text that is put into the format, but may have any
4773 TODO state, priority and tags.")
4775 (defvar-local org-todo-line-tags-regexp nil
4776 "Matches a headline and puts TODO state into group 2 if present.
4777 Also put tags into group 4 if tags are present.")
4779 (defconst org-plain-time-of-day-regexp
4782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4785 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4787 "Regular expression to match a plain time or time range.
4788 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4789 groups carry important information:
4791 1 the first time, range or not
4792 8 the second time, if it is a range.")
4794 (defconst org-plain-time-extension-regexp
4797 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4798 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4799 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4800 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4801 groups carry important information:
4804 9 minutes of duration")
4806 (defconst org-stamp-time-of-day-regexp
4808 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4809 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4811 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4812 "Regular expression to match a timestamp time or time range.
4813 After a match, the following groups carry important information:
4815 1 date plus weekday, for back referencing to make sure both times are on the same day
4816 2 the first time, range or not
4817 4 the second time, if it is a range.")
4819 (defconst org-startup-options
4820 '(("fold" org-startup-folded t
)
4821 ("overview" org-startup-folded t
)
4822 ("nofold" org-startup-folded nil
)
4823 ("showall" org-startup-folded nil
)
4824 ("showeverything" org-startup-folded showeverything
)
4825 ("content" org-startup-folded content
)
4826 ("indent" org-startup-indented t
)
4827 ("noindent" org-startup-indented nil
)
4828 ("hidestars" org-hide-leading-stars t
)
4829 ("showstars" org-hide-leading-stars nil
)
4830 ("odd" org-odd-levels-only t
)
4831 ("oddeven" org-odd-levels-only nil
)
4832 ("align" org-startup-align-all-tables t
)
4833 ("noalign" org-startup-align-all-tables nil
)
4834 ("inlineimages" org-startup-with-inline-images t
)
4835 ("noinlineimages" org-startup-with-inline-images nil
)
4836 ("latexpreview" org-startup-with-latex-preview t
)
4837 ("nolatexpreview" org-startup-with-latex-preview nil
)
4838 ("customtime" org-display-custom-times t
)
4839 ("logdone" org-log-done time
)
4840 ("lognotedone" org-log-done note
)
4841 ("nologdone" org-log-done nil
)
4842 ("lognoteclock-out" org-log-note-clock-out t
)
4843 ("nolognoteclock-out" org-log-note-clock-out nil
)
4844 ("logrepeat" org-log-repeat state
)
4845 ("lognoterepeat" org-log-repeat note
)
4846 ("logdrawer" org-log-into-drawer t
)
4847 ("nologdrawer" org-log-into-drawer nil
)
4848 ("logstatesreversed" org-log-states-order-reversed t
)
4849 ("nologstatesreversed" org-log-states-order-reversed nil
)
4850 ("nologrepeat" org-log-repeat nil
)
4851 ("logreschedule" org-log-reschedule time
)
4852 ("lognotereschedule" org-log-reschedule note
)
4853 ("nologreschedule" org-log-reschedule nil
)
4854 ("logredeadline" org-log-redeadline time
)
4855 ("lognoteredeadline" org-log-redeadline note
)
4856 ("nologredeadline" org-log-redeadline nil
)
4857 ("logrefile" org-log-refile time
)
4858 ("lognoterefile" org-log-refile note
)
4859 ("nologrefile" org-log-refile nil
)
4860 ("fninline" org-footnote-define-inline t
)
4861 ("nofninline" org-footnote-define-inline nil
)
4862 ("fnlocal" org-footnote-section nil
)
4863 ("fnauto" org-footnote-auto-label t
)
4864 ("fnprompt" org-footnote-auto-label nil
)
4865 ("fnconfirm" org-footnote-auto-label confirm
)
4866 ("fnplain" org-footnote-auto-label plain
)
4867 ("fnadjust" org-footnote-auto-adjust t
)
4868 ("nofnadjust" org-footnote-auto-adjust nil
)
4869 ("constcgs" constants-unit-system cgs
)
4870 ("constSI" constants-unit-system SI
)
4871 ("noptag" org-tag-persistent-alist nil
)
4872 ("hideblocks" org-hide-block-startup t
)
4873 ("nohideblocks" org-hide-block-startup nil
)
4874 ("beamer" org-startup-with-beamer-mode t
)
4875 ("entitiespretty" org-pretty-entities t
)
4876 ("entitiesplain" org-pretty-entities nil
))
4877 "Variable associated with STARTUP options for Org.
4878 Each element is a list of three items: the startup options (as written
4879 in the #+STARTUP line), the corresponding variable, and the value to set
4880 this variable to if the option is found. An optional forth element PUSH
4881 means to push this value onto the list in the variable.")
4883 (defcustom org-group-tags t
4884 "When non-nil (the default), use group tags.
4885 This can be turned on/off through `org-toggle-tags-groups'."
4890 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4892 (defun org-toggle-tags-groups ()
4893 "Toggle support for group tags.
4894 Support for group tags is controlled by the option
4895 `org-group-tags', which is non-nil by default."
4897 (setq org-group-tags
(not org-group-tags
))
4898 (cond ((and (derived-mode-p 'org-agenda-mode
)
4901 ((derived-mode-p 'org-mode
)
4902 (let ((org-inhibit-startup t
)) (org-mode))))
4903 (message "Groups tags support has been turned %s"
4904 (if org-group-tags
"on" "off")))
4906 (defun org-set-regexps-and-options (&optional tags-only
)
4907 "Precompute regular expressions used in the current buffer.
4908 When optional argument TAGS-ONLY is non-nil, only compute tags
4909 related expressions."
4910 (when (derived-mode-p 'org-mode
)
4911 (let ((alist (org--setup-collect-keywords
4912 (org-make-options-regexp
4913 (append '("FILETAGS" "TAGS" "SETUPFILE")
4914 (and (not tags-only
)
4915 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4916 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4917 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4918 ;; Startup options. Get this early since it does change
4919 ;; behavior for other options (e.g., tags).
4920 (let ((startup (cdr (assq 'startup alist
))))
4921 (dolist (option startup
)
4922 (let ((entry (assoc-string option org-startup-options t
)))
4924 (let ((var (nth 1 entry
))
4925 (val (nth 2 entry
)))
4926 (if (not (nth 3 entry
)) (set (make-local-variable var
) val
)
4927 (unless (listp (symbol-value var
))
4928 (set (make-local-variable var
) nil
))
4929 (add-to-list var val
)))))))
4930 (setq-local org-file-tags
4931 (mapcar #'org-add-prop-inherited
4932 (cdr (assq 'filetags alist
))))
4933 (setq org-current-tag-alist
4934 (append org-tag-persistent-alist
4935 (let ((tags (cdr (assq 'tags alist
))))
4936 (if tags
(org-tag-string-to-alist tags
)
4938 (setq org-tag-groups-alist
4939 (org-tag-alist-to-groups org-current-tag-alist
))
4942 (setq-local org-file-properties
(cdr (assq 'property alist
)))
4943 ;; Archive location.
4944 (let ((archive (cdr (assq 'archive alist
))))
4945 (when archive
(setq-local org-archive-location archive
)))
4947 (let ((cat (org-string-nw-p (cdr (assq 'category alist
)))))
4949 (setq-local org-category
(intern cat
))
4950 (setq-local org-file-properties
4951 (org--update-property-plist
4952 "CATEGORY" cat org-file-properties
))))
4954 (let ((column (cdr (assq 'columns alist
))))
4955 (when column
(setq-local org-columns-default-format column
)))
4957 (setq org-table-formula-constants-local
(cdr (assq 'constants alist
)))
4958 ;; Link abbreviations.
4959 (let ((links (cdr (assq 'link alist
))))
4960 (when links
(setq org-link-abbrev-alist-local
(nreverse links
))))
4962 (let ((priorities (cdr (assq 'priorities alist
))))
4964 (setq-local org-highest-priority
(nth 0 priorities
))
4965 (setq-local org-lowest-priority
(nth 1 priorities
))
4966 (setq-local org-default-priority
(nth 2 priorities
))))
4968 (let ((scripts (assq 'scripts alist
)))
4970 (setq-local org-use-sub-superscripts
(cdr scripts
))))
4972 (setq-local org-todo-kwd-alist nil
)
4973 (setq-local org-todo-key-alist nil
)
4974 (setq-local org-todo-key-trigger nil
)
4975 (setq-local org-todo-keywords-1 nil
)
4976 (setq-local org-done-keywords nil
)
4977 (setq-local org-todo-heads nil
)
4978 (setq-local org-todo-sets nil
)
4979 (setq-local org-todo-log-states nil
)
4980 (let ((todo-sequences
4981 (or (nreverse (cdr (assq 'todo alist
)))
4982 (let ((d (default-value 'org-todo-keywords
)))
4983 (if (not (stringp (car d
))) d
4984 ;; XXX: Backward compatibility code.
4985 (list (cons org-todo-interpretation d
)))))))
4986 (dolist (sequence todo-sequences
)
4987 (let* ((sequence (or (run-hook-with-args-until-success
4988 'org-todo-setup-filter-hook sequence
)
4990 (sequence-type (car sequence
))
4991 (keywords (cdr sequence
))
4992 (sep (member "|" keywords
))
4994 (dolist (k (remove "|" keywords
))
4995 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4997 (error "Invalid TODO keyword %s" k
))
4998 (let ((name (match-string 1 k
))
4999 (key (match-string 2 k
))
5000 (log (org-extract-log-state-settings k
)))
5002 (push (cons name
(and key
(string-to-char key
))) alist
)
5003 (when log
(push log org-todo-log-states
))))
5004 (let* ((names (nreverse names
))
5005 (done (if sep
(org-remove-keyword-keys (cdr sep
))
5008 (tail (list sequence-type head
(car done
) (org-last done
))))
5009 (add-to-list 'org-todo-heads head
'append
)
5010 (push names org-todo-sets
)
5011 (setq org-done-keywords
(append org-done-keywords done nil
))
5012 (setq org-todo-keywords-1
(append org-todo-keywords-1 names nil
))
5013 (setq org-todo-key-alist
5014 (append org-todo-key-alist
5016 (append '((:startgroup
))
5019 (dolist (k names
) (push (cons k tail
) org-todo-kwd-alist
))))))
5020 (setq org-todo-sets
(nreverse org-todo-sets
)
5021 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5022 org-todo-key-trigger
(delq nil
(mapcar #'cdr org-todo-key-alist
))
5023 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
))
5024 ;; Compute the regular expressions and other local variables.
5025 ;; Using `org-outline-regexp-bol' would complicate them much,
5026 ;; because of the fixed white space at the end of that string.
5027 (unless org-done-keywords
5028 (setq org-done-keywords
5029 (and org-todo-keywords-1
(last org-todo-keywords-1
))))
5030 (setq org-not-done-keywords
5031 (org-delete-all org-done-keywords
5032 (copy-sequence org-todo-keywords-1
))
5033 org-todo-regexp
(regexp-opt org-todo-keywords-1 t
)
5034 org-not-done-regexp
(regexp-opt org-not-done-keywords t
)
5035 org-not-done-heading-regexp
5036 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5037 org-todo-line-regexp
5038 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5039 org-complex-heading-regexp
5040 (concat "^\\(\\*+\\)"
5041 "\\(?: +" org-todo-regexp
"\\)?"
5042 "\\(?: +\\(\\[#.\\]\\)\\)?"
5043 "\\(?: +\\(.*?\\)\\)??"
5044 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5046 org-complex-heading-regexp-format
5047 (concat "^\\(\\*+\\)"
5048 "\\(?: +" org-todo-regexp
"\\)?"
5049 "\\(?: +\\(\\[#.\\]\\)\\)?"
5051 ;; Stats cookies can be stuck to body.
5052 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5054 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5056 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5058 org-todo-line-tags-regexp
5059 (concat "^\\(\\*+\\)"
5060 "\\(?: +" org-todo-regexp
"\\)?"
5061 "\\(?: +\\(.*?\\)\\)??"
5062 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5064 (org-compute-latex-and-related-regexp)))))
5066 (defun org--setup-collect-keywords (regexp &optional files alist
)
5067 "Return setup keywords values as an alist.
5069 REGEXP matches a subset of setup keywords. FILES is a list of
5070 file names already visited. It is used to avoid circular setup
5071 files. ALIST, when non-nil, is the alist computed so far.
5073 Return value contains the following keys: `archive', `category',
5074 `columns', `constants', `filetags', `link', `priorities',
5075 `property', `scripts', `startup', `tags' and `todo'."
5076 (org-with-wide-buffer
5077 (goto-char (point-min))
5078 (let ((case-fold-search t
))
5079 (while (re-search-forward regexp nil t
)
5080 (let ((element (org-element-at-point)))
5081 (when (eq (org-element-type element
) 'keyword
)
5082 (let ((key (org-element-property :key element
))
5083 (value (org-element-property :value element
)))
5085 ((equal key
"ARCHIVE")
5086 (when (org-string-nw-p value
)
5087 (push (cons 'archive value
) alist
)))
5088 ((equal key
"CATEGORY") (push (cons 'category value
) alist
))
5089 ((equal key
"COLUMNS") (push (cons 'columns value
) alist
))
5090 ((equal key
"CONSTANTS")
5091 (let* ((constants (assq 'constants alist
))
5092 (store (cdr constants
)))
5093 (dolist (pair (split-string value
))
5094 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5096 (let* ((name (match-string 1 pair
))
5097 (value (match-string 2 pair
))
5098 (old (assoc name store
)))
5099 (if old
(setcdr old value
)
5100 (push (cons name value
) store
)))))
5101 (if constants
(setcdr constants store
)
5102 (push (cons 'constants store
) alist
))))
5103 ((equal key
"FILETAGS")
5104 (when (org-string-nw-p value
)
5105 (let ((old (assq 'filetags alist
))
5107 (mapcar (lambda (x) (org-split-string x
":"))
5108 (split-string value
)))))
5109 (if old
(setcdr old
(append new
(cdr old
)))
5110 (push (cons 'filetags new
) alist
)))))
5112 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5113 (let ((links (assq 'link alist
))
5114 (pair (cons (match-string-no-properties 1 value
)
5115 (match-string-no-properties 2 value
))))
5116 (if links
(push pair
(cdr links
))
5117 (push (list 'link pair
) alist
)))))
5118 ((equal key
"OPTIONS")
5119 (when (and (org-string-nw-p value
)
5120 (string-match "\\^:\\(t\\|nil\\|{}\\)" value
))
5121 (push (cons 'scripts
(read (match-string 1 value
))) alist
)))
5122 ((equal key
"PRIORITIES")
5123 (push (cons 'priorities
5124 (let ((prio (split-string value
)))
5125 (if (< (length prio
) 3) '(?A ?C ?B
)
5126 (mapcar #'string-to-char prio
))))
5128 ((equal key
"PROPERTY")
5129 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value
)
5130 (let* ((property (assq 'property alist
))
5131 (value (org--update-property-plist
5132 (match-string-no-properties 1 value
)
5133 (match-string-no-properties 2 value
)
5135 (if property
(setcdr property value
)
5136 (push (cons 'property value
) alist
)))))
5137 ((equal key
"STARTUP")
5138 (let ((startup (assq 'startup alist
)))
5141 (append (cdr startup
) (split-string value
)))
5142 (push (cons 'startup
(split-string value
)) alist
))))
5144 (let ((tag-cell (assq 'tags alist
)))
5146 (setcdr tag-cell
(concat (cdr tag-cell
) "\n" value
))
5147 (push (cons 'tags value
) alist
))))
5148 ((member key
'("TODO" "SEQ_TODO" "TYP_TODO"))
5149 (let ((todo (assq 'todo alist
))
5150 (value (cons (if (equal key
"TYP_TODO") 'type
'sequence
)
5151 (split-string value
))))
5152 (if todo
(push value
(cdr todo
))
5153 (push (list 'todo value
) alist
))))
5154 ((equal key
"SETUPFILE")
5155 (unless buffer-read-only
; Do not check in Gnus messages.
5156 (let ((f (and (org-string-nw-p value
)
5158 (org-unbracket-string "\"" "\"" value
)))))
5159 (when (and f
(file-readable-p f
) (not (member f files
)))
5161 (setq default-directory
(file-name-directory f
))
5162 (insert-file-contents f
)
5164 ;; Fake Org mode to benefit from cache
5165 ;; without recurring needlessly.
5166 (let ((major-mode 'org-mode
))
5167 (org--setup-collect-keywords
5168 regexp
(cons f files
) alist
)))))))))))))))
5171 (defun org-tag-string-to-alist (s)
5172 "Return tag alist associated to string S.
5173 S is a value for TAGS keyword or produced with
5174 `org-tag-alist-to-string'. Return value is an alist suitable for
5175 `org-tag-alist' or `org-tag-persistent-alist'."
5176 (let ((lines (mapcar #'split-string
(split-string s
"\n" t
)))
5177 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5178 "\\|{.+?}\\)" ; regular expression
5179 "\\(?:(\\(.\\))\\)?\\'"))
5181 (dolist (tokens lines
(cdr (nreverse alist
)))
5182 (push '(:newline
) alist
)
5184 (let ((token (pop tokens
)))
5187 (push '(:startgroup
) alist
)
5188 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5190 (push '(:endgroup
) alist
)
5191 (setq group-flag nil
))
5193 (push '(:startgrouptag
) alist
)
5194 (when (equal (nth 1 tokens
) ":") (setq group-flag t
)))
5196 (push '(:endgrouptag
) alist
)
5197 (setq group-flag nil
))
5199 (push '(:grouptags
) alist
))
5200 ((guard (string-match tag-re token
))
5201 (let ((tag (match-string 1 token
))
5202 (key (and (match-beginning 2)
5203 (string-to-char (match-string 2 token
)))))
5204 ;; Push all tags in groups, no matter if they already
5205 ;; appear somewhere else in the list.
5206 (when (or group-flag
(not (assoc tag alist
)))
5207 (push (cons tag key
) alist
))))))))))
5209 (defun org-tag-alist-to-string (alist &optional skip-key
)
5210 "Return tag string associated to ALIST.
5212 ALIST is an alist, as defined in `org-tag-alist' or
5213 `org-tag-persistent-alist', or produced with
5214 `org-tag-string-to-alist'.
5216 Return value is a string suitable as a value for \"TAGS\"
5219 When optional argument SKIP-KEY is non-nil, skip selection keys
5221 (mapconcat (lambda (token)
5223 (`(:startgroup
) "{")
5225 (`(:startgrouptag
) "[")
5226 (`(:endgrouptag
) "]")
5230 (guard (not skip-key
))
5231 `(,(and tag
(pred stringp
)) .
,(and key
(pred characterp
))))
5232 (format "%s(%c)" tag key
))
5233 (`(,(and tag
(pred stringp
)) .
,_
) tag
)
5234 (_ (user-error "Invalid tag token: %S" token
))))
5238 (defun org-tag-alist-to-groups (alist)
5239 "Return group alist from tag ALIST.
5240 ALIST is an alist, as defined in `org-tag-alist' or
5241 `org-tag-persistent-alist', or produced with
5242 `org-tag-string-to-alist'. Return value is an alist following
5243 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5244 a string, summarizing TAGS, as a list of strings."
5245 (let (groups group-status current-group
)
5246 (dolist (token alist
(nreverse groups
))
5248 (`(,(or :startgroup
:startgrouptag
)) (setq group-status t
))
5249 (`(,(or :endgroup
:endgrouptag
))
5250 (when (eq group-status
'append
)
5251 (push (nreverse current-group
) groups
))
5252 (setq group-status nil
))
5253 (`(:grouptags
) (setq group-status
'append
))
5254 ((and `(,tag .
,_
) (guard group-status
))
5255 (if (eq group-status
'append
) (push tag current-group
)
5256 (setq current-group
(list tag
))))
5259 (defvar org--file-cache
(make-hash-table :test
#'equal
)
5260 "Hash table to store contents of files referenced via a URL.
5261 This is the cache of file URLs read using `org-file-contents'.")
5263 (defun org-reset-file-cache ()
5264 "Reset the cache of files downloaded by `org-file-contents'."
5265 (clrhash org--file-cache
))
5267 (defun org-file-url-p (file)
5268 "Non-nil if FILE is a URL."
5270 (string-match-p ffap-url-regexp file
))
5272 (defun org-file-contents (file &optional noerror nocache
)
5273 "Return the contents of FILE, as a string.
5275 FILE can be a file name or URL.
5277 If FILE is a URL, download the contents. If the URL contents are
5278 already cached in the `org--file-cache' hash table, the download step
5281 If NOERROR is non-nil, ignore the error when unable to read the FILE
5284 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5285 is available. This option applies only if FILE is a URL."
5286 (let* ((is-url (org-file-url-p file
))
5289 (gethash file org--file-cache
))))
5293 (with-current-buffer (url-retrieve-synchronously file
)
5294 (goto-char (point-min))
5295 ;; Move point to after the url-retrieve header.
5296 (search-forward "\n\n" nil
:move
)
5297 ;; Search for the success code only in the url-retrieve header.
5299 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil
:noerror
))
5300 ;; Update the cache `org--file-cache' and return contents.
5302 (buffer-substring-no-properties (point) (point-max))
5304 (funcall (if noerror
#'message
#'user-error
)
5305 "Unable to fetch file from %S"
5311 (insert-file-contents file
)
5314 (funcall (if noerror
#'message
#'user-error
)
5315 "Unable to read file %S"
5318 (defun org-extract-log-state-settings (x)
5319 "Extract the log state setting from a TODO keyword string.
5320 This will extract info from a string like \"WAIT(w@/!)\"."
5321 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5322 (let ((kw (match-string 1 x
))
5323 (log1 (and (match-end 3) (match-string 3 x
)))
5324 (log2 (and (match-end 4) (match-string 4 x
))))
5327 (and log1
(if (equal log1
"!") 'time
'note
))
5328 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5330 (defun org-remove-keyword-keys (list)
5331 "Remove a pair of parenthesis at the end of each string in LIST."
5333 (if (string-match "(.*)$" x
)
5334 (substring x
0 (match-beginning 0))
5338 (defun org-assign-fast-keys (alist)
5339 "Assign fast keys to a keyword-key alist.
5340 Respect keys that are already there."
5341 (let (new e
(alt ?
0))
5342 (while (setq e
(pop alist
))
5343 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5344 (cdr e
)) ;; Key already assigned.
5346 (let ((clist (string-to-list (downcase (car e
))))
5347 (used (append new alist
)))
5348 (when (= (car clist
) ?
@)
5350 (while (and clist
(rassoc (car clist
) used
))
5353 (while (rassoc alt used
)
5355 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5358 ;;; Some variables used in various places
5360 (defvar org-window-configuration nil
5361 "Used in various places to store a window configuration.")
5362 (defvar org-selected-window nil
5363 "Used in various places to store a window configuration.")
5364 (defvar org-finish-function nil
5365 "Function to be called when `C-c C-c' is used.
5366 This is for getting out of special buffers like capture.")
5367 (defvar org-last-state
)
5369 ;; Defined somewhere in this file, but used before definition.
5370 (defvar org-entities
) ;; defined in org-entities.el
5371 (defvar org-struct-menu
)
5372 (defvar org-org-menu
)
5373 (defvar org-tbl-menu
)
5375 ;;;; Define the Org mode
5377 ;; We use a before-change function to check if a table might need
5379 (defvar org-table-may-need-update t
5380 "Indicates that a table might need an update.
5381 This variable is set by `org-before-change-function'.
5382 `org-table-align' sets it back to nil.")
5383 (defun org-before-change-function (_beg _end
)
5384 "Every change indicates that a table might need an update."
5385 (setq org-table-may-need-update t
))
5386 (defvar org-mode-map
)
5387 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5388 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5389 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5390 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5391 (defvar org-table-buffer-is-an nil
)
5393 (defvar bidi-paragraph-direction
)
5394 (defvar buffer-face-mode-face
)
5398 ;; Other stuff we need.
5399 (require 'time-date
)
5400 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5402 (autoload 'easy-menu-add
"easymenu")
5405 ;; (require 'org-macs) moved higher up in the file before it is first used
5406 (require 'org-entities
)
5407 ;; (require 'org-compat) moved higher up in the file before it is first used
5408 (require 'org-faces
)
5410 (require 'org-pcomplete
)
5412 (require 'org-footnote
)
5413 (require 'org-macro
)
5419 (define-derived-mode org-mode outline-mode
"Org"
5420 "Outline-based notes management and organizer, alias
5421 \"Carsten's outline-mode for keeping track of everything.\"
5423 Org mode develops organizational tasks around a NOTES file which
5424 contains information about projects as plain text. Org mode is
5425 implemented on top of Outline mode, which is ideal to keep the content
5426 of large files well structured. It supports ToDo items, deadlines and
5427 time stamps, which magically appear in the diary listing of the Emacs
5428 calendar. Tables are easily created with a built-in table editor.
5429 Plain text URL-like links connect to websites, emails (VM), Usenet
5430 messages (Gnus), BBDB entries, and any files related to the project.
5431 For printing and sharing of notes, an Org file (or a part of it)
5432 can be exported as a structured ASCII or HTML file.
5434 The following commands are available:
5438 ;; Get rid of Outline menus, they are not needed
5439 ;; Need to do this here because define-derived-mode sets up
5440 ;; the keymap so late. Still, it is a waste to call this each time
5441 ;; we switch another buffer into Org mode.
5442 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5443 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5444 (define-key org-mode-map
[menu-bar show
] 'undefined
)
5446 (org-load-modules-maybe)
5447 (org-install-agenda-files-menu)
5448 (when org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5449 (add-to-invisibility-spec '(org-cwidth))
5450 (add-to-invisibility-spec '(org-hide-block . t
))
5451 (setq-local outline-regexp org-outline-regexp
)
5452 (setq-local outline-level
'org-outline-level
)
5453 (setq bidi-paragraph-direction
'left-to-right
)
5454 (when (and (stringp org-ellipsis
) (not (equal "" org-ellipsis
)))
5455 (unless org-display-table
5456 (setq org-display-table
(make-display-table)))
5457 (set-display-table-slot
5459 (vconcat (mapcar (lambda (c) (make-glyph-code c
'org-ellipsis
))
5461 (setq buffer-display-table org-display-table
))
5462 (org-set-regexps-and-options)
5463 (org-set-font-lock-defaults)
5464 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5465 ;; tag faces set outside customize.... force initialization.
5466 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5468 (setq-local calc-embedded-open-mode
"# ")
5469 ;; Modify a few syntax entries
5470 (modify-syntax-entry ?
@ "w")
5471 (modify-syntax-entry ?
\" "\"")
5472 (modify-syntax-entry ?
\\ "_")
5473 (modify-syntax-entry ?~
"_")
5474 (setq-local font-lock-unfontify-region-function
'org-unfontify-region
)
5475 ;; Activate before-change-function
5476 (setq-local org-table-may-need-update t
)
5477 (add-hook 'before-change-functions
'org-before-change-function nil
'local
)
5478 ;; Check for running clock before killing a buffer
5479 (add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5480 ;; Initialize macros templates.
5481 (org-macro-initialize-templates)
5482 ;; Initialize radio targets.
5483 (org-update-radio-target-regexp)
5485 (setq-local indent-line-function
'org-indent-line
)
5486 (setq-local indent-region-function
'org-indent-region
)
5487 ;; Filling and auto-filling.
5490 (org-setup-comments-handling)
5491 ;; Initialize cache.
5492 (org-element-cache-reset)
5493 ;; Beginning/end of defun
5494 (setq-local beginning-of-defun-function
'org-backward-element
)
5495 (setq-local end-of-defun-function
5497 (if (not (org-at-heading-p))
5498 (org-forward-element)
5499 (org-forward-element)
5500 (forward-char -
1))))
5501 ;; Next error for sparse trees
5502 (setq-local next-error-function
'org-occur-next-match
)
5503 ;; Make sure dependence stuff works reliably, even for users who set it
5505 (if org-enforce-todo-dependencies
5506 (add-hook 'org-blocker-hook
5507 'org-block-todo-from-children-or-siblings-or-parent
)
5508 (remove-hook 'org-blocker-hook
5509 'org-block-todo-from-children-or-siblings-or-parent
))
5510 (if org-enforce-todo-checkbox-dependencies
5511 (add-hook 'org-blocker-hook
5512 'org-block-todo-from-checkboxes
)
5513 (remove-hook 'org-blocker-hook
5514 'org-block-todo-from-checkboxes
))
5516 ;; Align options lines
5518 align-mode-rules-list
5519 '((org-in-buffer-settings
5520 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5521 (modes .
'(org-mode)))))
5524 (setq-local imenu-create-index-function
'org-imenu-get-tree
)
5526 ;; Make isearch reveal context
5527 (setq-local outline-isearch-open-invisible-function
5528 (lambda (&rest _
) (org-show-context 'isearch
)))
5530 ;; Setup the pcomplete hooks
5531 (setq-local pcomplete-command-completion-function
'org-pcomplete-initial
)
5532 (setq-local pcomplete-command-name-function
'org-command-at-point
)
5533 (setq-local pcomplete-default-completion-function
'ignore
)
5534 (setq-local pcomplete-parse-arguments-function
'org-parse-arguments
)
5535 (setq-local pcomplete-termination-string
"")
5536 (setq-local buffer-face-mode-face
'org-default
)
5538 ;; If empty file that did not turn on Org mode automatically, make
5540 (when (and org-insert-mode-line-in-empty-file
5541 (called-interactively-p 'any
)
5542 (= (point-min) (point-max)))
5543 (insert "# -*- mode: org -*-\n\n"))
5544 (unless org-inhibit-startup
5546 (when org-startup-with-beamer-mode
(org-beamer-mode))
5547 (when org-startup-align-all-tables
5548 (org-table-map-tables #'org-table-align t
))
5549 (when org-startup-with-inline-images
(org-display-inline-images))
5550 (when org-startup-with-latex-preview
(org-toggle-latex-fragment '(16)))
5551 (unless org-inhibit-startup-visibility-stuff
(org-set-startup-visibility))
5552 (when org-startup-truncated
(setq truncate-lines t
))
5553 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5554 (org-refresh-effort-properties)))
5555 ;; Try to set `org-hide' face correctly.
5556 (let ((foreground (org-find-invisible-foreground)))
5558 (set-face-foreground 'org-hide foreground
))))
5560 ;; Update `customize-package-emacs-version-alist'
5561 (add-to-list 'customize-package-emacs-version-alist
5562 '(Org ("8.0" .
"24.4")
5570 (defvar org-mode-transpose-word-syntax-table
5571 (let ((st (make-syntax-table text-mode-syntax-table
)))
5572 (dolist (c org-emphasis-alist st
)
5573 (modify-syntax-entry (string-to-char (car c
)) "w p" st
))))
5575 (when (fboundp 'abbrev-table-put
)
5576 (abbrev-table-put org-mode-abbrev-table
5577 :parents
(list text-mode-abbrev-table
)))
5579 (defun org-find-invisible-foreground ()
5580 (let ((candidates (remove
5583 (list (face-background 'default
)
5584 (face-background 'org-default
))
5587 (when (boundp alist
)
5588 (cdr (assq 'background-color
(symbol-value alist
)))))
5589 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5590 (list (face-foreground 'org-hide
))))))
5591 (car (remove nil candidates
))))
5593 (defun org-current-time (&optional rounding-minutes past
)
5594 "Current time, possibly rounded to ROUNDING-MINUTES.
5595 When ROUNDING-MINUTES is not an integer, fall back on the car of
5596 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5597 the rounding returns a past time."
5598 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5599 (car org-time-stamp-rounding-minutes
)))
5600 (time (decode-time)) res
)
5605 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5607 (if (and past
(< (float-time (time-subtract (current-time) res
)) 0))
5608 (seconds-to-time (- (float-time res
) (* r
60)))
5612 "Return today date, considering `org-extend-today-until'."
5614 (time-subtract (current-time)
5615 (list 0 (* 3600 org-extend-today-until
) 0))))
5617 ;;;; Font-Lock stuff, including the activators
5619 (defvar org-mouse-map
(make-sparse-keymap))
5620 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5621 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5622 (when org-mouse-1-follows-link
5623 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5624 (when org-tab-follows-link
5625 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5626 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5628 (require 'font-lock
)
5630 (defconst org-non-link-chars
"]\t\n\r<>")
5631 (defvar org-link-types-re nil
5632 "Matches a link that has a url-like prefix like \"http:\"")
5633 (defvar org-link-re-with-space nil
5634 "Matches a link with spaces, optional angular brackets around it.")
5635 (defvar org-link-re-with-space2 nil
5636 "Matches a link with spaces, optional angular brackets around it.")
5637 (defvar org-link-re-with-space3 nil
5638 "Matches a link with spaces, only for internal part in bracket links.")
5639 (defvar org-angle-link-re nil
5640 "Matches link with angular brackets, spaces are allowed.")
5641 (defvar org-plain-link-re nil
5642 "Matches plain link, without spaces.")
5643 (defvar org-bracket-link-regexp nil
5644 "Matches a link in double brackets.")
5645 (defvar org-bracket-link-analytic-regexp nil
5646 "Regular expression used to analyze links.
5647 Here is what the match groups contain after a match:
5653 (defvar org-bracket-link-analytic-regexp
++ nil
5654 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5655 (defvar org-any-link-re nil
5656 "Regular expression matching any link.")
5658 (defconst org-match-sexp-depth
3
5659 "Number of stacked braces for sub/superscript matching.")
5661 (defun org-create-multibrace-regexp (left right n
)
5662 "Create a regular expression which will match a balanced sexp.
5663 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5664 as single character strings.
5665 The regexp returned will match the entire expression including the
5666 delimiters. It will also define a single group which contains the
5667 match except for the outermost delimiters. The maximum depth of
5668 stacked delimiters is N. Escaping delimiters is not possible."
5669 (let* ((nothing (concat "[^" left right
"]*?"))
5672 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5675 re
(concat re or next
)
5676 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5677 (concat left
"\\(" re
"\\)" right
)))
5679 (defconst org-match-substring-regexp
5681 "\\(\\S-\\)\\([_^]\\)\\("
5682 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5684 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5686 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5687 "The regular expression matching a sub- or superscript.")
5689 (defconst org-match-substring-with-braces-regexp
5691 "\\(\\S-\\)\\([_^]\\)"
5692 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5693 "The regular expression matching a sub- or superscript, forcing braces.")
5695 (defun org-make-link-regexps ()
5696 "Update the link regular expressions.
5697 This should be called after the variable `org-link-parameters' has changed."
5698 (let ((types-re (regexp-opt (org-link-types) t
)))
5699 (setq org-link-types-re
5700 (concat "\\`" types-re
":")
5701 org-link-re-with-space
5702 (concat "<?" types-re
":"
5703 "\\([^" org-non-link-chars
" ]"
5704 "[^" org-non-link-chars
"]*"
5705 "[^" org-non-link-chars
" ]\\)>?")
5706 org-link-re-with-space2
5707 (concat "<?" types-re
":"
5708 "\\([^" org-non-link-chars
" ]"
5710 "[^" org-non-link-chars
" ]\\)>?")
5711 org-link-re-with-space3
5712 (concat "<?" types-re
":"
5713 "\\([^" org-non-link-chars
" ]"
5716 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5721 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5722 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5723 org-bracket-link-regexp
5724 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5725 org-bracket-link-analytic-regexp
5728 "\\(" types-re
":\\)?"
5731 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 org-bracket-link-analytic-regexp
++
5736 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t
) ":\\)?"
5739 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5742 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5743 org-angle-link-re
"\\)\\|\\("
5744 org-plain-link-re
"\\)"))))
5746 (org-make-link-regexps)
5748 (defvar org-emph-face nil
)
5750 (defun org-do-emphasis-faces (limit)
5751 "Run through the buffer and emphasize strings."
5752 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5753 (car org-emphasis-regexp-components
))))
5755 (while (re-search-forward quick-re limit t
)
5756 (let* ((marker (match-string 2))
5757 (verbatim?
(member marker
'("~" "="))))
5758 (when (save-excursion
5759 (goto-char (match-beginning 0))
5761 ;; Do not match table hlines.
5762 (not (and (equal marker
"+")
5764 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5765 ;; Do not match headline stars. Do not consider
5766 ;; stars of a headline as closing marker for bold
5768 (not (and (equal marker
"*")
5771 (skip-chars-backward "*")
5772 (looking-at-p org-outline-regexp-bol
))))
5773 ;; Match full emphasis markup regexp.
5774 (looking-at (if verbatim? org-verbatim-re org-emph-re
))
5775 ;; Do not span over paragraph boundaries.
5776 (not (string-match-p org-element-paragraph-separate
5778 ;; Do not span over cells in table rows.
5779 (not (and (save-match-data (org-match-line "[ \t]*|"))
5780 (string-match-p "|" (match-string 4))))))
5781 (pcase-let ((`(,_
,face
,_
) (assoc marker org-emphasis-alist
)))
5782 (font-lock-prepend-text-property
5783 (match-beginning 2) (match-end 2) 'face face
)
5785 (org-remove-flyspell-overlays-in
5786 (match-beginning 0) (match-end 0)))
5787 (add-text-properties (match-beginning 2) (match-end 2)
5788 '(font-lock-multiline t org-emphasis t
))
5789 (when org-hide-emphasis-markers
5790 (add-text-properties (match-end 4) (match-beginning 5)
5791 '(invisible org-link
))
5792 (add-text-properties (match-beginning 3) (match-end 3)
5793 '(invisible org-link
)))
5794 (throw :exit t
))))))))
5796 (defun org-emphasize (&optional char
)
5797 "Insert or change an emphasis, i.e. a font like bold or italic.
5798 If there is an active region, change that region to a new emphasis.
5799 If there is no region, just insert the marker characters and position
5800 the cursor between them.
5801 CHAR should be the marker character. If it is a space, it means to
5802 remove the emphasis of the selected region.
5803 If CHAR is not given (for example in an interactive call) it will be
5806 (let ((erc org-emphasis-regexp-components
)
5807 (string "") beg end move s
)
5808 (if (org-region-active-p)
5809 (setq beg
(region-beginning)
5811 string
(buffer-substring beg end
))
5815 (message "Emphasis marker or tag: [%s]"
5816 (mapconcat #'car org-emphasis-alist
""))
5817 (setq char
(read-char-exclusive)))
5818 (if (equal char ?\s
)
5821 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5822 (user-error "No such emphasis marker: \"%c\"" char
))
5823 (setq s
(char-to-string char
)))
5824 (while (and (> (length string
) 1)
5825 (equal (substring string
0 1) (substring string -
1))
5826 (assoc (substring string
0 1) org-emphasis-alist
))
5827 (setq string
(substring string
1 -
1)))
5828 (setq string
(concat s string s
))
5829 (when beg
(delete-region beg end
))
5831 (string-match (concat "[" (nth 0 erc
) "\n]")
5832 (char-to-string (char-before (point)))))
5835 (string-match (concat "[" (nth 1 erc
) "\n]")
5836 (char-to-string (char-after (point)))))
5837 (insert " ") (backward-char 1))
5839 (and move
(backward-char 1))))
5841 (defconst org-nonsticky-props
5842 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5844 (defsubst org-rear-nonsticky-at
(pos)
5845 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5847 (defun org-activate-links (limit)
5848 "Add link properties to links.
5849 This includes angle, plain, and bracket links."
5851 (while (re-search-forward org-any-link-re limit t
)
5852 (let* ((start (match-beginning 0))
5854 (style (cond ((eq ?
< (char-after start
)) 'angle
)
5855 ((eq ?\
[ (char-after (1+ start
))) 'bracket
)
5857 (when (and (memq style org-highlight-links
)
5858 ;; Do not confuse plain links with tags.
5859 (not (and (eq style
'plain
)
5860 (let ((face (get-text-property
5861 (max (1- start
) (point-min)) 'face
)))
5862 (if (consp face
) (memq 'org-tag face
)
5863 (eq 'org-tag face
))))))
5864 (let* ((link-object (save-excursion
5866 (save-match-data (org-element-link-parser))))
5867 (link (org-element-property :raw-link link-object
))
5868 (type (org-element-property :type link-object
))
5869 (path (org-element-property :path link-object
))
5870 (properties ;for link's visible part
5872 'face
(pcase (org-link-get-parameter type
:face
)
5873 ((and (pred functionp
) face
) (funcall face path
))
5874 ((and (pred facep
) face
) face
)
5875 ((and (pred consp
) face
) face
) ;anonymous
5877 'mouse-face
(or (org-link-get-parameter type
:mouse-face
)
5879 'keymap
(or (org-link-get-parameter type
:keymap
)
5881 'help-echo
(pcase (org-link-get-parameter type
:help-echo
)
5882 ((and (pred stringp
) echo
) echo
)
5883 ((and (pred functionp
) echo
) echo
)
5884 (_ (concat "LINK: " link
)))
5885 'htmlize-link
(pcase (org-link-get-parameter type
5887 ((and (pred functionp
) f
) (funcall f
))
5889 'font-lock-multiline t
)))
5890 (org-remove-flyspell-overlays-in start end
)
5891 (org-rear-nonsticky-at end
)
5892 (if (not (eq 'bracket style
))
5893 (add-text-properties start end properties
)
5894 ;; Handle invisible parts in bracket links.
5895 (remove-text-properties start end
'(invisible nil
))
5898 ,(or (org-link-get-parameter type
:display
)
5901 (visible-start (or (match-beginning 4) (match-beginning 2)))
5902 (visible-end (or (match-end 4) (match-end 2))))
5903 (add-text-properties start visible-start hidden
)
5904 (add-text-properties visible-start visible-end properties
)
5905 (add-text-properties visible-end end hidden
)
5906 (org-rear-nonsticky-at visible-start
)
5907 (org-rear-nonsticky-at visible-end
)))
5908 (let ((f (org-link-get-parameter type
:activate-func
)))
5910 (funcall f start end path
(eq style
'bracket
))))
5911 (throw :exit t
))))) ;signal success
5914 (defun org-activate-code (limit)
5915 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5916 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5917 (remove-text-properties (match-beginning 0) (match-end 0)
5918 '(display t invisible t intangible t
))
5921 (defcustom org-src-fontify-natively t
5922 "When non-nil, fontify code in code blocks.
5923 See also the `org-block' face."
5926 :package-version
'(Org .
"8.3")
5927 :group
'org-appearance
5930 (defcustom org-allow-promoting-top-level-subtree nil
5931 "When non-nil, allow promoting a top level subtree.
5932 The leading star of the top level headline will be replaced
5936 :group
'org-appearance
)
5938 (defun org-fontify-meta-lines-and-blocks (limit)
5940 (org-fontify-meta-lines-and-blocks-1 limit
)
5941 (error (message "Org mode fontification error in %S at %d"
5943 (line-number-at-pos)))))
5945 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5946 "Fontify #+ lines and blocks."
5947 (let ((case-fold-search t
))
5948 (when (re-search-forward
5949 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5951 (let ((beg (match-beginning 0))
5952 (block-start (match-end 0))
5954 (lang (match-string 7))
5955 (beg1 (line-beginning-position 2))
5956 (dc1 (downcase (match-string 2)))
5957 (dc3 (downcase (match-string 3)))
5958 end end1 quoting block-type
)
5960 ((and (match-end 4) (equal dc3
"+begin"))
5962 (setq block-type
(downcase (match-string 5))
5963 quoting
(member block-type org-protecting-blocks
))
5964 (when (re-search-forward
5965 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5966 nil t
) ;; on purpose, we look further than LIMIT
5967 (setq end
(min (point-max) (match-end 0))
5968 end1
(min (point-max) (1- (match-beginning 0))))
5969 (setq block-end
(match-beginning 0))
5971 (org-remove-flyspell-overlays-in beg1 end1
)
5972 (remove-text-properties beg end
5973 '(display t invisible t intangible t
)))
5974 (add-text-properties
5975 beg end
'(font-lock-fontified t font-lock-multiline t
))
5976 (add-text-properties beg beg1
'(face org-meta-line
))
5977 (org-remove-flyspell-overlays-in beg beg1
)
5978 (add-text-properties ; For end_src
5979 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
5980 (org-remove-flyspell-overlays-in end1 end
)
5982 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5983 (org-src-font-lock-fontify-block lang block-start block-end
)
5984 (add-text-properties beg1 block-end
'(src-block t
)))
5986 (add-text-properties beg1
(min (point-max) (1+ end1
))
5990 (intern (format "org-block-%s" lang
))))
5991 (append (and (facep face-name
) (list face-name
))
5992 '(org-block))))))) ; end of source block
5993 ((not org-fontify-quote-and-verse-blocks
))
5994 ((string= block-type
"quote")
5995 (add-face-text-property
5996 beg1
(min (point-max) (1+ end1
)) 'org-quote t
))
5997 ((string= block-type
"verse")
5998 (add-face-text-property
5999 beg1
(min (point-max) (1+ end1
)) 'org-verse t
)))
6000 (add-text-properties beg beg1
'(face org-block-begin-line
))
6001 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
6002 '(face org-block-end-line
))
6004 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
6005 (org-remove-flyspell-overlays-in
6007 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
6008 (add-text-properties
6010 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
6011 '(font-lock-fontified t invisible t
)
6012 '(font-lock-fontified t face org-document-info-keyword
)))
6013 (add-text-properties
6014 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6015 (if (string-equal dc1
"+title:")
6016 '(font-lock-fontified t face org-document-title
)
6017 '(font-lock-fontified t face org-document-info
))))
6018 ((string-prefix-p "+caption" dc1
)
6019 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6020 (remove-text-properties (match-beginning 0) (match-end 0)
6021 '(display t invisible t intangible t
))
6022 ;; Handle short captions.
6025 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6026 (add-text-properties (line-beginning-position) (match-end 1)
6027 '(font-lock-fontified t face org-meta-line
))
6028 (add-text-properties (match-end 0) (line-end-position)
6029 '(font-lock-fontified t face org-block
))
6031 ((member dc3
'(" " ""))
6032 (org-remove-flyspell-overlays-in beg
(match-end 0))
6033 (add-text-properties
6035 '(font-lock-fontified t face font-lock-comment-face
)))
6036 (t ;; just any other in-buffer setting, but not indented
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6038 (remove-text-properties (match-beginning 0) (match-end 0)
6039 '(display t invisible t intangible t
))
6040 (add-text-properties beg
(match-end 0)
6041 '(font-lock-fontified t face org-meta-line
))
6044 (defun org-fontify-drawers (limit)
6046 (when (re-search-forward org-drawer-regexp limit t
)
6047 (add-text-properties
6048 (match-beginning 0) (match-end 0)
6049 '(font-lock-fontified t face org-special-keyword
))
6050 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6053 (defun org-fontify-macros (limit)
6055 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
6056 (add-text-properties
6057 (match-beginning 0) (match-end 0)
6058 '(font-lock-fontified t face org-macro
))
6059 (when org-hide-macro-markers
6060 (add-text-properties (match-end 2) (match-beginning 2)
6062 (add-text-properties (match-beginning 1) (match-end 1)
6064 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6067 (defun org-activate-footnote-links (limit)
6068 "Add text properties for footnotes."
6069 (let ((fn (org-footnote-next-reference-or-definition limit
)))
6071 (let* ((beg (nth 1 fn
))
6074 (referencep (/= (line-beginning-position) beg
)))
6075 (when (and referencep
(nth 3 fn
))
6078 (search-forward (or label
"fn:"))
6079 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6080 (add-text-properties beg end
6081 (list 'mouse-face
'highlight
6082 'keymap org-mouse-map
6084 (if referencep
"Footnote reference"
6085 "Footnote definition")
6086 'font-lock-fontified t
6087 'font-lock-multiline t
6088 'face
'org-footnote
))))))
6090 (defun org-activate-dates (limit)
6091 "Add text properties for dates."
6092 (when (and (re-search-forward org-tsr-regexp-both limit t
)
6093 (not (equal (char-before (match-beginning 0)) 91)))
6094 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6095 (add-text-properties (match-beginning 0) (match-end 0)
6096 (list 'mouse-face
'highlight
6097 'keymap org-mouse-map
))
6098 (org-rear-nonsticky-at (match-end 0))
6099 (when org-display-custom-times
6100 ;; If it's a date range, activate custom time for second date.
6102 (org-display-custom-time (match-beginning 3) (match-end 3)))
6103 (org-display-custom-time (match-beginning 1) (match-end 1)))
6106 (defvar-local org-target-link-regexp nil
6107 "Regular expression matching radio targets in plain text.")
6109 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6110 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6111 border border border
))
6112 "Regular expression matching a link target.")
6114 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6115 "Regular expression matching a radio target.")
6117 (defconst org-any-target-regexp
6118 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6119 "Regular expression matching any target.")
6121 (defun org-activate-target-links (limit)
6122 "Add text properties for target matches."
6123 (when org-target-link-regexp
6124 (let ((case-fold-search t
))
6125 (when (re-search-forward org-target-link-regexp limit t
)
6126 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6127 (add-text-properties (match-beginning 1) (match-end 1)
6128 (list 'mouse-face
'highlight
6129 'keymap org-mouse-map
6130 'help-echo
"Radio target link"
6131 'org-linked-text t
))
6132 (org-rear-nonsticky-at (match-end 1))
6135 (defun org-update-radio-target-regexp ()
6136 "Find all radio targets in this file and update the regular expression.
6137 Also refresh fontification if needed."
6139 (let ((old-regexp org-target-link-regexp
)
6140 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6141 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6143 (org-with-wide-buffer
6144 (goto-char (point-min))
6146 (while (re-search-forward org-radio-target-regexp nil t
)
6147 ;; Make sure point is really within the object.
6149 (let ((obj (org-element-context)))
6150 (when (eq (org-element-type obj
) 'radio-target
)
6151 (cl-pushnew (org-element-property :value obj
) rtn
6154 (setq org-target-link-regexp
6159 (replace-regexp-in-string
6160 " +" "\\s-+" (regexp-quote x
) t t
))
6164 (unless (equal old-regexp org-target-link-regexp
)
6166 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6167 ((not org-target-link-regexp
) old-regexp
)
6172 (substring re
(length before-re
)
6173 (- (length after-re
))))
6174 (list old-regexp org-target-link-regexp
)
6177 (org-with-wide-buffer
6178 (goto-char (point-min))
6179 (while (re-search-forward regexp nil t
)
6180 (org-element-cache-refresh (match-beginning 1)))))
6181 ;; Re fontify buffer.
6182 (when (memq 'radio org-highlight-links
)
6183 (org-restart-font-lock)))))
6185 (defun org-hide-wide-columns (limit)
6187 (setq s
(text-property-any (point) (or limit
(point-max))
6190 (setq e
(next-single-property-change s
'org-cwidth
))
6191 (add-text-properties s e
'(invisible org-cwidth
))
6195 (defvar org-latex-and-related-regexp nil
6196 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6198 (defun org-compute-latex-and-related-regexp ()
6199 "Compute regular expression for LaTeX, entities and sub/superscript.
6200 Result depends on variable `org-highlight-latex-and-related'."
6202 org-latex-and-related-regexp
6204 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6205 ((eq org-use-sub-superscripts
'{})
6206 (list org-match-substring-with-braces-regexp
))
6207 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6209 (when (memq 'latex org-highlight-latex-and-related
)
6210 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6213 (and (member (car x
) matchers
) (nth 1 x
)))
6214 org-latex-regexps
)))))
6216 (when (memq 'entities org-highlight-latex-and-related
)
6217 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6218 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6220 (defun org-do-latex-and-related (limit)
6221 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6222 LIMIT bounds the search for syntax to highlight. Stop at first
6223 highlighted object, if any. Return t if some highlighting was
6224 done, nil otherwise."
6225 (when (org-string-nw-p org-latex-and-related-regexp
)
6227 (while (re-search-forward org-latex-and-related-regexp limit t
)
6231 (memq f
'(org-code org-verbatim underline org-special-keyword
)))
6233 (goto-char (1+ (match-beginning 0)))
6234 (face-at-point nil t
)))
6235 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6239 (font-lock-prepend-text-property
6240 (+ offset
(match-beginning 0)) (match-end 0)
6241 'face
'org-latex-and-related
)
6242 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6243 '(font-lock-multiline t
)))
6247 (defun org-restart-font-lock ()
6248 "Restart `font-lock-mode', to force refontification."
6249 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6251 (font-lock-mode 1)))
6253 (defun org-activate-tags (limit)
6254 (when (re-search-forward
6255 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t
)
6256 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6257 (add-text-properties (match-beginning 1) (match-end 1)
6258 (list 'mouse-face
'highlight
6259 'keymap org-mouse-map
))
6260 (org-rear-nonsticky-at (match-end 1))
6263 (defun org-outline-level ()
6264 "Compute the outline level of the heading at point.
6266 If this is called at a normal headline, the level is the number
6267 of stars. Use `org-reduced-level' to remove the effect of
6268 `org-odd-levels'. Unlike to `org-current-level', this function
6269 takes into consideration inlinetasks."
6270 (org-with-wide-buffer
6272 (if (re-search-backward org-outline-regexp-bol nil t
)
6273 (1- (- (match-end 0) (match-beginning 0)))
6276 (defvar org-font-lock-keywords nil
)
6278 (defsubst org-re-property
(property &optional literal allow-null value
)
6279 "Return a regexp matching a PROPERTY line.
6281 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6282 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6283 non-nil, match properties even without a value.
6285 Match group 3 is set to the value when it exists. If there is no
6286 value and ALLOW-NULL is non-nil, it is set to the empty string.
6288 With optional argument VALUE, match only property lines with
6289 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6290 unless LITERAL is non-nil."
6293 (format "\\(?1::\\(?2:%s\\):\\)"
6294 (if literal property
(regexp-quote property
)))
6296 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6297 (if literal value
(regexp-quote value
))))
6299 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6301 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6303 (defconst org-property-re
6304 (org-re-property "\\S-+" 'literal t
)
6305 "Regular expression matching a property line.
6306 There are four matching groups:
6307 1: :PROPKEY: including the leading and trailing colon,
6308 2: PROPKEY without the leading and trailing colon,
6309 3: PROPVAL without leading or trailing spaces,
6310 4: the indentation of the current line,
6311 5: trailing whitespace.")
6313 (defvar org-font-lock-hook nil
6314 "Functions to be called for special font lock stuff.")
6316 (defvar org-font-lock-extra-keywords nil
) ;Dynamically scoped.
6318 (defvar org-font-lock-set-keywords-hook nil
6319 "Functions that can manipulate `org-font-lock-extra-keywords'.
6320 This is called after `org-font-lock-extra-keywords' is defined, but before
6321 it is installed to be used by font lock. This can be useful if something
6322 needs to be inserted at a specific position in the font-lock sequence.")
6324 (defun org-font-lock-hook (limit)
6325 "Run `org-font-lock-hook' within LIMIT."
6326 (run-hook-with-args 'org-font-lock-hook limit
))
6328 (defun org-set-font-lock-defaults ()
6329 "Set font lock defaults for the current buffer."
6330 (let* ((em org-fontify-emphasized-text
)
6331 (lk org-highlight-links
)
6332 (org-font-lock-extra-keywords
6335 '(org-font-lock-hook)
6337 `(,(if org-fontify-whole-heading-line
6338 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6339 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6340 (1 (org-get-level-face 1))
6341 (2 (org-get-level-face 2))
6342 (3 (org-get-level-face 3)))
6344 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6347 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6348 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6349 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6350 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6352 '(org-fontify-drawers)
6354 (list org-property-re
6355 '(1 'org-special-keyword t
)
6356 '(3 'org-property-value t
))
6357 ;; Link related fontification.
6358 '(org-activate-links)
6359 (when (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6360 (when (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6361 (when (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6362 (when (memq 'footnote lk
) '(org-activate-footnote-links))
6364 (list org-any-target-regexp
'(0 'org-target t
))
6366 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6368 '(org-fontify-macros)
6369 '(org-hide-wide-columns (0 nil append
))
6371 (list (format org-heading-keyword-regexp-format
6373 '(2 (org-get-todo-face 2) t
))
6375 (if org-fontify-done-headline
6376 (list (format org-heading-keyword-regexp-format
6379 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6381 '(2 'org-headline-done t
))
6384 '(org-font-lock-add-priority-faces)
6386 '(org-font-lock-add-tag-faces)
6388 (when (and org-group-tags org-tag-groups-alist
)
6389 (list (concat org-outline-regexp-bol
".+\\(:"
6390 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6392 '(1 'org-tag-group prepend
)))
6394 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6395 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6396 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6397 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6399 (when em
'(org-do-emphasis-faces))
6401 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6402 1 'org-checkbox prepend
)
6403 (when (cdr (assq 'checkbox org-list-automatic-rules
))
6404 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6405 (0 (org-get-checkbox-statistics-face) t
)))
6406 ;; Description list items
6407 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6408 1 'org-list-dt prepend
)
6409 ;; ARCHIVEd headings
6411 org-outline-regexp-bol
6412 "\\(.*:" org-archive-tag
":.*\\)")
6413 '(1 'org-archived prepend
))
6415 '(org-do-latex-and-related)
6416 '(org-fontify-entities)
6417 '(org-raise-scripts)
6419 '(org-activate-code (1 'org-code t
))
6422 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6425 '(9 'org-special-keyword t
))
6426 ;; Blocks and meta lines
6427 '(org-fontify-meta-lines-and-blocks))))
6428 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6429 (run-hooks 'org-font-lock-set-keywords-hook
)
6430 ;; Now set the full font-lock-keywords
6431 (setq-local org-font-lock-keywords org-font-lock-extra-keywords
)
6432 (setq-local font-lock-defaults
6433 '(org-font-lock-keywords t nil nil backward-paragraph
))
6434 (kill-local-variable 'font-lock-keywords
)
6437 (defun org-toggle-pretty-entities ()
6438 "Toggle the composition display of entities as UTF8 characters."
6440 (setq-local org-pretty-entities
(not org-pretty-entities
))
6441 (org-restart-font-lock)
6442 (if org-pretty-entities
6443 (message "Entities are now displayed as UTF8 characters")
6446 (decompose-region (point-min) (point-max))
6447 (message "Entities are now displayed as plain text"))))
6449 (defvar-local org-custom-properties-overlays nil
6450 "List of overlays used for custom properties.")
6452 (defun org-toggle-custom-properties-visibility ()
6453 "Display or hide properties in `org-custom-properties'."
6455 (if org-custom-properties-overlays
6456 (progn (mapc #'delete-overlay org-custom-properties-overlays
)
6457 (setq org-custom-properties-overlays nil
))
6458 (when org-custom-properties
6459 (org-with-wide-buffer
6460 (goto-char (point-min))
6461 (let ((regexp (org-re-property (regexp-opt org-custom-properties
) t t
)))
6462 (while (re-search-forward regexp nil t
)
6463 (let ((end (cdr (save-match-data (org-get-property-block)))))
6464 (when (and end
(< (point) end
))
6465 ;; Hide first custom property in current drawer.
6466 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6467 (overlay-put o
'invisible t
)
6468 (overlay-put o
'org-custom-property t
)
6469 (push o org-custom-properties-overlays
))
6470 ;; Hide additional custom properties in the same drawer.
6471 (while (re-search-forward regexp end t
)
6472 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6473 (overlay-put o
'invisible t
)
6474 (overlay-put o
'org-custom-property t
)
6475 (push o org-custom-properties-overlays
)))))
6476 ;; Each entry is limited to a single property drawer.
6477 (outline-next-heading)))))))
6479 (defun org-fontify-entities (limit)
6480 "Find an entity to fontify."
6482 (when org-pretty-entities
6484 ;; "\_ "-family is left out on purpose. Only the first one,
6485 ;; i.e., "\_ ", could be fontified anyway, and it would be
6486 ;; confusing when adding a second white space character.
6487 (while (re-search-forward
6488 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6490 (when (and (not (org-at-comment-p))
6491 (setq ee
(org-entity-get (match-string 1)))
6492 (= (length (nth 6 ee
)) 1))
6493 (let* ((end (if (equal (match-string 2) "{}")
6496 (add-text-properties
6497 (match-beginning 0) end
6498 (list 'font-lock-fontified t
))
6499 (compose-region (match-beginning 0) end
6505 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6506 "Fontify string S like in Org mode."
6509 (let ((org-odd-levels-only odd-levels
))
6511 (org-font-lock-ensure)
6517 (defun org-get-level-face (n)
6518 "Get the right face for match N in font-lock matching of headlines."
6519 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6520 (when org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6521 (if org-cycle-level-faces
6522 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6523 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6525 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6527 (t (unless org-level-color-stars-only org-f
))))
6529 (defun org-face-from-face-or-color (context inherit face-or-color
)
6530 "Create a face list that inherits INHERIT, but sets the foreground color.
6531 When FACE-OR-COLOR is not a string, just return it."
6532 (if (stringp face-or-color
)
6533 (list :inherit inherit
6534 (cdr (assoc context org-faces-easy-properties
))
6538 (defun org-get-todo-face (kwd)
6539 "Get the right face for a TODO keyword KWD.
6540 If KWD is a number, get the corresponding match group."
6541 (when (numberp kwd
) (setq kwd
(match-string kwd
)))
6542 (or (org-face-from-face-or-color
6543 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6544 (and (member kwd org-done-keywords
) 'org-done
)
6547 (defun org-get-priority-face (priority)
6548 "Get the right face for PRIORITY.
6549 PRIORITY is a character."
6550 (or (org-face-from-face-or-color
6551 'priority
'org-priority
(cdr (assq priority org-priority-faces
)))
6554 (defun org-get-tag-face (tag)
6555 "Get the right face for TAG.
6556 If TAG is a number, get the corresponding match group."
6557 (let ((tag (if (wholenump tag
) (match-string tag
) tag
)))
6558 (or (org-face-from-face-or-color
6559 'tag
'org-tag
(cdr (assoc tag org-tag-faces
)))
6562 (defun org-font-lock-add-priority-faces (limit)
6563 "Add the special priority faces."
6564 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t
)
6565 (add-text-properties
6566 (match-beginning 1) (match-end 1)
6567 (list 'face
(org-get-priority-face (string-to-char (match-string 2)))
6568 'font-lock-fontified t
))))
6570 (defun org-font-lock-add-tag-faces (limit)
6571 "Add the special tag faces."
6572 (when (and org-tag-faces org-tags-special-faces-re
)
6573 (while (re-search-forward org-tags-special-faces-re limit t
)
6574 (add-text-properties (match-beginning 1) (match-end 1)
6575 (list 'face
(org-get-tag-face 1)
6576 'font-lock-fontified t
))
6577 (backward-char 1))))
6579 (defun org-unfontify-region (beg end
&optional _maybe_loudly
)
6580 "Remove fontification and activation overlays from links."
6581 (font-lock-default-unfontify-region beg end
)
6582 (let* ((buffer-undo-list t
)
6583 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6584 (inhibit-modification-hooks t
)
6585 deactivate-mark buffer-file-name buffer-file-truename
)
6586 (decompose-region beg end
)
6587 (remove-text-properties beg end
6588 '(mouse-face t keymap t org-linked-text t
6589 invisible t intangible t
6591 (org-remove-font-lock-display-properties beg end
)))
6593 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6594 ((raise 0.3) (height 0.7))
6597 "Display properties for showing superscripts and subscripts.")
6599 (defun org-remove-font-lock-display-properties (beg end
)
6600 "Remove specific display properties that have been added by font lock.
6601 The will remove the raise properties that are used to show superscripts
6605 (setq next
(next-single-property-change beg
'display nil end
)
6606 prop
(get-text-property beg
'display
))
6607 (when (member prop org-script-display
)
6608 (put-text-property beg next
'display nil
))
6611 (defun org-raise-scripts (limit)
6612 "Add raise properties to sub/superscripts."
6613 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6615 (if (eq org-use-sub-superscripts t
)
6616 org-match-substring-regexp
6617 org-match-substring-with-braces-regexp
)
6619 (let* ((pos (point)) table-p comment-p
6620 (mpos (match-beginning 3))
6621 (emph-p (get-text-property mpos
'org-emphasis
))
6622 (link-p (get-text-property mpos
'mouse-face
))
6623 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6624 (goto-char (point-at-bol))
6625 (setq table-p
(looking-at-p org-table-dataline-regexp
)
6626 comment-p
(looking-at-p "^[ \t]*#[ +]"))
6629 (when (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6630 (unless (or comment-p emph-p link-p keyw-p
)
6631 (put-text-property (match-beginning 3) (match-end 0)
6633 (if (equal (char-after (match-beginning 2)) ?^
)
6634 (nth (if table-p
3 1) org-script-display
)
6635 (nth (if table-p
2 0) org-script-display
)))
6636 (add-text-properties (match-beginning 2) (match-end 2)
6637 (list 'invisible t
))
6638 (when (and (eq (char-after (match-beginning 3)) ?
{)
6639 (eq (char-before (match-end 3)) ?
}))
6640 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6641 (list 'invisible t
))
6642 (add-text-properties (1- (match-end 3)) (match-end 3)
6643 (list 'invisible t
))))
6646 ;;;; Visibility cycling, including org-goto and indirect buffer
6650 (defvar-local org-cycle-global-status nil
)
6651 (put 'org-cycle-global-status
'org-state t
)
6652 (defvar-local org-cycle-subtree-status nil
)
6653 (put 'org-cycle-subtree-status
'org-state t
)
6655 (defvar org-inlinetask-min-level
)
6657 (defun org-unlogged-message (&rest args
)
6658 "Display a message, but avoid logging it in the *Messages* buffer."
6659 (let ((message-log-max nil
))
6660 (apply 'message args
)))
6663 (defun org-cycle (&optional arg
)
6664 "TAB-action and visibility cycling for Org mode.
6666 This is the command invoked in Org mode by the `TAB' key. Its main
6667 purpose is outline visibility cycling, but it also invokes other actions
6668 in special contexts.
6670 When this function is called with a `\\[universal-argument]' prefix, rotate \
6672 buffer through 3 states (global cycling)
6673 1. OVERVIEW: Show only top-level headlines.
6674 2. CONTENTS: Show all headlines of all levels, but no body text.
6675 3. SHOW ALL: Show everything.
6677 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6678 switch to the startup visibility,
6679 determined by the variable `org-startup-folded', and by any VISIBILITY
6680 properties in the buffer.
6682 With a `\\[universal-argument] \\[universal-argument] \
6683 \\[universal-argument]' prefix argument, show the entire buffer, including
6686 When inside a table, re-align the table and move to the next field.
6688 When point is at the beginning of a headline, rotate the subtree started
6689 by this line through 3 different states (local cycling)
6690 1. FOLDED: Only the main headline is shown.
6691 2. CHILDREN: The main headline and the direct children are shown.
6692 From this state, you can move to one of the children
6693 and zoom in further.
6694 3. SUBTREE: Show the entire subtree, including body text.
6695 If there is no subtree, switch directly from CHILDREN to FOLDED.
6697 When point is at the beginning of an empty headline and the variable
6698 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6699 of the headline by demoting and promoting it to likely levels. This
6700 speeds up creation document structure by pressing `TAB' once or several
6701 times right after creating a new headline.
6703 When there is a numeric prefix, go up to a heading with level ARG, do
6704 a `show-subtree' and return to the previous cursor position. If ARG
6705 is negative, go up that many levels.
6707 When point is not at the beginning of a headline, execute the global
6708 binding for `TAB', which is re-indenting the line. See the option
6709 `org-cycle-emulate-tab' for details.
6711 As a special case, if point is at the beginning of the buffer and there is
6712 no headline in line 1, this function will act as if called with prefix arg
6713 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6714 prefix arg, but only
6715 if the variable `org-cycle-global-at-bob' is t."
6717 (org-load-modules-maybe)
6718 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6719 (and org-cycle-level-after-item
/entry-creation
6720 (or (org-cycle-level)
6721 (org-cycle-item-indentation))))
6723 (or org-cycle-max-level
6724 (and (boundp 'org-inlinetask-min-level
)
6725 org-inlinetask-min-level
6726 (1- org-inlinetask-min-level
))))
6727 (nstars (and limit-level
6728 (if org-odd-levels-only
6729 (and limit-level
(1- (* limit-level
2)))
6732 (if (not (derived-mode-p 'org-mode
))
6734 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6735 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6736 (not (looking-at org-outline-regexp
))))
6739 (delq 'org-optimize-window-after-visibility-change
6740 (copy-sequence org-cycle-hook
))
6747 (setq last-command
'dummy
)
6748 (org-set-startup-visibility)
6749 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6753 (org-unlogged-message "Entire buffer visible, including drawers"))
6755 ((equal arg
'(4)) (org-cycle-internal-global))
6757 ;; Try hiding block at point.
6758 ((org-hide-block-toggle-maybe))
6760 ;; Try cdlatex TAB completion
6761 ((org-try-cdlatex-tab))
6763 ;; Table: enter it or move to the next field.
6764 ((org-at-table-p 'any
)
6765 (if (org-at-table.el-p
)
6766 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6767 Use `\\[org-edit-special]' to edit table.el tables"))
6768 (if arg
(org-table-edit-field t
)
6769 (org-table-justify-field-maybe)
6770 (call-interactively 'org-table-next-field
))))
6772 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook
))
6774 ;; Global cycling: delegate to `org-cycle-internal-global'.
6775 (bob-special (org-cycle-internal-global))
6777 ;; Drawers: delegate to `org-flag-drawer'.
6779 (beginning-of-line 1)
6780 (looking-at org-drawer-regexp
))
6781 (org-flag-drawer ; toggle block visibility
6782 (not (get-char-property (match-end 0) 'invisible
))))
6784 ;; Show-subtree, ARG levels up from here.
6787 (org-back-to-heading)
6788 (outline-up-heading (if (< arg
0) (- arg
)
6789 (- (funcall outline-level
) arg
)))
6790 (org-show-subtree)))
6792 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6793 ((and (featurep 'org-inlinetask
)
6794 (org-inlinetask-at-task-p)
6795 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6796 (org-inlinetask-toggle-visibility))
6798 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6799 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6800 (save-excursion (move-beginning-of-line 1)
6801 (looking-at org-outline-regexp
)))
6802 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6803 (org-cycle-internal-local))
6805 ;; From there: TAB emulation and template completion.
6806 (buffer-read-only (org-back-to-heading))
6808 ((run-hook-with-args-until-success
6809 'org-tab-after-check-for-cycling-hook
))
6811 ((org-try-structure-completion))
6813 ((run-hook-with-args-until-success
6814 'org-tab-before-tab-emulation-hook
))
6816 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6818 (not (looking-at org-outline-regexp
))))
6819 (call-interactively (global-key-binding "\t")))
6821 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6822 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6823 (or (and (eq org-cycle-emulate-tab
'white
)
6824 (= (match-end 0) (point-at-eol)))
6825 (and (eq org-cycle-emulate-tab
'whitestart
)
6826 (>= (match-end 0) pos
))))
6828 (eq org-cycle-emulate-tab t
))
6829 (call-interactively (global-key-binding "\t")))
6832 (org-back-to-heading)
6835 (defun org-cycle-internal-global ()
6836 "Do the global cycling action."
6837 ;; Hack to avoid display of messages for .org attachments in Gnus
6838 (let ((ga (string-match "\\*fontification" (buffer-name))))
6840 ((and (eq last-command this-command
)
6841 (eq org-cycle-global-status
'overview
))
6842 ;; We just created the overview - now do table of contents
6843 ;; This can be slow in very large buffers, so indicate action
6844 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6845 (unless ga
(org-unlogged-message "CONTENTS..."))
6847 (unless ga
(org-unlogged-message "CONTENTS...done"))
6848 (setq org-cycle-global-status
'contents
)
6849 (run-hook-with-args 'org-cycle-hook
'contents
))
6851 ((and (eq last-command this-command
)
6852 (eq org-cycle-global-status
'contents
))
6853 ;; We just showed the table of contents - now show everything
6854 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6856 (unless ga
(org-unlogged-message "SHOW ALL"))
6857 (setq org-cycle-global-status
'all
)
6858 (run-hook-with-args 'org-cycle-hook
'all
))
6861 ;; Default action: go to overview
6862 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6864 (unless ga
(org-unlogged-message "OVERVIEW"))
6865 (setq org-cycle-global-status
'overview
)
6866 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6868 (defvar org-called-with-limited-levels nil
6869 "Non-nil when `org-with-limited-levels' is currently active.")
6871 (defun org-invisible-p (&optional pos
)
6872 "Non-nil if the character after POS is invisible.
6873 If POS is nil, use `point' instead."
6874 (get-char-property (or pos
(point)) 'invisible
))
6876 (defun org-cycle-internal-local ()
6877 "Do the local cycling action."
6878 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6879 ;; First, determine end of headline (EOH), end of subtree or item
6880 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6885 (setq struct
(org-list-struct))
6886 (setq eoh
(point-at-eol))
6887 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6888 (setq has-children
(org-list-has-child-p (point) struct
)))
6889 (org-back-to-heading)
6890 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6891 (setq eos
(save-excursion (org-end-of-subtree t t
)
6892 (when (bolp) (backward-char)) (point)))
6895 (let ((level (funcall outline-level
)))
6896 (outline-next-heading)
6897 (and (org-at-heading-p t
)
6898 (> (funcall outline-level
) level
))))
6900 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6901 ;; Determine end invisible part of buffer (EOL)
6902 (beginning-of-line 2)
6903 (while (and (not (eobp)) ;This is like `next-line'.
6904 (get-char-property (1- (point)) 'invisible
))
6905 (goto-char (next-single-char-property-change (point) 'invisible
))
6906 (and (eolp) (beginning-of-line 2)))
6908 ;; Find out what to do next and set `this-command'
6911 ;; Nothing is hidden behind this heading
6912 (unless (org-before-first-heading-p)
6913 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6914 (org-unlogged-message "EMPTY ENTRY")
6915 (setq org-cycle-subtree-status nil
)
6918 (outline-next-heading)
6919 (when (org-invisible-p) (org-flag-heading nil
))))
6920 ((and (or (>= eol eos
)
6921 (not (string-match "\\S-" (buffer-substring eol eos
))))
6923 (not (setq children-skipped
6924 org-cycle-skip-children-state-if-no-children
))))
6925 ;; Entire subtree is hidden in one line: children view
6926 (unless (org-before-first-heading-p)
6927 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6929 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6931 (org-with-limited-levels (org-show-children))
6932 (org-show-set-visibility 'canonical
)
6933 ;; FIXME: This slows down the func way too much.
6934 ;; How keep drawers hidden in subtree anyway?
6935 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6936 ;; (org-cycle-hide-drawers 'subtree))
6938 ;; Fold every list in subtree to top-level items.
6939 (when (eq org-cycle-include-plain-lists
'integrate
)
6941 (org-back-to-heading)
6942 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6943 (beginning-of-line 1)
6944 (let* ((struct (org-list-struct))
6945 (prevs (org-list-prevs-alist struct
))
6946 (end (org-list-get-bottom-point struct
)))
6947 (dolist (e (org-list-get-all-items (point) struct prevs
))
6948 (org-list-set-item-visibility e struct
'folded
))
6949 (goto-char (if (< end eos
) end eos
)))))))
6950 (org-unlogged-message "CHILDREN")
6953 (outline-next-heading)
6954 (when (org-invisible-p) (org-flag-heading nil
)))
6955 (setq org-cycle-subtree-status
'children
)
6956 (unless (org-before-first-heading-p)
6957 (run-hook-with-args 'org-cycle-hook
'children
)))
6958 ((or children-skipped
6959 (and (eq last-command this-command
)
6960 (eq org-cycle-subtree-status
'children
)))
6961 ;; We just showed the children, or no children are there,
6962 ;; now show everything.
6963 (unless (org-before-first-heading-p)
6964 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6965 (outline-flag-region eoh eos nil
)
6966 (org-unlogged-message
6967 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6968 (setq org-cycle-subtree-status
'subtree
)
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6972 ;; Default action: hide the subtree.
6973 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6974 (outline-flag-region eoh eos t
)
6975 (org-unlogged-message "FOLDED")
6976 (setq org-cycle-subtree-status
'folded
)
6977 (unless (org-before-first-heading-p)
6978 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6981 (defun org-global-cycle (&optional arg
)
6982 "Cycle the global visibility. For details see `org-cycle'.
6983 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6984 With a numeric prefix, show all headlines up to that level."
6986 (let ((org-cycle-include-plain-lists
6987 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6991 (outline-hide-sublevels arg
)
6992 (setq org-cycle-global-status
'contents
))
6994 (org-set-startup-visibility)
6995 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6997 (org-cycle '(4))))))
6999 (defun org-set-startup-visibility ()
7000 "Set the visibility required by startup options and properties."
7002 ((eq org-startup-folded t
)
7004 ((eq org-startup-folded
'content
)
7006 ((or (eq org-startup-folded
'showeverything
)
7007 (eq org-startup-folded nil
))
7008 (outline-show-all)))
7009 (unless (eq org-startup-folded
'showeverything
)
7010 (when org-hide-block-startup
(org-hide-block-all))
7011 (org-set-visibility-according-to-property 'no-cleanup
)
7012 (org-cycle-hide-archived-subtrees 'all
)
7013 (org-cycle-hide-drawers 'all
)
7014 (org-cycle-show-empty-lines t
)))
7016 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
7017 "Switch subtree visibilities according to :VISIBILITY: property."
7019 (org-with-wide-buffer
7020 (goto-char (point-min))
7021 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t
)
7022 (if (not (org-at-property-p)) (outline-next-heading)
7023 (let ((state (match-string 3)))
7025 (org-back-to-heading t
)
7026 (outline-hide-subtree)
7029 ((equal state
"folded")
7030 (outline-hide-subtree)
7031 (org-end-of-subtree t t
))
7032 ((equal state
"children")
7033 (org-show-hidden-entry)
7034 (org-show-children))
7035 ((equal state
"content")
7038 (org-narrow-to-subtree)
7040 (org-end-of-subtree t t
))
7041 ((member state
'("all" "showall"))
7042 (outline-show-subtree))))))
7044 (org-cycle-hide-archived-subtrees 'all
)
7045 (org-cycle-hide-drawers 'all
)
7046 (org-cycle-show-empty-lines 'all
))))
7048 ;; This function uses outline-regexp instead of the more fundamental
7049 ;; org-outline-regexp so that org-cycle-global works outside of Org
7050 ;; buffers, where outline-regexp is needed.
7051 (defun org-overview ()
7052 "Switch to overview mode, showing only top-level headlines.
7053 This shows all headlines with a level equal or greater than the level
7054 of the first headline in the buffer. This is important, because if the
7055 first headline is not level one, then (hide-sublevels 1) gives confusing
7061 (goto-char (point-min))
7062 (when (re-search-forward (concat "^" outline-regexp
) nil t
)
7063 (goto-char (match-beginning 0))
7064 (funcall outline-level
)))))
7065 (and level
(outline-hide-sublevels level
)))))
7067 (defun org-content (&optional arg
)
7068 "Show all headlines in the buffer, like a table of contents.
7069 With numerical argument N, show content up to level N."
7073 ;; Visit all headings and show their offspring
7074 (and (integerp arg
) (org-overview))
7075 (goto-char (point-max))
7077 (while (and (progn (condition-case nil
7078 (outline-previous-visible-heading 1)
7079 (error (goto-char (point-min))))
7081 (looking-at org-outline-regexp
))
7083 (org-show-children (1- arg
))
7084 (outline-show-branches))
7085 (when (bobp) (throw 'exit nil
))))))
7087 (defun org-optimize-window-after-visibility-change (state)
7088 "Adjust the window after a change in outline visibility.
7089 This function is the default value of the hook `org-cycle-hook'."
7090 (when (get-buffer-window (current-buffer))
7092 ((eq state
'content
) nil
)
7093 ((eq state
'all
) nil
)
7094 ((eq state
'folded
) nil
)
7095 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7096 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7098 (defun org-remove-empty-overlays-at (pos)
7099 "Remove outline overlays that do not contain non-white stuff."
7100 (dolist (o (overlays-at pos
))
7101 (and (eq 'outline
(overlay-get o
'invisible
))
7102 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7104 (delete-overlay o
))))
7106 (defun org-clean-visibility-after-subtree-move ()
7107 "Fix visibility issues after moving a subtree."
7108 ;; First, find a reasonable region to look at:
7109 ;; Start two siblings above, end three below
7110 (let* ((beg (save-excursion
7111 (and (org-get-last-sibling)
7112 (org-get-last-sibling))
7114 (end (save-excursion
7115 (and (org-get-next-sibling)
7116 (org-get-next-sibling)
7117 (org-get-next-sibling))
7118 (if (org-at-heading-p)
7121 (level (looking-at "\\*+"))
7122 (re (when level
(concat "^" (regexp-quote (match-string 0)) " "))))
7125 (narrow-to-region beg end
)
7127 ;; Properly fold already folded siblings
7128 (goto-char (point-min))
7129 (while (re-search-forward re nil t
)
7130 (when (and (not (org-invisible-p))
7132 (goto-char (point-at-eol)) (org-invisible-p)))
7133 (outline-hide-entry))))
7134 (org-cycle-show-empty-lines 'overview
)
7135 (org-cycle-hide-drawers 'overview
)))))
7137 (defun org-cycle-show-empty-lines (state)
7138 "Show empty lines above all visible headlines.
7139 The region to be covered depends on STATE when called through
7140 `org-cycle-hook'. Lisp program can use t for STATE to get the
7141 entire buffer covered. Note that an empty line is only shown if there
7142 are at least `org-cycle-separator-lines' empty lines before the headline."
7143 (when (/= org-cycle-separator-lines
0)
7145 (let* ((n (abs org-cycle-separator-lines
))
7147 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7148 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7149 (t (let ((ns (number-to-string (- n
2))))
7150 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7151 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7154 ((memq state
'(overview contents t
))
7155 (setq beg
(point-min) end
(point-max)))
7156 ((memq state
'(children folded
))
7158 end
(progn (org-end-of-subtree t t
)
7159 (line-beginning-position 2)))))
7162 (while (re-search-forward re end t
)
7163 (unless (get-char-property (match-end 1) 'invisible
)
7164 (let ((e (match-end 1))
7165 (b (if (>= org-cycle-separator-lines
0)
7168 (goto-char (match-beginning 0))
7169 (skip-chars-backward " \t\n")
7170 (line-end-position)))))
7171 (outline-flag-region b e nil
))))))))
7172 ;; Never hide empty lines at the end of the file.
7174 (goto-char (point-max))
7175 (outline-previous-heading)
7176 (outline-end-of-heading)
7177 (when (and (looking-at "[ \t\n]+")
7178 (= (match-end 0) (point-max)))
7179 (outline-flag-region (point) (match-end 0) nil
))))
7181 (defun org-show-empty-lines-in-parent ()
7182 "Move to the parent and re-show empty lines before visible headlines."
7184 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7185 (org-cycle-show-empty-lines context
))))
7187 (defun org-files-list ()
7188 "Return `org-agenda-files' list, plus all open Org files.
7189 This is useful for operations that need to scan all of a user's
7190 open and agenda-wise Org files."
7191 (let ((files (mapcar #'expand-file-name
(org-agenda-files))))
7192 (dolist (buf (buffer-list))
7193 (with-current-buffer buf
7194 (when (and (derived-mode-p 'org-mode
) (buffer-file-name))
7195 (cl-pushnew (expand-file-name (buffer-file-name)) files
7199 (defsubst org-entry-beginning-position
()
7200 "Return the beginning position of the current entry."
7201 (save-excursion (org-back-to-heading t
) (point)))
7203 (defsubst org-entry-end-position
()
7204 "Return the end position of the current entry."
7205 (save-excursion (outline-next-heading) (point)))
7207 (defun org-cycle-hide-drawers (state &optional exceptions
)
7208 "Re-hide all drawers after a visibility state change.
7209 STATE should be one of the symbols listed in the docstring of
7210 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7211 a list of strings specifying which drawers should not be hidden."
7212 (when (and (derived-mode-p 'org-mode
)
7213 (not (memq state
'(overview folded contents
))))
7215 (let* ((globalp (eq state
'all
))
7216 (beg (if globalp
(point-min) (point)))
7217 (end (if globalp
(point-max)
7218 (if (eq state
'children
)
7219 (save-excursion (outline-next-heading) (point))
7220 (org-end-of-subtree t
)))))
7222 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7223 (unless (member-ignore-case (match-string 1) exceptions
)
7224 (let ((drawer (org-element-at-point)))
7225 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7226 (org-flag-drawer t drawer
)
7227 ;; Make sure to skip drawer entirely or we might flag
7228 ;; it another time when matching its ending line with
7229 ;; `org-drawer-regexp'.
7230 (goto-char (org-element-property :end drawer
))))))))))
7232 (defun org-flag-drawer (flag &optional element
)
7233 "When FLAG is non-nil, hide the drawer we are at.
7234 Otherwise make it visible. When optional argument ELEMENT is
7235 a parsed drawer, as returned by `org-element-at-point', hide or
7236 show that drawer instead."
7237 (let ((drawer (or element
7238 (and (save-excursion
7240 (looking-at-p org-drawer-regexp
))
7241 (org-element-at-point)))))
7242 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7243 (let ((post (org-element-property :post-affiliated drawer
)))
7245 (outline-flag-region
7246 (progn (goto-char post
) (line-end-position))
7247 (progn (goto-char (org-element-property :end drawer
))
7248 (skip-chars-backward " \r\t\n")
7249 (line-end-position))
7251 ;; When the drawer is hidden away, make sure point lies in
7252 ;; a visible part of the buffer.
7253 (when (and flag
(> (line-beginning-position) post
))
7254 (goto-char post
))))))
7256 (defun org-subtree-end-visible-p ()
7257 "Is the end of the current subtree visible?"
7258 (pos-visible-in-window-p
7259 (save-excursion (org-end-of-subtree t
) (point))))
7261 (defun org-first-headline-recenter ()
7262 "Move cursor to the first headline and recenter the headline."
7263 (let ((window (get-buffer-window)))
7265 (goto-char (point-min))
7266 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7267 (set-window-start window
(line-beginning-position))))))
7269 ;;; Saving and restoring visibility
7271 (defun org-outline-overlay-data (&optional use-markers
)
7272 "Return a list of the locations of all outline overlays.
7273 These are overlays with the `invisible' property value `outline'.
7274 The return value is a list of cons cells, with start and stop
7275 positions for each overlay.
7276 If USE-MARKERS is set, return the positions as markers."
7278 (org-with-wide-buffer
7281 (when (eq (overlay-get o
'invisible
) 'outline
)
7282 (setq beg
(overlay-start o
)
7283 end
(overlay-end o
))
7284 (and beg end
(> end beg
)
7286 (cons (copy-marker beg
)
7287 (copy-marker end t
))
7289 (overlays-in (point-min) (point-max)))))))
7291 (defun org-set-outline-overlay-data (data)
7292 "Create visibility overlays for all positions in DATA.
7293 DATA should have been made by `org-outline-overlay-data'."
7294 (org-with-wide-buffer
7296 (dolist (c data
) (outline-flag-region (car c
) (cdr c
) t
))))
7298 ;;; Folding of blocks
7300 (defvar-local org-hide-block-overlays nil
7301 "Overlays hiding blocks.")
7303 (defun org-block-map (function &optional start end
)
7304 "Call FUNCTION at the head of all source blocks in the current buffer.
7305 Optional arguments START and END can be used to limit the range."
7306 (let ((start (or start
(point-min)))
7307 (end (or end
(point-max))))
7310 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7313 (goto-char (match-beginning 0))
7314 (funcall function
)))))))
7316 (defun org-hide-block-toggle-all ()
7317 "Toggle the visibility of all blocks in the current buffer."
7318 (org-block-map 'org-hide-block-toggle
))
7320 (defun org-hide-block-all ()
7321 "Fold all blocks in the current buffer."
7323 (org-show-block-all)
7324 (org-block-map 'org-hide-block-toggle-maybe
))
7326 (defun org-show-block-all ()
7327 "Unfold all blocks in the current buffer."
7329 (mapc #'delete-overlay org-hide-block-overlays
)
7330 (setq org-hide-block-overlays nil
))
7332 (defun org-hide-block-toggle-maybe ()
7333 "Toggle visibility of block at point.
7334 Unlike to `org-hide-block-toggle', this function does not throw
7335 an error. Return a non-nil value when toggling is successful."
7337 (ignore-errors (org-hide-block-toggle)))
7339 (defun org-hide-block-toggle (&optional force
)
7340 "Toggle the visibility of the current block.
7341 When optional argument FORCE is `off', make block visible. If it
7342 is non-nil, hide it unconditionally. Throw an error when not at
7343 a block. Return a non-nil value when toggling is successful."
7345 (let ((element (org-element-at-point)))
7346 (unless (memq (org-element-type element
)
7347 '(center-block comment-block dynamic-block example-block
7348 export-block quote-block special-block
7349 src-block verse-block
))
7350 (user-error "Not at a block"))
7351 (let* ((start (save-excursion
7352 (goto-char (org-element-property :post-affiliated element
))
7353 (line-end-position)))
7354 (end (save-excursion
7355 (goto-char (org-element-property :end element
))
7356 (skip-chars-backward " \r\t\n")
7357 (line-end-position)))
7358 (overlays (overlays-at start
)))
7360 ;; Do nothing when not before or at the block opening line or
7361 ;; at the block closing line.
7362 ((let ((eol (line-end-position))) (and (> eol start
) (/= eol end
))) nil
)
7363 ((and (not (eq force
'off
))
7364 (not (memq t
(mapcar
7366 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7368 (let ((ov (make-overlay start end
)))
7369 (overlay-put ov
'invisible
'org-hide-block
)
7370 ;; Make the block accessible to `isearch'.
7372 ov
'isearch-open-invisible
7374 (when (memq ov org-hide-block-overlays
)
7375 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7376 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7377 (delete-overlay ov
))))
7378 (push ov org-hide-block-overlays
)
7379 ;; When the block is hidden away, make sure point is left in
7380 ;; a visible part of the buffer.
7381 (when (> (line-beginning-position) start
)
7383 (beginning-of-line))
7384 ;; Signal successful toggling.
7386 ((or (not force
) (eq force
'off
))
7387 (dolist (ov overlays t
)
7388 (when (memq ov org-hide-block-overlays
)
7389 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7390 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7391 (delete-overlay ov
))))))))
7393 ;; Remove overlays when changing major mode
7394 (add-hook 'org-mode-hook
7395 (lambda () (add-hook 'change-major-mode-hook
7396 'org-show-block-all
'append
'local
)))
7400 (defvar org-goto-window-configuration nil
)
7401 (defvar org-goto-marker nil
)
7402 (defvar org-goto-map
)
7403 (defun org-goto-map ()
7404 "Set the keymap `org-goto'."
7406 (let ((map (make-sparse-keymap)))
7407 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7408 mouse-drag-region universal-argument org-occur
)))
7410 (substitute-key-definition cmd cmd map global-map
)))
7411 (suppress-keymap map
)
7412 (org-defkey map
"\C-m" 'org-goto-ret
)
7413 (org-defkey map
[(return)] 'org-goto-ret
)
7414 (org-defkey map
[(left)] 'org-goto-left
)
7415 (org-defkey map
[(right)] 'org-goto-right
)
7416 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7417 (org-defkey map
"\C-i" 'org-cycle
)
7418 (org-defkey map
[(tab)] 'org-cycle
)
7419 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7420 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7421 (if org-goto-auto-isearch
7422 (if (fboundp 'define-key-after
)
7423 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7425 (org-defkey map "q" 'org-goto-quit)
7426 (org-defkey map "n" 'outline-next-visible-heading)
7427 (org-defkey map "p" 'outline-previous-visible-heading)
7428 (org-defkey map "f" 'outline-forward-same-level)
7429 (org-defkey map "b" 'outline-backward-same-level)
7430 (org-defkey map "u" 'outline-up-heading))
7431 (org-defkey map "/" 'org-occur)
7432 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7433 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7434 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7435 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7436 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7439 (defconst org-goto-help
7440 "Browse buffer copy, to find location or copy text.%s
7441 RET=jump to location C-g=quit and return to previous location
7442 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7444 (defvar org-goto-start-pos) ; dynamically scoped parameter
7446 (defun org-goto (&optional alternative-interface)
7447 "Look up a different location in the current file, keeping current visibility.
7449 When you want look-up or go to a different location in a
7450 document, the fastest way is often to fold the entire buffer and
7451 then dive into the tree. This method has the disadvantage, that
7452 the previous location will be folded, which may not be what you
7455 This command works around this by showing a copy of the current
7456 buffer in an indirect buffer, in overview mode. You can dive
7457 into the tree in that copy, use org-occur and incremental search
7458 to find a location. When pressing RET or `Q', the command
7459 returns to the original buffer in which the visibility is still
7460 unchanged. After RET it will also jump to the location selected
7461 in the indirect buffer and expose the headline hierarchy above.
7463 With a prefix argument, use the alternative interface: e.g., if
7464 `org-goto-interface' is `outline' use `outline-path-completion'."
7467 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7468 (org-refile-use-outline-path t)
7469 (org-refile-target-verify-function nil)
7471 (if (not alternative-interface)
7473 (if (eq org-goto-interface 'outline)
7474 'outline-path-completion
7476 (org-goto-start-pos (point))
7478 (if (eq interface 'outline)
7479 (car (org-get-location (current-buffer) org-goto-help))
7480 (let ((pa (org-refile-get-location "Goto")))
7481 (org-refile-check-position pa)
7485 (org-mark-ring-push org-goto-start-pos)
7486 (goto-char selected-point)
7487 (when (or (org-invisible-p) (org-invisible-p2))
7488 (org-show-context 'org-goto)))
7491 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7492 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7493 (defvar org-goto-local-auto-isearch-map) ; defined below
7495 (defun org-get-location (_buf help)
7496 "Let the user select a location in current buffer.
7497 This function uses a recursive edit. It returns the selected position
7500 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7501 (isearch-hide-immediately nil)
7502 (isearch-search-fun-function
7503 (lambda () 'org-goto-local-search-headings))
7504 (org-goto-selected-point org-goto-exit-command))
7506 (save-window-excursion
7507 (delete-other-windows)
7508 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7509 (pop-to-buffer-same-window
7511 (make-indirect-buffer (current-buffer) "*org-goto*")
7512 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7513 (with-output-to-temp-buffer "*Org Help*"
7514 (princ (format help (if org-goto-auto-isearch
7515 " Just type for auto-isearch."
7516 " n/p/f/b/u to navigate, q to quit."))))
7517 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7518 (setq buffer-read-only nil)
7519 (let ((org-startup-truncated t)
7520 (org-startup-folded nil)
7521 (org-startup-align-all-tables nil))
7524 (setq buffer-read-only t)
7525 (if (and (boundp 'org-goto-start-pos)
7526 (integer-or-marker-p org-goto-start-pos))
7527 (progn (goto-char org-goto-start-pos)
7528 (when (org-invisible-p)
7529 (org-show-set-visibility 'lineage)))
7530 (goto-char (point-min)))
7531 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7532 (message "Select location and press RET")
7533 (use-local-map org-goto-map)
7535 (kill-buffer "*org-goto*")
7536 (cons org-goto-selected-point org-goto-exit-command))))
7538 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7539 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7540 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7541 (if (fboundp 'isearch-other-control-char)
7543 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7544 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7545 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7546 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7547 (define-key org-goto-local-auto-isearch-map [return] nil))
7549 (defun org-goto-local-search-headings (string bound noerror)
7550 "Search and make sure that any matches are in headlines."
7552 (while (if isearch-forward
7553 (search-forward string bound noerror)
7554 (search-backward string bound noerror))
7555 (when (save-match-data
7556 (and (save-excursion
7558 (looking-at org-complex-heading-regexp))
7559 (or (not (match-beginning 5))
7560 (< (point) (match-beginning 5)))))
7561 (throw 'return (point))))))
7563 (defun org-goto-local-auto-isearch ()
7566 (goto-char (point-min))
7567 (let ((keys (this-command-keys)))
7568 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7570 (isearch-process-search-char (string-to-char keys)))))
7572 (defun org-goto-ret (&optional _arg)
7573 "Finish `org-goto' by going to the new location."
7575 (setq org-goto-selected-point (point))
7576 (setq org-goto-exit-command 'return)
7579 (defun org-goto-left ()
7580 "Finish `org-goto' by going to the new location."
7582 (if (org-at-heading-p)
7584 (beginning-of-line 1)
7585 (setq org-goto-selected-point (point)
7586 org-goto-exit-command 'left)
7588 (user-error "Not on a heading")))
7590 (defun org-goto-right ()
7591 "Finish `org-goto' by going to the new location."
7593 (if (org-at-heading-p)
7595 (setq org-goto-selected-point (point)
7596 org-goto-exit-command 'right)
7598 (user-error "Not on a heading")))
7600 (defun org-goto-quit ()
7601 "Finish `org-goto' without cursor motion."
7603 (setq org-goto-selected-point nil)
7604 (setq org-goto-exit-command 'quit)
7607 ;;; Indirect buffer display of subtrees
7609 (defvar org-indirect-dedicated-frame nil
7610 "This is the frame being used for indirect tree display.")
7611 (defvar org-last-indirect-buffer nil)
7613 (defun org-tree-to-indirect-buffer (&optional arg)
7614 "Create indirect buffer and narrow it to current subtree.
7616 With a numerical prefix ARG, go up to this level and then take that tree.
7617 If ARG is negative, go up that many levels.
7619 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7620 indirect buffer previously made with this command, to avoid proliferation of
7621 indirect buffers. However, when you call the command with a \
7622 `\\[universal-argument]' prefix, or
7623 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7624 so that you can work with several indirect buffers at the same time. If
7625 `org-indirect-buffer-display' is `dedicated-frame', the \
7626 `\\[universal-argument]' prefix also
7627 requests that a new frame be made for the new buffer, so that the dedicated
7628 frame is not changed."
7630 (let ((cbuf (current-buffer))
7631 (cwin (selected-window))
7633 beg end level heading ibuf)
7635 (org-back-to-heading t)
7637 (setq level (org-outline-level))
7638 (when (< arg 0) (setq arg (+ level arg)))
7639 (while (> (setq level (org-outline-level)) arg)
7640 (org-up-heading-safe)))
7642 heading (org-get-heading 'no-tags))
7643 (org-end-of-subtree t t)
7644 (when (org-at-heading-p) (backward-char 1))
7646 (when (and (buffer-live-p org-last-indirect-buffer)
7647 (not (eq org-indirect-buffer-display 'new-frame))
7649 (kill-buffer org-last-indirect-buffer))
7650 (setq ibuf (org-get-indirect-buffer cbuf heading)
7651 org-last-indirect-buffer ibuf)
7653 ((or (eq org-indirect-buffer-display 'new-frame)
7654 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7655 (select-frame (make-frame))
7656 (delete-other-windows)
7657 (pop-to-buffer-same-window ibuf)
7658 (org-set-frame-title heading))
7659 ((eq org-indirect-buffer-display 'dedicated-frame)
7661 (select-frame (or (and org-indirect-dedicated-frame
7662 (frame-live-p org-indirect-dedicated-frame)
7663 org-indirect-dedicated-frame)
7664 (setq org-indirect-dedicated-frame (make-frame)))))
7665 (delete-other-windows)
7666 (pop-to-buffer-same-window ibuf)
7667 (org-set-frame-title (concat "Indirect: " heading)))
7668 ((eq org-indirect-buffer-display 'current-window)
7669 (pop-to-buffer-same-window ibuf))
7670 ((eq org-indirect-buffer-display 'other-window)
7671 (pop-to-buffer ibuf))
7672 (t (error "Invalid value")))
7673 (narrow-to-region beg end)
7676 (run-hook-with-args 'org-cycle-hook 'all)
7677 (and (window-live-p cwin) (select-window cwin))))
7679 (defun org-get-indirect-buffer (&optional buffer heading)
7680 (setq buffer (or buffer (current-buffer)))
7681 (let ((n 1) (base (buffer-name buffer)) bname)
7682 (while (buffer-live-p
7686 (if heading (concat heading "-" (number-to-string n))
7687 (number-to-string n))))))
7690 (make-indirect-buffer buffer bname 'clone)
7691 (error (make-indirect-buffer buffer bname)))))
7693 (defun org-set-frame-title (title)
7694 "Set the title of the current frame to the string TITLE."
7695 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7697 ;;;; Structure editing
7699 ;;; Inserting headlines
7701 (defun org--line-empty-p (n)
7702 "Is the Nth next line empty?
7704 Counts the current line as N = 1 and the previous line as N = 0;
7705 see `beginning-of-line'."
7708 (or (beginning-of-line n) t)
7710 (looking-at "[ \t]*$")))))
7712 (defun org-previous-line-empty-p ()
7713 "Is the previous line a blank line?
7714 When NEXT is non-nil, check the next line instead."
7715 (org--line-empty-p 0))
7717 (defun org-next-line-empty-p ()
7718 "Is the previous line a blank line?
7719 When NEXT is non-nil, check the next line instead."
7720 (org--line-empty-p 2))
7722 (defun org--blank-before-heading-p (&optional parent)
7723 "Non-nil when an empty line should precede a new heading here.
7724 When optional argument PARENT is non-nil, consider parent
7725 headline instead of current one."
7726 (pcase (assq 'heading org-blank-before-new-entry)
7729 (org-with-limited-levels
7730 (unless (and (org-before-first-heading-p)
7731 (not (outline-next-heading)))
7732 (org-back-to-heading t)
7733 (when parent (org-up-heading-safe))
7735 (org-previous-line-empty-p))
7736 ((outline-next-heading)
7737 (org-previous-line-empty-p))
7738 ;; Ignore trailing spaces on last buffer line.
7739 ((progn (skip-chars-backward " \t") (bolp))
7740 (org-previous-line-empty-p))
7742 (`(heading . ,value) value)
7745 (defun org-insert-heading (&optional arg invisible-ok top)
7746 "Insert a new heading or an item with the same depth at point.
7748 If point is at the beginning of a heading, insert a new heading
7749 or a new headline above the current one. When at the beginning
7750 of a regular line of text, turn it into a heading.
7752 If point is in the middle of a line, split it and create a new
7753 headline with the text in the current line after point (see
7754 `org-M-RET-may-split-line' on how to modify this behavior). As
7755 a special case, on a headline, splitting can only happen on the
7756 title itself. E.g., this excludes breaking stars or tags.
7758 With a `\\[universal-argument]' prefix, set \
7759 `org-insert-heading-respect-content' to
7760 a non-nil value for the duration of the command. This forces the
7761 insertion of a heading after the current subtree, independently
7762 on the location of point.
7764 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7765 insert the heading at the end of the tree
7766 above the current heading. For example, if point is within a
7767 2nd-level heading, then it will insert a 2nd-level heading at
7768 the end of the 1st-level parent subtree.
7770 When INVISIBLE-OK is set, stop at invisible headlines when going
7771 back. This is important for non-interactive uses of the
7774 When optional argument TOP is non-nil, insert a level 1 heading,
7777 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7778 (level (org-current-level))
7779 (stars (make-string (if (and level (not top)) level 1) ?*)))
7781 ((or org-insert-heading-respect-content
7782 (member arg '((4) (16)))
7783 (and (not invisible-ok)
7784 (invisible-p (max (1- (point)) (point-min)))))
7785 ;; Position point at the location of insertion.
7786 (if (not level) ;before first headline
7787 (org-with-limited-levels (outline-next-heading))
7788 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7790 (org-with-limited-levels (org-back-to-heading invisible-ok))
7791 (cond ((equal arg '(16))
7792 (org-up-heading-safe)
7793 (org-end-of-subtree t t))
7795 (org-end-of-subtree t t))))
7796 (unless (bolp) (insert "\n")) ;ensure final newline
7797 (unless (and blank? (org-previous-line-empty-p))
7798 (org-N-empty-lines-before-current (if blank? 1 0)))
7799 (insert stars " \n")
7804 (when blank? (save-excursion (insert "\n")))
7805 (save-excursion (insert stars " \n"))
7806 (unless (and blank? (org-previous-line-empty-p))
7807 (org-N-empty-lines-before-current (if blank? 1 0)))
7809 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7810 (org-match-line org-complex-heading-regexp)
7811 (org-pos-in-match-range (point) 4))
7812 ;; Grab the text that should moved to the new headline.
7814 (let ((split (delete-and-extract-region (point) (match-end 4))))
7815 (if (looking-at "[ \t]*$") (replace-match "")
7816 (org-set-tags nil t))
7818 (when blank? (insert "\n"))
7819 (insert "\n" stars " ")
7820 (when (org-string-nw-p split) (insert split))
7821 (when (eobp) (save-excursion (insert "\n")))))
7824 (when blank? (insert "\n"))
7825 (insert "\n" stars " ")
7826 (when (eobp) (save-excursion (insert "\n"))))))
7827 ;; On regular text, turn line into a headline or split, if
7831 (unless (and blank? (org-previous-line-empty-p))
7832 (org-N-empty-lines-before-current (if blank? 1 0))))
7834 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7836 (insert "\n" stars " ")
7837 (unless (and blank? (org-previous-line-empty-p))
7838 (org-N-empty-lines-before-current (if blank? 1 0))))))
7839 (run-hooks 'org-insert-heading-hook))
7841 (defun org-N-empty-lines-before-current (n)
7842 "Make the number of empty lines before current exactly N.
7843 So this will delete or add empty lines."
7844 (let ((column (current-column)))
7847 (let ((start (save-excursion
7848 (skip-chars-backward " \r\t\n")
7849 (line-end-position))))
7850 (delete-region start (line-end-position 0))))
7851 (insert (make-string n ?\n))
7852 (move-to-column column)))
7854 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7855 "Return the heading of the current entry, without the stars.
7856 When NO-TAGS is non-nil, don't include tags.
7857 When NO-TODO is non-nil, don't include TODO keywords.
7858 When NO-PRIORITY is non-nil, don't include priority cookie.
7859 When NO-COMMENT is non-nil, don't include COMMENT string."
7861 (org-back-to-heading t)
7862 (let ((case-fold-search nil))
7863 (looking-at org-complex-heading-regexp)
7864 (let ((todo (and (not no-todo) (match-string 2)))
7865 (priority (and (not no-priority) (match-string 3)))
7866 (headline (pcase (match-string 4)
7868 ((and (guard no-comment) h)
7869 (replace-regexp-in-string
7871 (format "\\`%s[ \t]+" org-comment-string))
7874 (tags (and (not no-tags) (match-string 5))))
7875 (mapconcat #'identity
7876 (delq nil (list todo priority headline tags))
7879 (defvar orgstruct-mode) ; defined below
7881 (defun org-heading-components ()
7882 "Return the components of the current heading.
7883 This is a list with the following elements:
7884 - the level as an integer
7885 - the reduced level, different if `org-odd-levels-only' is set.
7886 - the TODO keyword, or nil
7887 - the priority character, like ?A, or nil if no priority is given
7888 - the headline text itself, or the tags string if no headline text
7889 - the tags string, or nil."
7891 (org-back-to-heading t)
7892 (when (let (case-fold-search)
7896 org-complex-heading-regexp)))
7898 (list (length (match-string 1))
7899 (org-reduced-level (length (match-string 1)))
7904 (list (length (match-string 1))
7905 (org-reduced-level (length (match-string 1)))
7906 (match-string-no-properties 2)
7907 (and (match-end 3) (aref (match-string 3) 2))
7908 (match-string-no-properties 4)
7909 (match-string-no-properties 5))))))
7911 (defun org-get-entry ()
7912 "Get the entry text, after heading, entire subtree."
7914 (org-back-to-heading t)
7915 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7917 (defun org-edit-headline (&optional heading)
7918 "Edit the current headline.
7919 Set it to HEADING when provided."
7921 (org-with-wide-buffer
7922 (org-back-to-heading t)
7923 (let ((case-fold-search nil))
7924 (when (looking-at org-complex-heading-regexp)
7925 (let* ((old (match-string-no-properties 4))
7926 (new (save-match-data
7927 (org-trim (or heading (read-string "Edit: " old))))))
7928 (unless (equal old new)
7929 (if old (replace-match new t t nil 4)
7930 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7932 (org-set-tags nil t)
7933 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7935 (defun org-insert-heading-after-current ()
7936 "Insert a new heading with same level as current, after current subtree."
7938 (org-back-to-heading)
7939 (org-insert-heading)
7940 (org-move-subtree-down)
7943 (defun org-insert-heading-respect-content (&optional invisible-ok)
7944 "Insert heading with `org-insert-heading-respect-content' set to t."
7946 (org-insert-heading '(4) invisible-ok))
7948 (defun org-insert-todo-heading-respect-content (&optional force-state)
7949 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7951 (org-insert-todo-heading force-state '(4)))
7953 (defun org-insert-todo-heading (arg &optional force-heading)
7954 "Insert a new heading with the same level and TODO state as current heading.
7956 If the heading has no TODO state, or if the state is DONE, use
7957 the first state (TODO by default). Also with one prefix arg,
7958 force first state. With two prefix args, force inserting at the
7959 end of the parent subtree.
7961 When called at a plain list item, insert a new item with an
7962 unchecked check box."
7964 (when (or force-heading (not (org-insert-item 'checkbox)))
7965 (org-insert-heading (or (and (equal arg '(16)) '(16))
7968 (org-forward-heading-same-level -1)
7969 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7971 (if (or (equal arg '(4))
7972 (not (match-beginning 2))
7973 (member (match-string 2) org-done-keywords))
7974 (car org-todo-keywords-1)
7978 (run-hook-with-args-until-success
7979 'org-todo-get-default-hook new-mark-x nil)
7981 (beginning-of-line 1)
7982 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7983 (if org-treat-insert-todo-heading-as-state-change
7985 (insert new-mark " "))))
7986 (when org-provide-todo-statistics
7987 (org-update-parent-todo-statistics))))
7989 (defun org-insert-subheading (arg)
7990 "Insert a new subheading and demote it.
7991 Works for outline headings and for plain lists alike."
7993 (org-insert-heading arg)
7995 ((org-at-heading-p) (org-do-demote))
7996 ((org-at-item-p) (org-indent-item))))
7998 (defun org-insert-todo-subheading (arg)
7999 "Insert a new subheading with TODO keyword or checkbox and demote it.
8000 Works for outline headings and for plain lists alike."
8002 (org-insert-todo-heading arg)
8004 ((org-at-heading-p) (org-do-demote))
8005 ((org-at-item-p) (org-indent-item))))
8007 ;;; Promotion and Demotion
8009 (defvar org-after-demote-entry-hook nil
8010 "Hook run after an entry has been demoted.
8011 The cursor will be at the beginning of the entry.
8012 When a subtree is being demoted, the hook will be called for each node.")
8014 (defvar org-after-promote-entry-hook nil
8015 "Hook run after an entry has been promoted.
8016 The cursor will be at the beginning of the entry.
8017 When a subtree is being promoted, the hook will be called for each node.")
8019 (defun org-promote-subtree ()
8020 "Promote the entire subtree.
8021 See also `org-promote'."
8024 (org-with-limited-levels (org-map-tree 'org-promote)))
8025 (org-fix-position-after-promote))
8027 (defun org-demote-subtree ()
8028 "Demote the entire subtree.
8029 See `org-demote' and `org-promote'."
8032 (org-with-limited-levels (org-map-tree 'org-demote)))
8033 (org-fix-position-after-promote))
8035 (defun org-do-promote ()
8036 "Promote the current heading higher up the tree.
8037 If the region is active in `transient-mark-mode', promote all
8038 headings in the region."
8041 (if (org-region-active-p)
8042 (org-map-region 'org-promote (region-beginning) (region-end))
8044 (org-fix-position-after-promote))
8046 (defun org-do-demote ()
8047 "Demote the current heading lower down the tree.
8048 If the region is active in `transient-mark-mode', demote all
8049 headings in the region."
8052 (if (org-region-active-p)
8053 (org-map-region 'org-demote (region-beginning) (region-end))
8055 (org-fix-position-after-promote))
8057 (defun org-fix-position-after-promote ()
8058 "Fix cursor position and indentation after demoting/promoting."
8059 (let ((pos (point)))
8060 (when (save-excursion
8062 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8063 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8064 (cond ((eobp) (insert " "))
8065 ((eolp) (insert " "))
8066 ((equal (char-after) ?\s) (forward-char 1))))))
8068 (defun org-current-level ()
8069 "Return the level of the current entry, or nil if before the first headline.
8070 The level is the number of stars at the beginning of the
8071 headline. Use `org-reduced-level' to remove the effect of
8072 `org-odd-levels'. Unlike to `org-outline-level', this function
8073 ignores inlinetasks."
8074 (let ((level (org-with-limited-levels (org-outline-level))))
8075 (and (> level 0) level)))
8077 (defun org-get-previous-line-level ()
8078 "Return the outline depth of the last headline before the current line.
8079 Returns 0 for the first headline in the buffer, and nil if before the
8081 (and (org-current-level)
8082 (or (and (/= (line-beginning-position) (point-min))
8083 (save-excursion (beginning-of-line 0) (org-current-level)))
8086 (defun org-reduced-level (l)
8087 "Compute the effective level of a heading.
8088 This takes into account the setting of `org-odd-levels-only'."
8091 (org-odd-levels-only (1+ (floor (/ l 2))))
8094 (defun org-level-increment ()
8095 "Return the number of stars that will be added or removed at a
8096 time to headlines when structure editing, based on the value of
8097 `org-odd-levels-only'."
8098 (if org-odd-levels-only 2 1))
8100 (defun org-get-valid-level (level &optional change)
8101 "Rectify a level change under the influence of `org-odd-levels-only'.
8102 LEVEL is a current level, CHANGE is by how much the level should
8103 be modified. Even if CHANGE is nil, LEVEL may be returned
8104 modified because even level numbers will become the next higher
8105 odd number. Returns values greater than 0."
8106 (if org-odd-levels-only
8107 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8108 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8109 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8110 (max 1 (+ level (or change 0)))))
8112 (defun org-promote ()
8113 "Promote the current heading higher up the tree."
8114 (org-with-wide-buffer
8115 (org-back-to-heading t)
8116 (let* ((after-change-functions (remq 'flyspell-after-change-function
8117 after-change-functions))
8118 (level (save-match-data (funcall outline-level)))
8119 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8120 (diff (abs (- level (length up-head) -1))))
8122 ((and (= level 1) org-allow-promoting-top-level-subtree)
8123 (replace-match "# " nil t))
8125 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8126 (t (replace-match up-head nil t)))
8128 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8129 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8130 (run-hooks 'org-after-promote-entry-hook))))
8132 (defun org-demote ()
8133 "Demote the current heading lower down the tree."
8134 (org-with-wide-buffer
8135 (org-back-to-heading t)
8136 (let* ((after-change-functions (remq 'flyspell-after-change-function
8137 after-change-functions))
8138 (level (save-match-data (funcall outline-level)))
8139 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8140 (diff (abs (- level (length down-head) -1))))
8141 (replace-match down-head nil t)
8142 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8143 (when org-adapt-indentation (org-fixup-indentation diff))
8144 (run-hooks 'org-after-demote-entry-hook))))
8146 (defun org-cycle-level ()
8147 "Cycle the level of an empty headline through possible states.
8148 This goes first to child, then to parent, level, then up the hierarchy.
8149 After top level, it switches back to sibling level."
8151 (let ((org-adapt-indentation nil))
8152 (when (org-point-at-end-of-empty-headline)
8153 (setq this-command 'org-cycle-level) ; Only needed for caching
8154 (let ((cur-level (org-current-level))
8155 (prev-level (org-get-previous-line-level)))
8157 ;; If first headline in file, promote to top-level.
8159 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8160 do (org-do-promote)))
8161 ;; If same level as prev, demote one.
8162 ((= prev-level cur-level)
8164 ;; If parent is top-level, promote to top level if not already.
8166 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8167 do (org-do-promote)))
8168 ;; If top-level, return to prev-level.
8170 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8171 do (org-do-demote)))
8172 ;; If less than prev-level, promote one.
8173 ((< cur-level prev-level)
8175 ;; If deeper than prev-level, promote until higher than
8177 ((> cur-level prev-level)
8178 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8179 do (org-do-promote))))
8182 (defun org-map-tree (fun)
8183 "Call FUN for every heading underneath the current one."
8184 (org-back-to-heading t)
8185 (let ((level (funcall outline-level)))
8189 (outline-next-heading)
8190 (> (funcall outline-level) level))
8194 (defun org-map-region (fun beg end)
8195 "Call FUN for every heading between BEG and END."
8196 (let ((org-ignore-region t))
8198 (setq end (copy-marker end))
8200 (when (and (re-search-forward org-outline-regexp-bol nil t)
8204 (outline-next-heading)
8209 (defun org-fixup-indentation (diff)
8210 "Change the indentation in the current entry by DIFF.
8212 DIFF is an integer. Indentation is done according to the
8215 - Planning information and property drawers are always indented
8216 according to the new level of the headline;
8218 - Footnote definitions and their contents are ignored;
8220 - Inlinetasks' boundaries are not shifted;
8222 - Empty lines are ignored;
8224 - Other lines' indentation are shifted by DIFF columns, unless
8225 it would introduce a structural change in the document, in
8226 which case no shifting is done at all.
8228 Assume point is at a heading or an inlinetask beginning."
8229 (org-with-wide-buffer
8230 (narrow-to-region (line-beginning-position)
8232 (if (org-with-limited-levels (org-at-heading-p))
8233 (org-with-limited-levels (outline-next-heading))
8234 (org-inlinetask-goto-end))
8237 ;; Indent properly planning info and property drawer.
8238 (when (looking-at-p org-planning-line-re)
8241 (when (looking-at org-property-drawer-re)
8242 (goto-char (match-end 0))
8244 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8246 (when (zerop diff) (throw 'no-shift nil))
8247 ;; If DIFF is negative, first check if a shift is possible at all
8248 ;; (e.g., it doesn't break structure). This can only happen if
8249 ;; some contents are not properly indented.
8250 (let ((case-fold-search t))
8252 (let ((diff (- diff))
8253 (forbidden-re (concat org-outline-regexp
8255 (substring org-footnote-definition-re 1))))
8259 ((looking-at-p "[ \t]*$") (forward-line))
8260 ((and (looking-at-p org-footnote-definition-re)
8261 (let ((e (org-element-at-point)))
8262 (and (eq (org-element-type e) 'footnote-definition)
8263 (goto-char (org-element-property :end e))))))
8264 ((looking-at-p org-outline-regexp) (forward-line))
8265 ;; Give up if shifting would move before column 0 or
8266 ;; if it would introduce a headline or a footnote
8269 (skip-chars-forward " \t")
8270 (let ((ind (current-column)))
8271 (when (or (< ind diff)
8272 (and (= ind diff) (looking-at-p forbidden-re)))
8273 (throw 'no-shift nil)))
8274 ;; Ignore contents of example blocks and source
8275 ;; blocks if their indentation is meant to be
8276 ;; preserved. Jump to block's closing line.
8278 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8279 (let ((e (org-element-at-point)))
8280 (and (memq (org-element-type e)
8281 '(example-block src-block))
8282 (or org-src-preserve-indentation
8283 (org-element-property :preserve-indent e))
8284 (goto-char (org-element-property :end e))
8285 (progn (skip-chars-backward " \r\t\n")
8288 (forward-line))))))))
8289 ;; Shift lines but footnote definitions, inlinetasks boundaries
8290 ;; by DIFF. Also skip contents of source or example blocks
8291 ;; when indentation is meant to be preserved.
8294 ((and (looking-at-p org-footnote-definition-re)
8295 (let ((e (org-element-at-point)))
8296 (and (eq (org-element-type e) 'footnote-definition)
8297 (goto-char (org-element-property :end e))))))
8298 ((looking-at-p org-outline-regexp) (forward-line))
8299 ((looking-at-p "[ \t]*$") (forward-line))
8301 (indent-line-to (+ (org-get-indentation) diff))
8303 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8304 (let ((e (org-element-at-point)))
8305 (and (memq (org-element-type e)
8306 '(example-block src-block))
8307 (or org-src-preserve-indentation
8308 (org-element-property :preserve-indent e))
8309 (goto-char (org-element-property :end e))
8310 (progn (skip-chars-backward " \r\t\n")
8313 (forward-line)))))))))
8315 (defun org-convert-to-odd-levels ()
8316 "Convert an Org file with all levels allowed to one with odd levels.
8317 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8320 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8321 (let ((outline-level 'org-outline-level)
8322 (org-odd-levels-only nil) n)
8324 (goto-char (point-min))
8325 (while (re-search-forward "^\\*\\*+ " nil t)
8326 (setq n (- (length (match-string 0)) 2))
8327 (while (>= (setq n (1- n)) 0)
8329 (end-of-line 1))))))
8331 (defun org-convert-to-oddeven-levels ()
8332 "Convert an Org file with only odd levels to one with odd/even levels.
8333 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8334 file contains a section with an even level, conversion would
8335 destroy the structure of the file. An error is signaled in this
8338 (goto-char (point-min))
8339 ;; First check if there are no even levels
8340 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8341 (org-show-set-visibility 'canonical)
8342 (error "Not all levels are odd in this file. Conversion not possible"))
8343 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8344 (let ((outline-regexp org-outline-regexp)
8345 (outline-level 'org-outline-level)
8346 (org-odd-levels-only nil) n)
8348 (goto-char (point-min))
8349 (while (re-search-forward "^\\*\\*+ " nil t)
8350 (setq n (/ (1- (length (match-string 0))) 2))
8351 (while (>= (setq n (1- n)) 0)
8353 (end-of-line 1))))))
8355 (defun org-tr-level (n)
8356 "Make N odd if required."
8357 (if org-odd-levels-only (1+ (/ n 2)) n))
8359 ;;; Vertical tree motion, cutting and pasting of subtrees
8361 (defun org-move-subtree-up (&optional arg)
8362 "Move the current subtree up past ARG headlines of the same level."
8364 (org-move-subtree-down (- (prefix-numeric-value arg))))
8366 (defun org-move-subtree-down (&optional arg)
8367 "Move the current subtree down past ARG headlines of the same level."
8369 (setq arg (prefix-numeric-value arg))
8370 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8371 'org-get-last-sibling))
8372 (ins-point (make-marker))
8374 (col (current-column))
8375 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8377 (org-back-to-heading)
8380 (setq ne-beg (org-back-over-empty-lines))
8383 (save-excursion (outline-end-of-heading)
8384 (setq folded (org-invisible-p)))
8385 (progn (org-end-of-subtree nil t)
8386 (unless (eobp) (backward-char))))
8387 (outline-next-heading)
8388 (setq ne-end (org-back-over-empty-lines))
8391 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8392 ;; include less whitespace
8395 (forward-line (- ne-beg ne-end))
8396 (setq beg (point))))
8397 ;; Find insertion point, with error handling
8399 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8400 (progn (goto-char beg0)
8401 (user-error "Cannot move past superior level or buffer limit")))
8402 (setq cnt (1- cnt)))
8404 ;; Moving forward - still need to move over subtree
8405 (org-end-of-subtree t t)
8407 (org-back-over-empty-lines)
8408 (or (bolp) (newline))))
8409 (setq ne-ins (org-back-over-empty-lines))
8410 (move-marker ins-point (point))
8411 (setq txt (buffer-substring beg end))
8412 (org-save-markers-in-region beg end)
8413 (delete-region beg end)
8414 (org-remove-empty-overlays-at beg)
8415 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8416 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8417 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8418 (let ((bbb (point)))
8419 (insert-before-markers txt)
8420 (org-reinstall-markers-in-region bbb)
8421 (move-marker ins-point bbb))
8422 (or (bolp) (insert "\n"))
8423 (setq ins-end (point))
8424 (goto-char ins-point)
8425 (org-skip-whitespace)
8426 (when (and (< arg 0)
8427 (org-first-sibling-p)
8429 ;; Move whitespace back to beginning
8432 (let ((kill-whole-line t))
8433 (kill-line (- ne-ins ne-beg)) (point)))
8434 (insert (make-string (- ne-ins ne-beg) ?\n)))
8435 (move-marker ins-point nil)
8437 (outline-hide-subtree)
8440 (org-cycle-hide-drawers 'children))
8441 (org-clean-visibility-after-subtree-move)
8442 ;; move back to the initial column we were at
8443 (move-to-column col)))
8445 (defvar org-subtree-clip ""
8446 "Clipboard for cut and paste of subtrees.
8447 This is actually only a copy of the kill, because we use the normal kill
8448 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8450 (defvar org-subtree-clip-folded nil
8451 "Was the last copied subtree folded?
8452 This is used to fold the tree back after pasting.")
8454 (defun org-cut-subtree (&optional n)
8455 "Cut the current subtree into the clipboard.
8456 With prefix arg N, cut this many sequential subtrees.
8457 This is a short-hand for marking the subtree and then cutting it."
8459 (org-copy-subtree n 'cut))
8461 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8462 "Copy the current subtree it in the clipboard.
8463 With prefix arg N, copy this many sequential subtrees.
8464 This is a short-hand for marking the subtree and then copying it.
8465 If CUT is non-nil, actually cut the subtree.
8466 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8467 of some markers in the region, even if CUT is non-nil. This is
8468 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8470 (let (beg end folded (beg0 (point)))
8471 (if (called-interactively-p 'any)
8472 (org-back-to-heading nil) ; take what looks like a subtree
8473 (org-back-to-heading t)) ; take what is really there
8475 (skip-chars-forward " \t\r\n")
8478 (outline-next-heading)
8479 (save-excursion (outline-end-of-heading)
8480 (setq folded (org-invisible-p)))
8481 (ignore-errors (org-forward-heading-same-level (1- n) t))
8482 (org-end-of-subtree t t)))
8483 ;; Include the end of an inlinetask
8484 (when (and (featurep 'org-inlinetask)
8485 (looking-at-p (concat (org-inlinetask-outline-regexp)
8491 (setq org-subtree-clip-folded folded)
8492 (when (or cut force-store-markers)
8493 (org-save-markers-in-region beg end))
8494 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8495 (setq org-subtree-clip (current-kill 0))
8496 (message "%s: Subtree(s) with %d characters"
8497 (if cut "Cut" "Copied")
8498 (length org-subtree-clip)))))
8500 (defun org-paste-subtree (&optional level tree for-yank remove)
8501 "Paste the clipboard as a subtree, with modification of headline level.
8502 The entire subtree is promoted or demoted in order to match a new headline
8505 If the cursor is at the beginning of a headline, the same level as
8506 that headline is used to paste the tree.
8508 If not, the new level is derived from the *visible* headings
8509 before and after the insertion point, and taken to be the inferior headline
8510 level of the two. So if the previous visible heading is level 3 and the
8511 next is level 4 (or vice versa), level 4 will be used for insertion.
8512 This makes sure that the subtree remains an independent subtree and does
8513 not swallow low level entries.
8515 You can also force a different level, either by using a numeric prefix
8516 argument, or by inserting the heading marker by hand. For example, if the
8517 cursor is after \"*****\", then the tree will be shifted to level 5.
8519 If optional TREE is given, use this text instead of the kill ring.
8521 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8522 move back over whitespace before inserting, and move point to the end of
8523 the inserted text when done.
8525 When REMOVE is non-nil, remove the subtree from the clipboard."
8527 (setq tree (or tree (and kill-ring (current-kill 0))))
8528 (unless (org-kill-is-subtree-p tree)
8530 (substitute-command-keys
8531 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8532 (org-with-limited-levels
8533 (let* ((visp (not (org-invisible-p)))
8535 (^re_ "\\(\\*+\\)[ \t]*")
8536 (old-level (if (string-match org-outline-regexp-bol txt)
8537 (- (match-end 0) (match-beginning 0) 1)
8539 (force-level (cond (level (prefix-numeric-value level))
8540 ((and (looking-at "[ \t]*$")
8542 "^\\*+$" (buffer-substring
8543 (point-at-bol) (point))))
8544 (- (match-end 0) (match-beginning 0)))
8546 (looking-at org-outline-regexp))
8547 (- (match-end 0) (point) 1))))
8548 (previous-level (save-excursion
8551 (outline-previous-visible-heading 1)
8552 (if (looking-at ^re_)
8553 (- (match-end 0) (match-beginning 0) 1)
8556 (next-level (save-excursion
8559 (or (looking-at org-outline-regexp)
8560 (outline-next-visible-heading 1))
8561 (if (looking-at ^re_)
8562 (- (match-end 0) (match-beginning 0) 1)
8565 (new-level (or force-level (max previous-level next-level)))
8566 (shift (if (or (= old-level -1)
8568 (= old-level new-level))
8570 (- new-level old-level)))
8571 (delta (if (> shift 0) -1 1))
8572 (func (if (> shift 0) 'org-demote 'org-promote))
8573 (org-odd-levels-only nil)
8575 ;; Remove the forced level indicator
8577 (delete-region (point-at-bol) (point)))
8579 (beginning-of-line (if (bolp) 1 2))
8581 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8582 (insert-before-markers txt)
8583 (unless (string-suffix-p "\n" txt) (insert "\n"))
8584 (setq newend (point))
8585 (org-reinstall-markers-in-region beg)
8588 (skip-chars-forward " \t\n\r")
8590 (when (and (org-invisible-p) visp)
8591 (save-excursion (outline-show-heading)))
8592 ;; Shift if necessary
8595 (narrow-to-region beg end)
8596 (while (not (= shift 0))
8597 (org-map-region func (point-min) (point-max))
8598 (setq shift (+ delta shift)))
8599 (goto-char (point-min))
8600 (setq newend (point-max))))
8601 (when (or (called-interactively-p 'interactive) for-yank)
8602 (message "Clipboard pasted as level %d subtree" new-level))
8603 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8605 (eq org-subtree-clip (current-kill 0))
8606 org-subtree-clip-folded)
8607 ;; The tree was folded before it was killed/copied
8608 (outline-hide-subtree))
8609 (and for-yank (goto-char newend))
8610 (and remove (setq kill-ring (cdr kill-ring))))))
8612 (defun org-kill-is-subtree-p (&optional txt)
8613 "Check if the current kill is an outline subtree, or a set of trees.
8614 Returns nil if kill does not start with a headline, or if the first
8615 headline level is not the largest headline level in the tree.
8616 So this will actually accept several entries of equal levels as well,
8617 which is OK for `org-paste-subtree'.
8618 If optional TXT is given, check this string instead of the current kill."
8619 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8620 (re (org-get-limited-outline-regexp))
8621 (^re (concat "^" re))
8622 (start-level (and kill
8624 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8626 (- (match-end 2) (match-beginning 2) 1)))
8627 (start (1+ (or (match-beginning 2) -1))))
8628 (if (not start-level)
8630 nil) ;; does not even start with a heading
8632 (while (setq start (string-match ^re kill (1+ start)))
8633 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8637 (defvar org-markers-to-move nil
8638 "Markers that should be moved with a cut-and-paste operation.
8639 Those markers are stored together with their positions relative to
8640 the start of the region.")
8642 (defun org-save-markers-in-region (beg end)
8643 "Check markers in region.
8644 If these markers are between BEG and END, record their position relative
8645 to BEG, so that after moving the block of text, we can put the markers back
8647 This function gets called just before an entry or tree gets cut from the
8648 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8649 called immediately, to move the markers with the entries."
8650 (setq org-markers-to-move nil)
8651 (when (featurep 'org-clock)
8652 (org-clock-save-markers-for-cut-and-paste beg end))
8653 (when (featurep 'org-agenda)
8654 (org-agenda-save-markers-for-cut-and-paste beg end)))
8656 (defun org-check-and-save-marker (marker beg end)
8657 "Check if MARKER is between BEG and END.
8658 If yes, remember the marker and the distance to BEG."
8659 (when (and (marker-buffer marker)
8660 (equal (marker-buffer marker) (current-buffer))
8661 (>= marker beg) (< marker end))
8662 (push (cons marker (- marker beg)) org-markers-to-move)))
8664 (defun org-reinstall-markers-in-region (beg)
8665 "Move all remembered markers to their position relative to BEG."
8666 (dolist (x org-markers-to-move)
8667 (move-marker (car x) (+ beg (cdr x))))
8668 (setq org-markers-to-move nil))
8670 (defun org-narrow-to-subtree ()
8671 "Narrow buffer to the current subtree."
8675 (org-with-limited-levels
8677 (progn (org-back-to-heading t) (point))
8678 (progn (org-end-of-subtree t t)
8679 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8682 (defun org-narrow-to-block ()
8683 "Narrow buffer to the current block."
8685 (let* ((case-fold-search t)
8686 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8687 "^[ \t]*#\\+end_.*")))
8689 (narrow-to-region (car blockp) (cdr blockp))
8690 (user-error "Not in a block"))))
8692 (defun org-clone-subtree-with-time-shift (n &optional shift)
8693 "Clone the task (subtree) at point N times.
8694 The clones will be inserted as siblings.
8696 In interactive use, the user will be prompted for the number of
8697 clones to be produced. If the entry has a timestamp, the user
8698 will also be prompted for a time shift, which may be a repeater
8699 as used in time stamps, for example `+3d'. To disable this,
8700 you can call the function with a universal prefix argument.
8702 When a valid repeater is given and the entry contains any time
8703 stamps, the clones will become a sequence in time, with time
8704 stamps in the subtree shifted for each clone produced. If SHIFT
8705 is nil or the empty string, time stamps will be left alone. The
8706 ID property of the original subtree is removed.
8708 In each clone, all the CLOCK entries will be removed. This
8709 prevents Org from considering that the clocked times overlap.
8711 If the original subtree did contain time stamps with a repeater,
8712 the following will happen:
8713 - the repeater will be removed in each clone
8714 - an additional clone will be produced, with the current, unshifted
8715 date(s) in the entry.
8716 - the original entry will be placed *after* all the clones, with
8718 - the start days in the repeater in the original entry will be shifted
8719 to past the last clone.
8720 In this way you can spell out a number of instances of a repeating task,
8721 and still retain the repeater to cover future instances of the task.
8723 As described above, N+1 clones are produced when the original
8724 subtree has a repeater. Setting N to 0, then, can be used to
8725 remove the repeater from a subtree and create a shifted clone
8726 with the original repeater."
8727 (interactive "nNumber of clones to produce: ")
8728 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8729 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8730 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8731 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8734 (if (and (not (equal current-prefix-arg '(4)))
8737 (re-search-forward org-ts-regexp-both end-of-tree t)))
8738 (read-from-minibuffer
8739 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8740 ""))) ;No time shift
8742 (and (org-string-nw-p shift)
8743 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8745 (user-error "Invalid shift specification %s" shift)))))
8746 (goto-char end-of-tree)
8747 (unless (bolp) (insert "\n"))
8748 (let* ((end (point))
8749 (template (buffer-substring beg end))
8750 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8751 (shift-what (pcase (and doshift (match-string 2 shift))
8754 ("w" (setq shift-n (* 7 shift-n)) 'day)
8757 (_ (error "Unsupported time unit"))))
8761 (idprop (org-entry-get nil "ID")))
8763 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8765 (delete-region beg end)
8768 (setq nmax (1+ nmax))
8769 (setq n-no-remove nmax))
8771 (cl-loop for n from nmin to nmax do
8777 (goto-char (point-min))
8779 (and idprop (if org-clone-delete-id
8780 (org-entry-delete nil "ID")
8781 (org-id-get-create t)))
8783 (while (re-search-forward org-clock-line-re nil t)
8784 (delete-region (line-beginning-position)
8785 (line-beginning-position 2)))
8786 (goto-char (point-min))
8787 (while (re-search-forward org-drawer-regexp nil t)
8788 (org-remove-empty-drawer-at (point))))
8789 (goto-char (point-min))
8791 (while (re-search-forward org-ts-regexp-both nil t)
8792 (org-timestamp-change (* n shift-n) shift-what))
8793 (unless (= n n-no-remove)
8794 (goto-char (point-min))
8795 (while (re-search-forward org-ts-regexp nil t)
8797 (goto-char (match-beginning 0))
8798 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8799 (delete-region (match-beginning 1) (match-end 1)))))))
8805 (defun org-sort (&optional with-case)
8806 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8807 Optional argument WITH-CASE means sort case-sensitively."
8810 (cond ((org-at-table-p) #'org-table-sort-lines)
8811 ((org-at-item-p) #'org-sort-list)
8812 (t #'org-sort-entries))
8815 (defun org-sort-remove-invisible (s)
8816 "Remove invisible part of links and emphasis markers from string S."
8817 (remove-text-properties 0 (length s) org-rm-props s)
8818 (replace-regexp-in-string
8819 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8820 (replace-regexp-in-string
8821 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8822 (org-link-display-format s)
8825 (defvar org-priority-regexp) ; defined later in the file
8827 (defvar org-after-sorting-entries-or-items-hook nil
8828 "Hook that is run after a bunch of entries or items have been sorted.
8829 When children are sorted, the cursor is in the parent line when this
8830 hook gets called. When a region or a plain list is sorted, the cursor
8831 will be in the first entry of the sorted region/list.")
8833 (defun org-sort-entries
8834 (&optional with-case sorting-type getkey-func compare-func property
8836 "Sort entries on a certain level of an outline tree.
8837 If there is an active region, the entries in the region are sorted.
8838 Else, if the cursor is before the first entry, sort the top-level items.
8839 Else, the children of the entry at point are sorted.
8841 Sorting can be alphabetically, numerically, by date/time as given by
8842 a time stamp, by a property, by priority order, or by a custom function.
8844 The command prompts for the sorting type unless it has been given to the
8845 function through the SORTING-TYPE argument, which needs to be a character,
8846 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8847 the precise meaning of each character:
8849 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8850 c By creation time, which is assumed to be the first inactive time stamp
8851 at the beginning of a line.
8852 d By deadline date/time.
8854 n Numerically, by converting the beginning of the entry/item to a number.
8855 o By order of TODO keywords.
8856 p By priority according to the cookie.
8857 r By the value of a property.
8858 s By scheduled date/time.
8859 t By date/time, either the first active time stamp in the entry, or, if
8860 none exist, by the first inactive one.
8862 Capital letters will reverse the sort order.
8864 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8865 called with point at the beginning of the record. It must return a
8866 value that is compatible with COMPARE-FUNC, the function used to
8869 Comparing entries ignores case by default. However, with an optional argument
8870 WITH-CASE, the sorting considers case as well.
8872 Sorting is done against the visible part of the headlines, it ignores hidden
8875 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8877 A non-nil value for INTERACTIVE? is used to signal that this
8878 function is being called interactively."
8879 (interactive (list current-prefix-arg nil nil nil nil t))
8880 (let ((case-func (if with-case 'identity 'downcase))
8881 start beg end stars re re2
8883 ;; Find beginning and end of region to sort
8885 ((org-region-active-p)
8886 ;; we will sort the region
8887 (setq end (region-end)
8889 (goto-char (region-beginning))
8890 (unless (org-at-heading-p) (outline-next-heading))
8891 (setq start (point)))
8892 ((or (org-at-heading-p)
8893 (ignore-errors (progn (org-back-to-heading) t)))
8894 ;; we will sort the children of the current headline
8895 (org-back-to-heading)
8897 end (progn (org-end-of-subtree t t)
8898 (or (bolp) (insert "\n"))
8899 (when (>= (org-back-over-empty-lines) 1)
8904 (outline-show-subtree)
8905 (outline-next-heading))
8907 ;; we will sort the top-level entries in this file
8908 (goto-char (point-min))
8909 (or (org-at-heading-p) (outline-next-heading))
8910 (setq start (point))
8911 (goto-char (point-max))
8912 (beginning-of-line 1)
8913 (when (looking-at ".*?\\S-")
8914 ;; File ends in a non-white line
8917 (setq end (point-max))
8918 (setq what "top-level")
8920 (outline-show-all)))
8923 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8925 (looking-at "\\(\\*+\\)")
8926 (setq stars (match-string 1)
8927 re (concat "^" (regexp-quote stars) " +")
8928 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8929 txt (buffer-substring beg end))
8930 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8931 (when (and (not (equal stars "*")) (string-match re2 txt))
8932 (user-error "Region to sort contains a level above the first entry"))
8934 (unless sorting-type
8936 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8937 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
8938 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8940 (setq sorting-type (read-char-exclusive)))
8943 (and (= (downcase sorting-type) ?f)
8945 (or (and interactive?
8947 "Function for extracting keys: "))
8948 (error "Missing key extractor")))))
8950 (and (= (downcase sorting-type) ?r)
8953 (completing-read "Property: "
8954 (mapcar #'list (org-buffer-property-keys t))
8957 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8958 (message "Sorting entries...")
8961 (narrow-to-region start end)
8962 (let ((restore-clock?
8963 ;; The clock marker is lost when using `sort-subr'; mark
8964 ;; the clock with temporary `:org-clock-marker-backup'
8966 (when (and (eq (org-clock-is-active) (current-buffer))
8967 (<= start (marker-position org-clock-marker))
8968 (>= end (marker-position org-clock-marker)))
8969 (org-with-silent-modifications
8970 (put-text-property (1- org-clock-marker) org-clock-marker
8971 :org-clock-marker-backup t))
8973 (dcst (downcase sorting-type))
8974 (case-fold-search nil)
8975 (now (current-time)))
8977 (/= dcst sorting-type)
8978 ;; This function moves to the beginning character of the "record" to
8981 (if (re-search-forward re nil t)
8982 (goto-char (match-beginning 0))
8983 (goto-char (point-max))))
8984 ;; This function moves to the last character of the "record" being
8989 (outline-forward-same-level 1)
8991 (goto-char (point-max))))))
8992 ;; This function returns the value that gets sorted against.
8996 (if (looking-at org-complex-heading-regexp)
8997 (string-to-number (org-sort-remove-invisible (match-string 4)))
9000 (if (looking-at org-complex-heading-regexp)
9001 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9004 (or (get-text-property (point) :org-clock-minutes) 0))
9006 (let ((end (save-excursion (outline-next-heading) (point))))
9007 (if (or (re-search-forward org-ts-regexp end t)
9008 (re-search-forward org-ts-regexp-both end t))
9009 (org-time-string-to-seconds (match-string 0))
9012 (let ((end (save-excursion (outline-next-heading) (point))))
9013 (if (re-search-forward
9014 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9016 (org-time-string-to-seconds (match-string 0))
9019 (let ((end (save-excursion (outline-next-heading) (point))))
9020 (if (re-search-forward org-scheduled-time-regexp end t)
9021 (org-time-string-to-seconds (match-string 1))
9024 (let ((end (save-excursion (outline-next-heading) (point))))
9025 (if (re-search-forward org-deadline-time-regexp end t)
9026 (org-time-string-to-seconds (match-string 1))
9029 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9030 (string-to-char (match-string 2))
9031 org-default-priority))
9033 (or (org-entry-get nil property) ""))
9035 (when (looking-at org-complex-heading-regexp)
9036 (let* ((m (match-string 2))
9037 (s (if (member m org-done-keywords) '- '+)))
9038 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9042 (setq tmp (funcall getkey-func))
9043 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9045 (error "Invalid key function `%s'" getkey-func)))
9046 (t (error "Invalid sorting type `%c'" sorting-type))))
9049 ((= dcst ?a) 'string<)
9054 (concat "Function for comparing keys "
9055 "(empty for default `sort-subr' predicate): ")
9057 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9058 (when restore-clock?
9059 (move-marker org-clock-marker
9060 (1+ (next-single-property-change
9061 start :org-clock-marker-backup)))
9062 (remove-text-properties (1- org-clock-marker) org-clock-marker
9063 '(:org-clock-marker-backup t)))))
9064 (run-hooks 'org-after-sorting-entries-or-items-hook)
9065 (message "Sorting entries...done")))
9067 ;;; The orgstruct minor mode
9069 ;; Define a minor mode which can be used in other modes in order to
9070 ;; integrate the Org mode structure editing commands.
9072 ;; This is really a hack, because the Org mode structure commands use
9073 ;; keys which normally belong to the major mode. Here is how it
9074 ;; works: The minor mode defines all the keys necessary to operate the
9075 ;; structure commands, but wraps the commands into a function which
9076 ;; tests if the cursor is currently at a headline or a plain list
9077 ;; item. If that is the case, the structure command is used,
9078 ;; temporarily setting many Org mode variables like regular
9079 ;; expressions for filling etc. However, when any of those keys is
9080 ;; used at a different location, function uses `key-binding' to look
9081 ;; up if the key has an associated command in another currently active
9082 ;; keymap (minor modes, major mode, global), and executes that
9083 ;; command. There might be problems if any of the keys is otherwise
9084 ;; used as a prefix key.
9086 (defcustom orgstruct-heading-prefix-regexp ""
9087 "Regexp that matches the custom prefix of Org headlines in
9088 orgstruct(++)-mode."
9091 :package-version '(Org . "8.3")
9093 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9095 (defcustom orgstruct-setup-hook nil
9096 "Hook run after orgstruct-mode-map is filled."
9099 :package-version '(Org . "8.0")
9102 (defvar orgstruct-initialized nil)
9104 (defvar org-local-vars nil
9105 "List of local variables, for use by `orgstruct-mode'.")
9108 (define-minor-mode orgstruct-mode
9109 "Toggle the minor mode `orgstruct-mode'.
9110 This mode is for using Org mode structure commands in other
9111 modes. The following keys behave as if Org mode were active, if
9112 the cursor is on a headline, or on a plain list item (both as
9113 defined by Org mode)."
9114 nil " OrgStruct" (make-sparse-keymap)
9115 (funcall (if orgstruct-mode
9116 'add-to-invisibility-spec
9117 'remove-from-invisibility-spec)
9119 (when orgstruct-mode
9120 (org-load-modules-maybe)
9121 (unless orgstruct-initialized
9123 (setq orgstruct-initialized t))))
9126 (defun turn-on-orgstruct ()
9127 "Unconditionally turn on `orgstruct-mode'."
9130 (defvar-local orgstruct-is-++ nil
9131 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9132 (defvar-local org-fb-vars nil)
9133 (defun orgstruct++-mode (&optional arg)
9134 "Toggle `orgstruct-mode', the enhanced version of it.
9135 In addition to setting orgstruct-mode, this also exports all
9136 indentation and autofilling variables from Org mode into the
9137 buffer. It will also recognize item context in multiline items."
9139 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9141 (progn (orgstruct-mode -1)
9142 (dolist (v org-fb-vars)
9143 (set (make-local-variable (car v))
9144 (if (eq (car-safe (cadr v)) 'quote)
9148 (setq org-fb-vars nil)
9149 (unless org-local-vars
9150 (setq org-local-vars (org-get-local-variables)))
9152 (dolist (x org-local-vars)
9154 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9155 \\|fill-prefix\\|indent-\\)"
9156 (symbol-name (car x)))
9157 (setq var (car x) val (nth 1 x))
9158 (push (list var `(quote ,(eval var))) org-fb-vars)
9159 (set (make-local-variable var)
9160 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9161 (setq-local orgstruct-is-++ t))))
9164 (defun turn-on-orgstruct++ ()
9165 "Unconditionally turn on `orgstruct++-mode'."
9166 (orgstruct++-mode 1))
9168 (defun orgstruct-error ()
9169 "Error when there is no default binding for a structure key."
9171 (funcall (if (fboundp 'user-error)
9174 "This key has no function outside structure elements"))
9176 (defun orgstruct-setup ()
9177 "Setup orgstruct keymap."
9178 (dolist (cell '((org-demote . t)
9182 (org-shiftmetaleft . t)
9183 (org-shiftmetaright . t)
9184 org-backward-element
9185 org-backward-heading-same-level
9190 org-force-cycle-archived
9191 org-forward-heading-same-level
9193 org-insert-heading-respect-content
9194 org-kill-note-or-show-branches
9199 org-narrow-to-subtree
9215 outline-next-visible-heading
9216 outline-previous-visible-heading
9218 outline-up-heading))
9219 (let ((f (or (car-safe cell) cell))
9220 (disable-when-heading-prefix (cdr-safe cell)))
9222 (let ((new-bindings))
9223 (dolist (binding (nconc (where-is-internal f org-mode-map)
9224 (where-is-internal f outline-mode-map)))
9225 (push binding new-bindings)
9226 ;; TODO use local-function-key-map
9227 (dolist (rep '(("<tab>" . "TAB")
9228 ("<return>" . "RET")
9229 ("<escape>" . "ESC")
9230 ("<delete>" . "DEL")))
9231 (setq binding (read-kbd-macro
9232 (let ((case-fold-search))
9233 (replace-regexp-in-string
9234 (regexp-quote (cdr rep))
9236 (key-description binding)))))
9237 (cl-pushnew binding new-bindings :test 'equal)))
9238 (dolist (binding new-bindings)
9239 (let ((key (lookup-key orgstruct-mode-map binding)))
9240 (when (or (not key) (numberp key))
9242 (org-defkey orgstruct-mode-map
9244 (orgstruct-make-binding
9245 f binding disable-when-heading-prefix))))))))))
9246 (run-hooks 'orgstruct-setup-hook))
9248 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9249 "Create a function for binding in the structure minor mode.
9250 FUN is the command to call inside a table. KEY is the key that
9251 should be checked in for a command to execute outside of tables.
9252 Non-nil `disable-when-heading-prefix' means to disable the command
9253 if `orgstruct-heading-prefix-regexp' is not empty."
9254 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9257 (while (fboundp (intern nname))
9258 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9259 (setq name (intern nname)))
9261 (let ((bindings '((org-heading-regexp
9263 orgstruct-heading-prefix-regexp
9264 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9266 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9267 (org-outline-regexp-bol
9268 (concat "^" org-outline-regexp))
9269 (outline-regexp org-outline-regexp)
9270 (outline-heading-end-regexp "\n")
9271 (outline-level 'org-outline-level)
9272 (outline-heading-alist))))
9274 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9275 "Outside of structure, run the binding of `"
9276 (key-description key) "'."
9277 (when disable-when-heading-prefix
9279 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9280 "back to the default binding due to limitations of Org's implementation of\n"
9281 "`" (symbol-name fun) "'.")))
9284 ,(and disable-when-heading-prefix
9285 '(not (string= orgstruct-heading-prefix-regexp ""))))
9290 (org-context-p 'headline 'item
9292 '(org-insert-heading
9293 org-insert-heading-respect-content
9295 '(when orgstruct-is-++
9298 (let* ((orgstruct-mode)
9305 ("<\\([^>]*\\)tab>" . "\\1TAB")
9306 ("<\\([^>]*\\)return>" . "\\1RET")
9307 ("<\\([^>]*\\)escape>" . "\\1ESC")
9308 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9311 (setq key (read-kbd-macro
9312 (let ((case-fold-search))
9313 (replace-regexp-in-string
9316 (key-description key))))))
9317 (when (key-binding key)
9318 (throw 'exit (key-binding key))))))))
9319 (if (keymapp binding)
9320 (org-set-transient-map binding)
9321 (let ((func (or binding
9323 'orgstruct-error))))
9325 (call-interactively func)))))
9326 (org-run-like-in-org-mode
9330 (call-interactively ',fun)))))))))
9333 (defun org-contextualize-keys (alist contexts)
9334 "Return valid elements in ALIST depending on CONTEXTS.
9336 `org-agenda-custom-commands' or `org-capture-templates' are the
9337 values used for ALIST, and `org-agenda-custom-commands-contexts'
9338 or `org-capture-templates-contexts' are the associated contexts
9341 ;; normalize contexts
9343 (lambda(c) (cond ((listp (cadr c))
9344 (list (car c) (car c) (nth 1 c)))
9345 ((string= "" (cadr c))
9346 (list (car c) (car c) (nth 2 c)))
9350 ;; loop over all commands or templates
9354 ((not (assoc (car c) contexts))
9356 ((and (assoc (car c) contexts)
9357 (setq vrules (org-contextualize-validate-key
9360 (unless (equal (car vr) (cadr vr))
9363 (if (not repl) (push c r)
9364 (push (cadr repl) s)
9367 (cdr (or (assoc (cadr repl) alist)
9368 (error "Undefined key `%s' as contextual replacement for `%s'"
9369 (cadr repl) (car c)))))
9371 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9376 (let ((tpl (car x)))
9385 (defun org-contextualize-validate-key (key contexts)
9386 "Check CONTEXTS for agenda or capture KEY."
9388 (dolist (r contexts)
9389 (dolist (rr (car (last r)))
9391 (and (equal key (car r))
9392 (if (functionp rr) (funcall rr)
9393 (or (and (eq (car rr) 'in-file)
9395 (string-match (cdr rr) (buffer-file-name)))
9396 (and (eq (car rr) 'in-mode)
9397 (string-match (cdr rr) (symbol-name major-mode)))
9398 (and (eq (car rr) 'in-buffer)
9399 (string-match (cdr rr) (buffer-name)))
9400 (when (and (eq (car rr) 'not-in-file)
9402 (not (string-match (cdr rr) (buffer-file-name))))
9403 (when (eq (car rr) 'not-in-mode)
9404 (not (string-match (cdr rr) (symbol-name major-mode))))
9405 (when (eq (car rr) 'not-in-buffer)
9406 (not (string-match (cdr rr) (buffer-name)))))))
9408 (delete-dups (delq nil res))))
9410 (defun org-context-p (&rest contexts)
9411 "Check if local context is any of CONTEXTS.
9412 Possible values in the list of contexts are `table', `headline', and `item'."
9413 (let ((pos (point)))
9414 (goto-char (point-at-bol))
9415 (prog1 (or (and (memq 'table contexts)
9416 (looking-at "[ \t]*|"))
9417 (and (memq 'headline contexts)
9418 (looking-at org-outline-regexp))
9419 (and (memq 'item contexts)
9420 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9421 (and (memq 'item-body contexts)
9426 (defun org-run-like-in-org-mode (cmd)
9427 "Run a command, pretending that the current buffer is in Org mode.
9428 This will temporarily bind local variables that are typically bound in
9429 Org mode to the values they have in Org mode, and then interactively
9431 (org-load-modules-maybe)
9432 (unless org-local-vars
9433 (setq org-local-vars (org-get-local-variables)))
9435 (dolist (var org-local-vars)
9436 (when (or (not (boundp (car var)))
9437 (eq (symbol-value (car var))
9438 (default-value (car var))))
9439 (push (list (car var) `(quote ,(cadr var))) binds)))
9441 (call-interactively (quote ,cmd))))))
9443 (defun org-get-category (&optional pos force-refresh)
9444 "Get the category applying to position POS."
9446 (when force-refresh (org-refresh-category-properties))
9447 (let ((pos (or pos (point))))
9448 (or (get-text-property pos 'org-category)
9449 (progn (org-refresh-category-properties)
9450 (get-text-property pos 'org-category))))))
9452 ;;; Refresh properties
9454 (defun org-refresh-properties (dprop tprop)
9455 "Refresh buffer text properties.
9456 DPROP is the drawer property and TPROP is either the
9457 corresponding text property to set, or an alist with each element
9458 being a text property (as a symbol) and a function to apply to
9459 the value of the drawer property."
9460 (let* ((case-fold-search t)
9461 (inhibit-read-only t)
9462 (inherit? (org-property-inherit-p dprop))
9463 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9464 (global (and inherit? (org--property-global-value dprop nil))))
9465 (org-with-silent-modifications
9466 (org-with-point-at 1
9467 ;; Set global values (e.g., values defined through
9468 ;; "#+PROPERTY:" keywords) to the whole buffer.
9469 (when global (put-text-property (point-min) (point-max) tprop global))
9470 ;; Set local values.
9471 (while (re-search-forward property-re nil t)
9472 (when (org-at-property-p)
9473 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9474 (outline-next-heading))))))
9476 (defun org-refresh-property (tprop p &optional inherit)
9477 "Refresh the buffer text property TPROP from the drawer property P.
9478 The refresh happens only for the current headline, or the whole
9479 sub-tree if optional argument INHERIT is non-nil."
9480 (unless (org-before-first-heading-p)
9482 (org-back-to-heading t)
9483 (let ((start (point))
9484 (end (save-excursion
9485 (if inherit (org-end-of-subtree t t)
9486 (or (outline-next-heading) (point-max))))))
9488 ;; TPROP is a text property symbol.
9489 (put-text-property start end tprop p)
9490 ;; TPROP is an alist with (property . function) elements.
9491 (pcase-dolist (`(,prop . ,f) tprop)
9492 (put-text-property start end prop (funcall f p))))))))
9494 (defun org-refresh-category-properties ()
9495 "Refresh category text properties in the buffer."
9496 (let ((case-fold-search t)
9497 (inhibit-read-only t)
9499 (cond ((null org-category)
9500 (if buffer-file-name
9501 (file-name-sans-extension
9502 (file-name-nondirectory buffer-file-name))
9504 ((symbolp org-category) (symbol-name org-category))
9506 (org-with-silent-modifications
9507 (org-with-wide-buffer
9508 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9509 ;; This is the default category for the buffer. If none is
9510 ;; found, fall-back to `org-category' or buffer file name.
9512 (point-min) (point-max)
9514 (catch 'buffer-category
9515 (goto-char (point-max))
9516 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9517 (let ((element (org-element-at-point)))
9518 (when (eq (org-element-type element) 'keyword)
9519 (throw 'buffer-category
9520 (org-element-property :value element)))))
9522 ;; Set sub-tree specific categories.
9523 (goto-char (point-min))
9524 (let ((regexp (org-re-property "CATEGORY")))
9525 (while (re-search-forward regexp nil t)
9526 (let ((value (match-string-no-properties 3)))
9527 (when (org-at-property-p)
9529 (save-excursion (org-back-to-heading t) (point))
9530 (save-excursion (org-end-of-subtree t t) (point))
9534 (defun org-refresh-stats-properties ()
9535 "Refresh stats text properties in the buffer."
9536 (org-with-silent-modifications
9537 (org-with-point-at 1
9538 (let ((regexp (concat org-outline-regexp-bol
9539 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9540 (while (re-search-forward regexp nil t)
9541 (let* ((numerator (string-to-number (match-string 1)))
9542 (denominator (and (match-end 2)
9543 (string-to-number (match-string 2))))
9544 (stats (cond ((not denominator) numerator) ;percent
9545 ((= denominator 0) 0)
9546 (t (/ (* numerator 100) denominator)))))
9547 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9548 'org-stats stats)))))))
9550 (defun org-refresh-effort-properties ()
9551 "Refresh effort properties"
9552 (org-refresh-properties
9554 '((effort . identity)
9555 (effort-minutes . org-duration-to-minutes))))
9559 ;;; Link abbreviations
9561 (defun org-link-expand-abbrev (link)
9562 "Apply replacements as defined in `org-link-abbrev-alist'."
9563 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9564 (let* ((key (match-string 1 link))
9565 (as (or (assoc key org-link-abbrev-alist-local)
9566 (assoc key org-link-abbrev-alist)))
9567 (tag (and (match-end 2) (match-string 3 link)))
9573 ((symbolp rpl) (funcall rpl tag))
9574 ((string-match "%(\\([^)]+\\))" rpl)
9577 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9578 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9579 ((string-match "%h" rpl)
9580 (replace-match (url-hexify-string (or tag "")) t t rpl))
9581 (t (concat rpl tag)))))
9584 ;;; Storing and inserting links
9586 (defvar org-insert-link-history nil
9587 "Minibuffer history for links inserted with `org-insert-link'.")
9589 (defvar org-stored-links nil
9590 "Contains the links stored with `org-store-link'.")
9592 (defvar org-store-link-plist nil
9593 "Plist with info about the most recently link created with `org-store-link'.")
9595 (defun org-store-link-functions ()
9596 "Return a list of functions that are called to create and store a link.
9597 The functions defined in the :store property of
9598 `org-link-parameters'.
9600 Each function will be called in turn until one returns a non-nil
9601 value. Each function should check if it is responsible for
9602 creating this link (for example by looking at the major mode).
9603 If not, it must exit and return nil. If yes, it should return
9604 a non-nil value after calling `org-store-link-props' with a list
9605 of properties and values. Special properties are:
9607 :type The link prefix, like \"http\". This must be given.
9608 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9609 This is obligatory as well.
9610 :description Optional default description for the second pair
9611 of brackets in an Org mode link. The user can still change
9612 this when inserting this link into an Org mode buffer.
9614 In addition to these, any additional properties can be specified
9615 and then used in capture templates."
9616 (cl-loop for link in org-link-parameters
9618 do (setq store-func (org-link-get-parameter (car link) :store))
9620 collect store-func))
9622 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9623 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9626 (defun org-store-link (arg)
9627 "Store an org-link to the current location.
9629 This link is added to `org-stored-links' and can later be inserted
9630 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9632 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9634 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9635 `org-gnus-prefer-web-links' for links to Usenet articles.
9637 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9638 skipping storing functions that are not
9641 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9642 prefix ARG forces storing a link for each line in the
9645 (org-load-modules-maybe)
9646 (if (and (equal arg '(64)) (org-region-active-p))
9648 (let ((end (region-end)))
9649 (goto-char (region-beginning))
9651 (while (< (point-at-eol) end)
9652 (move-end-of-line 1) (activate-mark)
9653 (let (current-prefix-arg)
9654 (call-interactively 'org-store-link))
9655 (move-beginning-of-line 2)
9656 (set-mark (point)))))
9657 (setq org-store-link-plist nil)
9658 (let (link cpltxt desc description search txt custom-id agenda-link)
9660 ;; Store a link using an external link type, if any function is
9661 ;; available. If more than one can generate a link from current
9662 ;; location, ask which one to use.
9663 ((and (not (equal arg '(16)))
9664 (let ((results-alist nil))
9665 (dolist (f (org-store-link-functions))
9667 ;; XXX: return value is not link's plist, so we
9668 ;; store the new value before it is modified. It
9669 ;; would be cleaner to ask store link functions to
9670 ;; return the plist instead.
9671 (push (cons f (copy-sequence org-store-link-plist))
9673 (pcase results-alist
9675 (`((,_ . ,_)) t) ;single choice: nothing to do
9676 (`((,name . ,_) . ,_)
9677 ;; Reinstate link plist associated to the chosen
9679 (apply #'org-store-link-props
9682 "Which function for creating the link? "
9683 (mapcar #'car results-alist) nil t name)
9686 (setq link (plist-get org-store-link-plist :link))
9687 (setq desc (or (plist-get org-store-link-plist :description)
9690 ;; Store a link from a source code buffer.
9691 ((org-src-edit-buffer-p)
9692 (let ((coderef-format (org-src-coderef-format)))
9693 (cond ((save-excursion
9695 (looking-at (org-src-coderef-regexp coderef-format)))
9696 (setq link (format "(%s)" (match-string-no-properties 3))))
9697 ((called-interactively-p 'any)
9698 (let ((label (read-string "Code line label: ")))
9700 (setq link (format coderef-format label))
9701 (let ((gc (- 79 (length link))))
9702 (if (< (current-column) gc)
9703 (org-move-to-column gc t)
9706 (setq link (concat "(" label ")"))
9708 (t (setq link nil)))))
9710 ;; We are in the agenda, link to referenced location
9711 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9712 (let ((m (or (get-text-property (point) 'org-hd-marker)
9713 (get-text-property (point) 'org-marker))))
9715 (org-with-point-at m
9717 (if (called-interactively-p 'any)
9718 (call-interactively 'org-store-link)
9719 (org-store-link nil)))))))
9721 ((eq major-mode 'calendar-mode)
9722 (let ((cd (calendar-cursor-to-date)))
9725 (car org-time-stamp-formats)
9727 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9729 (org-store-link-props :type "calendar" :date cd)))
9731 ((eq major-mode 'help-mode)
9732 (setq link (concat "help:" (save-excursion
9733 (goto-char (point-min))
9734 (looking-at "^[^ ]+")
9736 (org-store-link-props :type "help"))
9738 ((eq major-mode 'w3-mode)
9739 (setq cpltxt (if (and (buffer-name)
9740 (not (string-match "Untitled" (buffer-name))))
9743 link (url-view-url t))
9744 (org-store-link-props :type "w3" :url (url-view-url t)))
9746 ((eq major-mode 'image-mode)
9747 (setq cpltxt (concat "file:"
9748 (abbreviate-file-name buffer-file-name))
9750 (org-store-link-props :type "image" :file buffer-file-name))
9752 ;; In dired, store a link to the file of the current line
9753 ((derived-mode-p 'dired-mode)
9754 (let ((file (dired-get-filename nil t)))
9756 (abbreviate-file-name
9757 (expand-file-name (dired-get-filename nil t)))
9758 ;; otherwise, no file so use current directory.
9760 (setq cpltxt (concat "file:" file)
9763 ((setq search (run-hook-with-args-until-success
9764 'org-create-file-search-functions))
9765 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9767 (setq cpltxt (or description link)))
9769 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9770 (org-with-limited-levels
9771 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9773 ;; Store a link using the target at point
9774 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9777 (abbreviate-file-name
9778 (buffer-file-name (buffer-base-buffer)))
9779 "::" (match-string 1))
9781 ((and (featurep 'org-id)
9782 (or (eq org-id-link-to-org-use-id t)
9783 (and (called-interactively-p 'any)
9784 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9785 (and (eq org-id-link-to-org-use-id
9786 'create-if-interactive-and-no-custom-id)
9788 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9789 ;; Store a link using the ID at point
9790 (setq link (condition-case nil
9791 (prog1 (org-id-store-link)
9792 (setq desc (or (plist-get org-store-link-plist
9796 ;; Probably before first headline, link only to file
9798 (abbreviate-file-name
9799 (buffer-file-name (buffer-base-buffer))))))))
9801 ;; Just link to current headline
9802 (setq cpltxt (concat "file:"
9803 (abbreviate-file-name
9804 (buffer-file-name (buffer-base-buffer)))))
9805 ;; Add a context search string
9806 (when (org-xor org-context-in-file-links
9808 (let* ((element (org-element-at-point))
9809 (name (org-element-property :name element)))
9811 ((org-at-heading-p) nil)
9813 ((org-region-active-p)
9814 (buffer-substring (region-beginning) (region-end)))))
9815 (when (or (null txt) (string-match "\\S-" txt))
9819 (org-make-org-heading-search-string txt)
9822 (nth 4 (ignore-errors (org-heading-components)))
9824 (when (string-match "::\\'" cpltxt)
9825 (setq cpltxt (substring cpltxt 0 -2)))
9826 (setq link cpltxt)))))
9828 ((buffer-file-name (buffer-base-buffer))
9829 ;; Just link to this file here.
9830 (setq cpltxt (concat "file:"
9831 (abbreviate-file-name
9832 (buffer-file-name (buffer-base-buffer)))))
9833 ;; Add a context string.
9834 (when (org-xor org-context-in-file-links
9836 (setq txt (if (org-region-active-p)
9837 (buffer-substring (region-beginning) (region-end))
9838 (buffer-substring (point-at-bol) (point-at-eol))))
9839 ;; Only use search option if there is some text.
9840 (when (string-match "\\S-" txt)
9842 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9846 ((called-interactively-p 'interactive)
9847 (user-error "No method for storing a link from this buffer"))
9849 (t (setq link nil)))
9851 ;; We're done setting link and desc, clean up
9852 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9853 (setq link (or link cpltxt)
9854 desc (or desc cpltxt))
9856 ((equal desc "NONE") (setq desc nil))
9858 (replace-regexp-in-string
9859 org-bracket-link-analytic-regexp
9860 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9863 (if (not (and (or (called-interactively-p 'any)
9864 executing-kbd-macro)
9866 (or agenda-link (and link (org-make-link-string link desc)))
9867 (push (list link desc) org-stored-links)
9868 (message "Stored: %s" (or desc link))
9870 (setq link (concat "file:" (abbreviate-file-name
9871 (buffer-file-name)) "::#" custom-id))
9872 (push (list link desc) org-stored-links))
9873 (car org-stored-links)))))
9875 (defun org-store-link-props (&rest plist)
9876 "Store link properties.
9877 The properties are pre-processed by extracting names, addresses
9879 (let ((x (plist-get plist :from)))
9881 (let ((adr (mail-extract-address-components x)))
9882 (setq plist (plist-put plist :fromname (car adr)))
9883 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9884 (let ((x (plist-get plist :to)))
9886 (let ((adr (mail-extract-address-components x)))
9887 (setq plist (plist-put plist :toname (car adr)))
9888 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9889 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9891 (setq plist (plist-put plist :date-timestamp
9893 (org-time-stamp-format t) x)))
9894 (setq plist (plist-put plist :date-timestamp-inactive
9896 (org-time-stamp-format t t) x)))))
9897 (let ((from (plist-get plist :from))
9898 (to (plist-get plist :to)))
9899 (when (and from to org-from-is-user-regexp)
9901 (plist-put plist :fromto
9902 (if (string-match org-from-is-user-regexp from)
9904 (concat "from %f"))))))
9905 (setq org-store-link-plist plist))
9907 (defun org-add-link-props (&rest plist)
9908 "Add these properties to the link property list."
9911 (setq key (pop plist) value (pop plist))
9912 (setq org-store-link-plist
9913 (plist-put org-store-link-plist key value)))))
9915 (defun org-email-link-description (&optional fmt)
9916 "Return the description part of an email link.
9917 This takes information from `org-store-link-plist' and formats it
9918 according to FMT (default from `org-email-link-description-format')."
9919 (setq fmt (or fmt org-email-link-description-format))
9920 (let* ((p org-store-link-plist)
9921 (to (plist-get p :toaddress))
9922 (from (plist-get p :fromaddress))
9925 (cons "%c" (plist-get p :fromto))
9926 (cons "%F" (plist-get p :from))
9927 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9928 (cons "%T" (plist-get p :to))
9929 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9930 (cons "%s" (plist-get p :subject))
9931 (cons "%d" (plist-get p :date))
9932 (cons "%m" (plist-get p :message-id)))))
9933 (when (string-match "%c" fmt)
9934 ;; Check if the user wrote this message
9935 (if (and org-from-is-user-regexp from to
9936 (save-match-data (string-match org-from-is-user-regexp from)))
9937 (setq fmt (replace-match "to %t" t t fmt))
9938 (setq fmt (replace-match "from %f" t t fmt))))
9939 (org-replace-escapes fmt table)))
9941 (defun org-make-org-heading-search-string (&optional string)
9942 "Make search string for the current headline or STRING."
9944 (and (derived-mode-p 'org-mode)
9946 (org-back-to-heading t)
9947 (org-element-property :raw-value (org-element-at-point))))))
9948 (lines org-context-in-file-links))
9949 (unless string (setq s (concat "*" s))) ;Add * for headlines
9950 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9951 (when (and string (integerp lines) (> lines 0))
9952 (let ((slines (org-split-string s "\n")))
9953 (when (< lines (length slines))
9956 (reverse (nthcdr (- (length slines) lines)
9957 (reverse slines))) "\n")))))
9958 (mapconcat #'identity (split-string s) " ")))
9960 (defconst org-link-escape-chars
9963 "List of characters that should be escaped in a link when stored to Org.
9964 This is the list that is used for internal purposes.")
9966 (defun org-make-link-string (link &optional description)
9967 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9968 (unless (org-string-nw-p link) (error "Empty link"))
9969 (let ((uri (cond ((string-match org-link-types-re link)
9970 (concat (match-string 1 link)
9971 (org-link-escape (substring link (match-end 1)))))
9972 ((or (file-name-absolute-p link)
9973 (string-match-p "\\`\\.\\.?/" link))
9974 (org-link-escape link))
9975 ;; For readability, do not encode space characters
9977 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9979 (and (org-string-nw-p description)
9980 ;; Remove brackets from description, as they are fatal.
9981 (replace-regexp-in-string
9982 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9983 (org-trim description)))))
9986 (if description (format "[%s]" description) ""))))
9988 (defun org-link-escape (text &optional table merge)
9989 "Return percent escaped representation of TEXT.
9990 TEXT is a string with the text to escape.
9991 Optional argument TABLE is a list with characters that should be
9992 escaped. When nil, `org-link-escape-chars' is used.
9993 If optional argument MERGE is set, merge TABLE into
9994 `org-link-escape-chars'."
9995 (let ((characters-to-encode
9996 (cond ((null table) org-link-escape-chars)
9997 (merge (append org-link-escape-chars table))
10001 (if (or (memq c characters-to-encode)
10002 (and org-url-hexify-p (or (< c 32) (> c 126))))
10003 (mapconcat (lambda (e) (format "%%%.2X" e))
10004 (or (encode-coding-char c 'utf-8)
10005 (error "Unable to percent escape character: %c" c))
10007 (char-to-string c)))
10010 (defun org-link-unescape (str)
10011 "Unhex hexified Unicode parts in string STR.
10012 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10013 reciprocal of `org-link-escape', which see."
10014 (if (org-string-nw-p str)
10015 (replace-regexp-in-string
10016 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10019 (defun org-link-unescape-compound (hex)
10020 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10021 Note: this function also decodes single byte encodings like
10022 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10024 (let* ((bytes (cdr (split-string hex "%")))
10029 (let* ((val (string-to-number (pop bytes) 16))
10033 ((>= val 252) (cons 6 252))
10034 ((>= val 248) (cons 5 248))
10035 ((>= val 240) (cons 4 240))
10036 ((>= val 224) (cons 3 224))
10037 ((>= val 192) (cons 2 192))
10040 (when (>= val 192) (setq eat (car shift-xor)))
10041 (setq val (logxor val (cdr shift-xor)))
10042 (setq sum (+ (lsh sum (car shift-xor)) val))
10043 (when (> eat 0) (setq eat (- eat 1)))
10045 ((= 0 eat) ;multi byte
10046 (setq ret (concat ret (char-to-string sum)))
10048 ((not bytes) ; single byte(s)
10049 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10052 (defun org-link-unescape-single-byte-sequence (hex)
10053 "Unhexify hex-encoded single byte character sequences."
10054 (mapconcat (lambda (byte)
10055 (char-to-string (string-to-number byte 16)))
10056 (cdr (split-string hex "%")) ""))
10058 (defun org-xor (a b)
10062 (defun org-fixup-message-id-for-http (s)
10063 "Replace special characters in a message id, so it can be used in an http query."
10064 (when (string-match "%" s)
10065 (setq s (mapconcat (lambda (c)
10068 (char-to-string c)))
10070 (while (string-match "<" s)
10071 (setq s (replace-match "%3C" t t s)))
10072 (while (string-match ">" s)
10073 (setq s (replace-match "%3E" t t s)))
10074 (while (string-match "@" s)
10075 (setq s (replace-match "%40" t t s)))
10078 (defun org-link-prettify (link)
10079 "Return a human-readable representation of LINK.
10080 The car of LINK must be a raw link.
10081 The cdr of LINK must be either a link description or nil."
10082 (let ((desc (or (cadr link) "<no description>")))
10083 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10084 "<" (car link) ">")))
10087 (defun org-insert-link-global ()
10088 "Insert a link like Org mode does.
10089 This command can be called in any mode to insert a link in Org syntax."
10091 (org-load-modules-maybe)
10092 (org-run-like-in-org-mode 'org-insert-link))
10094 (defun org-insert-all-links (arg &optional pre post)
10095 "Insert all links in `org-stored-links'.
10096 When a universal prefix, do not delete the links from `org-stored-links'.
10097 When `ARG' is a number, insert the last N link(s).
10098 `PRE' and `POST' are optional arguments to define a string to
10099 prepend or to append."
10101 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10102 (links (copy-sequence org-stored-links))
10104 (po (or post "\n"))
10106 (if (null org-stored-links)
10107 (message "No link to insert")
10108 (while (and (or (listp arg) (>= arg cnt))
10109 (setq l (if (listp arg)
10111 (pop org-stored-links))))
10112 (setq cnt (1+ cnt))
10114 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10117 (defun org-insert-last-stored-link (arg)
10118 "Insert the last link stored in `org-stored-links'."
10120 (org-insert-all-links arg "" "\n"))
10122 (defun org-link-fontify-links-to-this-file ()
10123 "Fontify links to the current file in `org-stored-links'."
10124 (let ((f (buffer-file-name)) a b)
10125 (setq a (mapcar (lambda(l)
10126 (let ((ll (car l)))
10127 (when (and (string-match "^file:\\(.+\\)::" ll)
10128 (equal f (expand-file-name (match-string 1 ll))))
10131 (when (featurep 'org-id)
10132 (setq b (mapcar (lambda(l)
10133 (let ((ll (car l)))
10134 (when (and (string-match "^id:\\(.+\\)$" ll)
10135 (equal f (expand-file-name
10136 (or (org-id-find-id-file
10137 (match-string 1 ll)) ""))))
10139 org-stored-links)))
10141 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10142 (delq nil (append a b)))))
10144 (defvar org--links-history nil)
10145 (defun org-insert-link (&optional complete-file link-location default-description)
10146 "Insert a link. At the prompt, enter the link.
10148 Completion can be used to insert any of the link protocol prefixes in use.
10150 The history can be used to select a link previously stored with
10151 `org-store-link'. When the empty string is entered (i.e. if you just
10152 press `RET' at the prompt), the link defaults to the most recently
10153 stored link. As `SPC' triggers completion in the minibuffer, you need to
10154 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10156 You will also be prompted for a description, and if one is given, it will
10157 be displayed in the buffer instead of the link.
10159 If there is already a link at point, this command will allow you to edit
10160 link and description parts.
10162 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10164 selected using completion. The path to the file will be relative to the
10165 current directory if the file is in the current directory or a subdirectory.
10166 Otherwise, the link will be the absolute path as completed in the minibuffer
10167 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10168 option `org-link-file-path-type'.
10170 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10171 absolute path even if the file is in
10172 the current directory or below.
10174 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10175 prefix negates `org-keep-stored-link-after-insertion'.
10177 If the LINK-LOCATION parameter is non-nil, this value will be used as
10178 the link location instead of reading one interactively.
10180 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10181 be used as the default description. Otherwise, if
10182 `org-make-link-description-function' is non-nil, this function
10183 will be called with the link target, and the result will be the
10184 default link description."
10186 (let* ((wcf (current-window-configuration))
10187 (origbuf (current-buffer))
10188 (region (when (org-region-active-p)
10189 (buffer-substring (region-beginning) (region-end))))
10190 (remove (and region (list (region-beginning) (region-end))))
10192 (link link-location)
10193 (abbrevs org-link-abbrev-alist-local)
10194 entry all-prefixes auto-desc)
10196 (link-location) ; specified by arg, just use it.
10197 ((org-in-regexp org-bracket-link-regexp 1)
10198 ;; We do have a link at point, and we are going to edit it.
10199 (setq remove (list (match-beginning 0) (match-end 0)))
10200 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10201 (setq link (read-string "Link: "
10203 (match-string-no-properties 1)))))
10204 ((or (org-in-regexp org-angle-link-re)
10205 (org-in-regexp org-plain-link-re))
10206 ;; Convert to bracket link
10207 (setq remove (list (match-beginning 0) (match-end 0))
10208 link (read-string "Link: "
10209 (org-unbracket-string "<" ">" (match-string 0)))))
10210 ((member complete-file '((4) (16)))
10211 ;; Completing read for file names.
10212 (setq link (org-file-complete-link complete-file)))
10214 ;; Read link, with completion for stored links.
10215 (org-link-fontify-links-to-this-file)
10216 (org-switch-to-buffer-other-window "*Org Links*")
10217 (with-current-buffer "*Org Links*"
10219 (insert "Insert a link.
10220 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10221 (when org-stored-links
10222 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10223 (insert (mapconcat 'org-link-prettify
10224 (reverse org-stored-links) "\n")))
10225 (goto-char (point-min)))
10226 (let ((cw (selected-window)))
10227 (select-window (get-buffer-window "*Org Links*" 'visible))
10228 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10229 (unless (pos-visible-in-window-p (point-max))
10230 (org-fit-window-to-buffer))
10231 (and (window-live-p cw) (select-window cw)))
10232 (setq all-prefixes (append (mapcar 'car abbrevs)
10233 (mapcar 'car org-link-abbrev-alist)
10236 ;; Fake a link history, containing the stored links.
10237 (let ((org--links-history
10238 (append (mapcar #'car org-stored-links)
10239 org-insert-link-history)))
10241 (org-completing-read
10244 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10245 (mapcar #'car org-stored-links))
10247 'org--links-history
10248 (caar org-stored-links)))
10249 (unless (org-string-nw-p link) (user-error "No link selected"))
10250 (dolist (l org-stored-links)
10251 (when (equal link (cadr l))
10252 (setq link (car l))
10253 (setq auto-desc t)))
10254 (when (or (member link all-prefixes)
10255 (and (equal ":" (substring link -1))
10256 (member (substring link 0 -1) all-prefixes)
10257 (setq link (substring link 0 -1))))
10258 (setq link (with-current-buffer origbuf
10259 (org-link-try-special-completion link)))))
10260 (set-window-configuration wcf)
10261 (kill-buffer "*Org Links*"))
10262 (setq entry (assoc link org-stored-links))
10263 (or entry (push link org-insert-link-history))
10264 (setq desc (or desc (nth 1 entry)))))
10266 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10267 (not org-keep-stored-link-after-insertion))
10268 (setq org-stored-links (delq (assoc link org-stored-links)
10269 org-stored-links)))
10271 (when (and (string-match org-plain-link-re link)
10272 (not (string-match org-ts-regexp link)))
10273 ;; URL-like link, normalize the use of angular brackets.
10274 (setq link (org-unbracket-string "<" ">" link)))
10276 ;; Check if we are linking to the current file with a search
10277 ;; option If yes, simplify the link by using only the search
10279 (when (and buffer-file-name
10280 (let ((case-fold-search nil))
10281 (string-match "\\`file:\\(.+?\\)::" link)))
10282 (let ((path (match-string-no-properties 1 link))
10283 (search (substring-no-properties link (match-end 0))))
10285 (when (equal (file-truename buffer-file-name) (file-truename path))
10286 ;; We are linking to this same file, with a search option
10287 (setq link search)))))
10289 ;; Check if we can/should use a relative path. If yes, simplify
10291 (let ((case-fold-search nil))
10292 (when (string-match "\\`\\(file\\|docview\\):" link)
10293 (let* ((type (match-string-no-properties 0 link))
10294 (path-start (match-end 0))
10295 (search (and (string-match "::\\(.*\\)\\'" link)
10296 (match-string 1 link)))
10299 (substring-no-properties
10300 link path-start (match-beginning 0))
10301 (substring-no-properties link (match-end 0))))
10304 ((or (eq org-link-file-path-type 'absolute)
10305 (equal complete-file '(16)))
10306 (setq path (abbreviate-file-name (expand-file-name path))))
10307 ((eq org-link-file-path-type 'noabbrev)
10308 (setq path (expand-file-name path)))
10309 ((eq org-link-file-path-type 'relative)
10310 (setq path (file-relative-name path)))
10313 (if (string-match (concat "^" (regexp-quote
10315 (file-name-as-directory
10316 default-directory))))
10317 (expand-file-name path))
10318 ;; We are linking a file with relative path name.
10319 (setq path (substring (expand-file-name path)
10321 (setq path (abbreviate-file-name (expand-file-name path)))))))
10322 (setq link (concat type path (and search (concat "::" search))))
10323 (when (equal desc origpath)
10324 (setq desc path)))))
10327 (let ((initial-input
10329 (default-description)
10330 ((not org-make-link-description-function) desc)
10331 (t (condition-case nil
10332 (funcall org-make-link-description-function link desc)
10334 (message "Can't get link description from `%s'"
10335 (symbol-name org-make-link-description-function))
10338 (setq desc (read-string "Description: " initial-input))))
10340 (unless (string-match "\\S-" desc) (setq desc nil))
10341 (when remove (apply 'delete-region remove))
10342 (insert (org-make-link-string link desc))
10343 ;; Redisplay so as the new link has proper invisible characters.
10346 (defun org-link-try-special-completion (type)
10347 "If there is completion support for link type TYPE, offer it."
10348 (let ((fun (org-link-get-parameter type :complete)))
10349 (if (functionp fun)
10351 (read-string "Link (no completion support): " (concat type ":")))))
10353 (defun org-file-complete-link (&optional arg)
10354 "Create a file link using completion."
10355 (let ((file (read-file-name "File: "))
10356 (pwd (file-name-as-directory (expand-file-name ".")))
10357 (pwd1 (file-name-as-directory (abbreviate-file-name
10358 (expand-file-name ".")))))
10359 (cond ((equal arg '(16))
10361 (abbreviate-file-name (expand-file-name file))))
10363 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10364 (concat "file:" (match-string 1 file)))
10366 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10367 (expand-file-name file))
10369 (match-string 1 (expand-file-name file))))
10370 (t (concat "file:" file)))))
10372 (defun org-completing-read (&rest args)
10373 "Completing-read with SPACE being a normal character."
10374 (let ((enable-recursive-minibuffers t)
10375 (minibuffer-local-completion-map
10376 (copy-keymap minibuffer-local-completion-map)))
10377 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10378 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10379 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10380 'org-time-stamp-inactive)
10381 (apply #'completing-read args)))
10383 ;;; Opening/following a link
10385 (defvar org-link-search-failed nil)
10387 (defvar org-open-link-functions nil
10388 "Hook for functions finding a plain text link.
10389 These functions must take a single argument, the link content.
10390 They will be called for links that look like [[link text][description]]
10391 when LINK TEXT does not have a protocol like \"http:\" and does not look
10392 like a filename (e.g. \"./blue.png\").
10394 These functions will be called *before* Org attempts to resolve the
10395 link by doing text searches in the current buffer - so if you want a
10396 link \"[[target]]\" to still find \"<<target>>\", your function should
10397 handle this as a special case.
10399 When the function does handle the link, it must return a non-nil value.
10400 If it decides that it is not responsible for this link, it must return
10401 nil to indicate that that Org can continue with other options like
10402 exact and fuzzy text search.")
10404 (defun org-next-link (&optional search-backward)
10405 "Move forward to the next link.
10406 If the link is in hidden text, expose it."
10408 (when (and org-link-search-failed (eq this-command last-command))
10409 (goto-char (point-min))
10410 (message "Link search wrapped back to beginning of buffer"))
10411 (setq org-link-search-failed nil)
10412 (let* ((pos (point))
10414 (a (assq :link ct))
10415 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10416 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10417 ((looking-at org-any-link-re)
10418 ;; Don't stay stuck at link without an org-link face
10419 (forward-char (if search-backward -1 1))))
10420 (if (funcall srch-fun org-any-link-re nil t)
10422 (goto-char (match-beginning 0))
10423 (when (org-invisible-p) (org-show-context)))
10425 (setq org-link-search-failed t)
10426 (message "No further link found"))))
10428 (defun org-previous-link ()
10429 "Move backward to the previous link.
10430 If the link is in hidden text, expose it."
10432 (funcall 'org-next-link t))
10434 (defun org-translate-link (s)
10435 "Translate a link string if a translation function has been defined."
10437 (insert (org-trim s))
10438 (org-trim (org-element-interpret-data (org-element-context)))))
10440 (defun org-translate-link-from-planner (type path)
10441 "Translate a link from Emacs Planner syntax so that Org can follow it.
10442 This is still an experimental function, your mileage may vary."
10444 ((member type '("http" "https" "news" "ftp"))
10445 ;; standard Internet links are the same.
10447 ((and (equal type "irc") (string-match "^//" path))
10448 ;; Planner has two / at the beginning of an irc link, we have 1.
10449 ;; We should have zero, actually....
10450 (setq path (substring path 1)))
10451 ((and (equal type "lisp") (string-match "^/" path))
10452 ;; Planner has a slash, we do not.
10453 (setq type "elisp" path (substring path 1)))
10454 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10455 ;; A typical message link. Planner has the id after the final slash,
10456 ;; we separate it with a hash mark
10457 (setq path (concat (match-string 1 path) "#"
10458 (org-unbracket-string "<" ">" (match-string 2 path))))))
10461 (defun org-find-file-at-mouse (ev)
10462 "Open file link or URL at mouse."
10464 (mouse-set-point ev)
10465 (org-open-at-point 'in-emacs))
10467 (defun org-open-at-mouse (ev)
10468 "Open file link or URL at mouse.
10469 See the docstring of `org-open-file' for details."
10471 (mouse-set-point ev)
10472 (when (eq major-mode 'org-agenda-mode)
10473 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10474 (org-open-at-point))
10476 (defvar org-window-config-before-follow-link nil
10477 "The window configuration before following a link.
10478 This is saved in case the need arises to restore it.")
10481 (defun org-open-at-point-global ()
10482 "Follow a link or time-stamp like Org mode does.
10483 This command can be called in any mode to follow an external link
10484 or a time-stamp that has Org mode syntax. Its behavior is
10485 undefined when called on internal links (e.g., fuzzy links).
10486 Raise an error when there is nothing to follow. "
10488 (cond ((org-in-regexp org-any-link-re)
10489 (org-open-link-from-string (match-string-no-properties 0)))
10490 ((or (org-in-regexp org-ts-regexp-both nil t)
10491 (org-in-regexp org-tsr-regexp-both nil t))
10492 (org-follow-timestamp-link))
10493 (t (user-error "No link found"))))
10496 (defun org-open-link-from-string (s &optional arg reference-buffer)
10497 "Open a link in the string S, as if it was in Org mode."
10498 (interactive "sLink: \nP")
10499 (let ((reference-buffer (or reference-buffer (current-buffer))))
10501 (let ((org-inhibit-startup (not reference-buffer)))
10504 (goto-char (point-min))
10505 (when reference-buffer
10506 (setq org-link-abbrev-alist-local
10507 (with-current-buffer reference-buffer
10508 org-link-abbrev-alist-local)))
10509 (org-open-at-point arg reference-buffer)))))
10511 (defvar org-open-at-point-functions nil
10512 "Hook that is run when following a link at point.
10514 Functions in this hook must return t if they identify and follow
10515 a link at point. If they don't find anything interesting at point,
10516 they must return nil.")
10518 (defvar org-link-search-inhibit-query nil)
10519 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10520 (defun org--open-doi-link (path)
10521 "Open a \"doi\" type link.
10522 PATH is a the path to search for, as a string."
10523 (browse-url (url-encode-url (concat org-doi-server-url path))))
10525 (defun org--open-elisp-link (path)
10526 "Open a \"elisp\" type link.
10527 PATH is the sexp to evaluate, as a string."
10529 (if (or (and (org-string-nw-p
10530 org-confirm-elisp-link-not-regexp)
10531 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10532 (not org-confirm-elisp-link-function)
10533 (funcall org-confirm-elisp-link-function
10534 (format "Execute \"%s\" as elisp? "
10535 (org-add-props cmd nil 'face 'org-warning))))
10536 (message "%s => %s" cmd
10537 (if (eq (string-to-char cmd) ?\()
10539 (call-interactively (read cmd))))
10540 (user-error "Abort"))))
10542 (defun org--open-help-link (path)
10543 "Open a \"help\" type link.
10544 PATH is a symbol name, as a string."
10545 (pcase (intern path)
10546 ((and (pred fboundp) variable) (describe-function variable))
10547 ((and (pred boundp) function) (describe-variable function))
10548 (name (user-error "Unknown function or variable: %s" name))))
10550 (defun org--open-shell-link (path)
10551 "Open a \"shell\" type link.
10552 PATH is the command to execute, as a string."
10553 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10555 (if (or (and (org-string-nw-p
10556 org-confirm-shell-link-not-regexp)
10558 org-confirm-shell-link-not-regexp cmd))
10559 (not org-confirm-shell-link-function)
10560 (funcall org-confirm-shell-link-function
10561 (format "Execute \"%s\" in shell? "
10562 (org-add-props cmd nil
10563 'face 'org-warning))))
10565 (message "Executing %s" cmd)
10566 (shell-command cmd buf)
10567 (when (featurep 'midnight)
10568 (setq clean-buffer-list-kill-buffer-names
10569 (cons (buffer-name buf)
10570 clean-buffer-list-kill-buffer-names))))
10571 (user-error "Abort"))))
10573 (defun org-open-at-point (&optional arg reference-buffer)
10574 "Open link, timestamp, footnote or tags at point.
10576 When point is on a link, follow it. Normally, files will be
10577 opened by an appropriate application. If the optional prefix
10578 argument ARG is non-nil, Emacs will visit the file. With
10579 a double prefix argument, try to open outside of Emacs, in the
10580 application the system uses for this file type.
10582 When point is on a timestamp, open the agenda at the day
10585 When point is a footnote definition, move to the first reference
10586 found. If it is on a reference, move to the associated
10589 When point is on a headline, display a list of every link in the
10590 entry, so it is possible to pick one, or all, of them. If point
10591 is on a tag, call `org-tags-view' instead.
10593 When optional argument REFERENCE-BUFFER is non-nil, it should
10594 specify a buffer from where the link search should happen. This
10595 is used internally by `org-open-link-from-string'.
10597 On top of syntactically correct links, this function will also
10598 try to open links and time-stamps in comments, example
10599 blocks... i.e., whenever point is on something looking like
10600 a timestamp or a link."
10602 ;; On a code block, open block's results.
10603 (unless (call-interactively 'org-babel-open-src-block-result)
10604 (org-load-modules-maybe)
10605 (setq org-window-config-before-follow-link (current-window-configuration))
10606 (org-remove-occur-highlights nil nil t)
10607 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10609 ;; Only consider supported types, even if they are not
10610 ;; the closest one.
10611 (org-element-lineage
10612 (org-element-context)
10613 '(clock footnote-definition footnote-reference headline
10614 inlinetask link timestamp)
10616 (type (org-element-type context))
10617 (value (org-element-property :value context)))
10619 ;; On a headline or an inlinetask, but not on a timestamp,
10620 ;; a link, a footnote reference.
10621 ((memq type '(headline inlinetask))
10622 (org-match-line org-complex-heading-regexp)
10623 (if (and (match-beginning 5)
10624 (>= (point) (match-beginning 5))
10625 (< (point) (match-end 5)))
10627 (org-tags-view arg (substring (match-string 5) 0 -1))
10629 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10631 (require 'org-attach)
10632 (org-attach-reveal 'if-exists))
10633 (`(,links . ,links-end)
10634 (dolist (link (if (stringp links) (list links) links))
10635 (search-forward link nil links-end)
10636 (goto-char (match-beginning 0))
10637 (org-open-at-point))))))
10638 ;; On a footnote reference or at definition's label.
10639 ((or (eq type 'footnote-reference)
10640 (and (eq type 'footnote-definition)
10642 ;; Do not validate action when point is on the
10643 ;; spaces right after the footnote label, in
10644 ;; order to be on par with behaviour on links.
10645 (skip-chars-forward " \t")
10647 (org-element-property :contents-begin context)))
10648 (if begin (< (point) begin)
10649 (= (org-element-property :post-affiliated context)
10650 (line-beginning-position)))))))
10651 (org-footnote-action))
10652 ;; No valid context. Ignore catch-all types like `headline'.
10653 ;; If point is on something looking like a link or
10654 ;; a time-stamp, try opening it. It may be useful in
10655 ;; comments, example blocks...
10656 ((memq type '(footnote-definition headline inlinetask nil))
10657 (call-interactively #'org-open-at-point-global))
10658 ;; On a clock line, make sure point is on the timestamp
10659 ;; before opening it.
10660 ((and (eq type 'clock)
10662 (>= (point) (org-element-property :begin value))
10663 (<= (point) (org-element-property :end value)))
10664 (org-follow-timestamp-link))
10665 ;; Do nothing on white spaces after an object.
10668 (goto-char (org-element-property :end context))
10669 (skip-chars-backward " \t")
10671 (user-error "No link found"))
10672 ((eq type 'timestamp) (org-follow-timestamp-link))
10674 (let ((type (org-element-property :type context))
10675 (path (org-link-unescape (org-element-property :path context))))
10676 ;; Switch back to REFERENCE-BUFFER needed when called in
10677 ;; a temporary buffer through `org-open-link-from-string'.
10678 (with-current-buffer (or reference-buffer (current-buffer))
10680 ((equal type "file")
10681 (if (string-match "[*?{]" (file-name-nondirectory path))
10683 ;; Look into `org-link-parameters' in order to find
10684 ;; a DEDICATED-FUNCTION to open file. The function
10685 ;; will be applied on raw link instead of parsed
10686 ;; link due to the limitation in `org-add-link-type'
10687 ;; ("open" function called with a single argument).
10688 ;; If no such function is found, fallback to
10689 ;; `org-open-file'.
10690 (let* ((option (org-element-property :search-option context))
10691 (app (org-element-property :application context))
10692 (dedicated-function
10693 (org-link-get-parameter
10694 (if app (concat type "+" app) type)
10696 (if dedicated-function
10697 (funcall dedicated-function
10699 (and option (concat "::" option))))
10700 (apply #'org-open-file
10703 ((equal app "emacs") 'emacs)
10704 ((equal app "sys") 'system))
10705 (cond ((not option) nil)
10706 ((string-match-p "\\`[0-9]+\\'" option)
10707 (list (string-to-number option)))
10709 (org-link-unescape option)))))))))
10710 ((functionp (org-link-get-parameter type :follow))
10711 (funcall (org-link-get-parameter type :follow) path))
10712 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10713 (unless (run-hook-with-args-until-success
10714 'org-open-link-functions path)
10715 (if (not arg) (org-mark-ring-push)
10716 (switch-to-buffer-other-window
10717 (org-get-buffer-for-internal-link (current-buffer))))
10719 (org-with-wide-buffer
10720 (if (equal type "radio")
10721 (org-search-radio-target
10722 (org-element-property :path context))
10724 (if (member type '("custom-id" "coderef"))
10725 (org-element-property :raw-link context)
10727 ;; Prevent fuzzy links from matching
10729 (and (equal type "fuzzy")
10730 (+ 2 (org-element-property :begin context)))))
10732 (unless (and (<= (point-min) destination)
10733 (>= (point-max) destination))
10735 (goto-char destination))))
10736 (t (browse-url-at-point))))))
10737 (t (user-error "No link found")))))
10738 (run-hook-with-args 'org-follow-link-hook)))
10740 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10741 "Offer links in the current entry and return the selected link.
10742 If there is only one link, return it.
10743 If NTH is an integer, return the NTH link found.
10744 If ZERO is a string, check also this string for a link, and if
10745 there is one, return it."
10746 (with-current-buffer buffer
10747 (org-with-wide-buffer
10750 have-zero end links link c)
10751 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10752 (push (match-string 0 zero) links)
10753 (setq cnt (1- cnt) have-zero t))
10755 (org-back-to-heading t)
10756 (setq end (save-excursion (outline-next-heading) (point)))
10757 (while (re-search-forward org-any-link-re end t)
10758 (push (match-string 0) links))
10759 (setq links (org-uniquify (reverse links))))
10762 (message "No links"))
10763 ((equal (length links) 1)
10764 (setq link (car links)))
10765 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10766 (setq link (nth (if have-zero nth (1- nth)) links)))
10767 (t ; we have to select a link
10769 (save-window-excursion
10770 (delete-other-windows)
10771 (with-output-to-temp-buffer "*Select Link*"
10774 ((not (string-match org-bracket-link-regexp l))
10775 (princ (format "[%c] %s\n" (cl-incf cnt)
10776 (org-unbracket-string "<" ">" l))))
10778 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10779 (match-string 3 l) (match-string 1 l))))
10780 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10781 (match-string 1 l)))))))
10782 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10783 (message "Select link to open, RET to open all:")
10784 (setq c (read-char-exclusive))
10785 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10786 (when (equal c ?q) (user-error "Abort"))
10787 (if (equal c ?\C-m)
10789 (setq nth (- c ?0))
10790 (when have-zero (setq nth (1+ nth)))
10791 (unless (and (integerp nth) (>= (length links) nth))
10792 (user-error "Invalid link selection"))
10793 (setq link (nth (1- nth) links)))))
10794 (cons link end)))))
10796 ;; TODO: These functions are deprecated since `org-open-at-point'
10797 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10798 (defun org-open-file-with-system (path)
10799 "Open file at PATH using the system way of opening it."
10800 (org-open-file path 'system))
10801 (defun org-open-file-with-emacs (path)
10802 "Open file at PATH in Emacs."
10803 (org-open-file path 'emacs))
10808 (defvar org-create-file-search-functions nil
10809 "List of functions to construct the right search string for a file link.
10810 These functions are called in turn with point at the location to
10811 which the link should point.
10813 A function in the hook should first test if it would like to
10814 handle this file type, for example by checking the `major-mode'
10815 or the file extension. If it decides not to handle this file, it
10816 should just return nil to give other functions a chance. If it
10817 does handle the file, it must return the search string to be used
10818 when following the link. The search string will be part of the
10819 file link, given after a double colon, and `org-open-at-point'
10820 will automatically search for it. If special measures must be
10821 taken to make the search successful, another function should be
10822 added to the companion hook `org-execute-file-search-functions',
10825 A function in this hook may also use `setq' to set the variable
10826 `description' to provide a suggestion for the descriptive text to
10827 be used for this link when it gets inserted into an Org buffer
10828 with \\[org-insert-link].")
10830 (defvar org-execute-file-search-functions nil
10831 "List of functions to execute a file search triggered by a link.
10833 Functions added to this hook must accept a single argument, the
10834 search string that was part of the file link, the part after the
10835 double colon. The function must first check if it would like to
10836 handle this search, for example by checking the `major-mode' or
10837 the file extension. If it decides not to handle this search, it
10838 should just return nil to give other functions a chance. If it
10839 does handle the search, it must return a non-nil value to keep
10840 other functions from trying.
10842 Each function can access the current prefix argument through the
10843 variable `current-prefix-arg'. Note that a single prefix is used
10844 to force opening a link in Emacs, so it may be good to only use a
10845 numeric or double prefix to guide the search function.
10847 In case this is needed, a function in this hook can also restore
10848 the window configuration before `org-open-at-point' was called using:
10850 (set-window-configuration org-window-config-before-follow-link)")
10852 (defun org-search-radio-target (target)
10853 "Search a radio target matching TARGET in current buffer.
10854 White spaces are not significant."
10855 (let ((re (format "<<<%s>>>"
10856 (mapconcat #'regexp-quote
10857 (split-string target)
10858 "[ \t]+\\(?:\n[ \t]*\\)?")))
10860 (goto-char (point-min))
10861 (catch :radio-match
10862 (while (re-search-forward re nil t)
10864 (let ((object (org-element-context)))
10865 (when (eq (org-element-type object) 'radio-target)
10866 (goto-char (org-element-property :begin object))
10867 (org-show-context 'link-search)
10868 (throw :radio-match nil))))
10870 (user-error "No match for radio target: %s" target))))
10872 (defun org-link-search (s &optional avoid-pos stealth)
10873 "Search for a search string S.
10875 If S starts with \"#\", it triggers a custom ID search.
10877 If S is enclosed within parenthesis, it initiates a coderef
10880 If S is surrounded by forward slashes, it is interpreted as
10881 a regular expression. In Org mode files, this will create an
10882 `org-occur' sparse tree. In ordinary files, `occur' will be used
10883 to list matches. If the current buffer is in `dired-mode', grep
10884 will be used to search in all files.
10886 When AVOID-POS is given, ignore matches near that position.
10888 When optional argument STEALTH is non-nil, do not modify
10889 visibility around point, thus ignoring `org-show-context-detail'
10892 Search is case-insensitive and ignores white spaces. Return type
10893 of matched result, which is either `dedicated' or `fuzzy'."
10894 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10895 (let* ((case-fold-search t)
10897 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10898 (starred (eq (string-to-char normalized) ?*))
10899 (words (split-string (if starred (substring s 1) s)))
10900 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10901 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10904 ;; Check if there are any special search functions.
10905 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10906 ((eq (string-to-char s) ?#)
10907 ;; Look for a custom ID S if S starts with "#".
10908 (let* ((id (substring normalized 1))
10909 (match (org-find-property "CUSTOM_ID" id)))
10910 (if match (progn (goto-char match) (setf type 'dedicated))
10911 (error "No match for custom ID: %s" id))))
10912 ((string-match "\\`(\\(.*\\))\\'" normalized)
10913 ;; Look for coderef targets if S is enclosed within parenthesis.
10914 (let ((coderef (match-string-no-properties 1 normalized))
10915 (re (substring s-single-re 1 -1)))
10916 (goto-char (point-min))
10917 (catch :coderef-match
10918 (while (re-search-forward re nil t)
10919 (let ((element (org-element-at-point)))
10920 (when (and (memq (org-element-type element)
10921 '(example-block src-block))
10922 ;; Build proper regexp according to current
10923 ;; block's label format.
10926 (or (org-element-property :label-fmt element)
10927 org-coderef-label-format))))
10929 (beginning-of-line)
10930 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10931 (format label-fmt coderef))))))
10932 (setq type 'dedicated)
10933 (goto-char (match-beginning 1))
10934 (throw :coderef-match nil))))
10936 (error "No match for coderef: %s" coderef))))
10937 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10938 ;; Look for a regular expression.
10939 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10940 (match-string 1 s)))
10941 ;; From here, we handle fuzzy links.
10943 ;; Look for targets, only if not in a headline search.
10944 ((and (not starred)
10945 (let ((target (format "<<%s>>" s-multi-re)))
10946 (catch :target-match
10947 (goto-char (point-min))
10948 (while (re-search-forward target nil t)
10950 (let ((context (org-element-context)))
10951 (when (eq (org-element-type context) 'target)
10952 (setq type 'dedicated)
10953 (goto-char (org-element-property :begin context))
10954 (throw :target-match t))))
10956 ;; Look for elements named after S, only if not in a headline
10958 ((and (not starred)
10959 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10961 (goto-char (point-min))
10962 (while (re-search-forward name nil t)
10963 (let ((element (org-element-at-point)))
10966 (org-element-property :name element)))
10967 (setq type 'dedicated)
10968 (beginning-of-line)
10969 (throw :name-match t))))
10971 ;; Regular text search. Prefer headlines in Org mode buffers.
10972 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10973 ;; statistics cookies and tags.
10974 ((and (derived-mode-p 'org-mode)
10976 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10977 org-outline-regexp-bol
10979 (mapconcat #'regexp-quote words ".+")))
10980 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10981 (comment-re (eval-when-compile
10982 (format "\\`%s[ \t]+" org-comment-string))))
10983 (goto-char (point-min))
10985 (while (re-search-forward title-re nil t)
10988 (replace-regexp-in-string
10990 (replace-regexp-in-string
10991 comment-re "" (org-get-heading t t t)))))
10994 (beginning-of-line)
10995 (setq type 'dedicated))
10996 ;; Offer to create non-existent headline depending on
10997 ;; `org-link-search-must-match-exact-headline'.
10998 ((and (derived-mode-p 'org-mode)
10999 (not org-link-search-inhibit-query)
11000 (eq org-link-search-must-match-exact-headline 'query-to-create)
11001 (yes-or-no-p "No match - create this as a new heading? "))
11002 (goto-char (point-max))
11003 (unless (bolp) (newline))
11004 (org-insert-heading nil t t)
11006 (beginning-of-line 0))
11007 ;; Only headlines are looked after. No need to process
11008 ;; further: throw an error.
11009 ((and (derived-mode-p 'org-mode)
11010 (or starred org-link-search-must-match-exact-headline))
11012 (error "No match for fuzzy expression: %s" normalized))
11013 ;; Regular text search.
11014 ((catch :fuzzy-match
11015 (goto-char (point-min))
11016 (while (re-search-forward s-multi-re nil t)
11017 ;; Skip match if it contains AVOID-POS or it is included in
11018 ;; a link with a description but outside the description.
11019 (unless (or (and avoid-pos
11020 (<= (match-beginning 0) avoid-pos)
11021 (> (match-end 0) avoid-pos))
11022 (and (save-match-data
11023 (org-in-regexp org-bracket-link-regexp))
11024 (match-beginning 3)
11025 (or (> (match-beginning 3) (point))
11026 (<= (match-end 3) (point)))
11027 (org-element-lineage
11028 (save-match-data (org-element-context))
11030 (goto-char (match-beginning 0))
11032 (throw :fuzzy-match t)))
11034 ;; All failed. Throw an error.
11035 (t (goto-char origin)
11036 (error "No match for fuzzy expression: %s" normalized)))
11037 ;; Disclose surroundings of match, if appropriate.
11038 (when (and (derived-mode-p 'org-mode) (not stealth))
11039 (org-show-context 'link-search))
11042 (defun org-get-buffer-for-internal-link (buffer)
11043 "Return a buffer to be used for displaying the link target of internal links."
11045 ((not org-display-internal-link-with-indirect-buffer)
11047 ((string-suffix-p "(Clone)" (buffer-name buffer))
11048 (message "Buffer is already a clone, not making another one")
11049 ;; we also do not modify visibility in this case
11051 (t ; make a new indirect buffer for displaying the link
11052 (let* ((bn (buffer-name buffer))
11053 (ibn (concat bn "(Clone)"))
11054 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11055 (with-current-buffer ib (org-overview))
11058 (defun org-do-occur (regexp &optional cleanup)
11059 "Call the Emacs command `occur'.
11060 If CLEANUP is non-nil, remove the printout of the regular expression
11061 in the *Occur* buffer. This is useful if the regex is long and not useful
11065 (let ((cwin (selected-window)) win beg end)
11066 (when (setq win (get-buffer-window "*Occur*"))
11067 (select-window win))
11068 (goto-char (point-min))
11069 (when (re-search-forward "match[a-z]+" nil t)
11070 (setq beg (match-end 0))
11071 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11072 (setq end (1- (match-beginning 0)))))
11073 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11074 (goto-char (point-min))
11075 (select-window cwin))))
11077 ;;; The mark ring for links jumps
11079 (defvar org-mark-ring nil
11080 "Mark ring for positions before jumps in Org mode.")
11081 (defvar org-mark-ring-last-goto nil
11082 "Last position in the mark ring used to go back.")
11083 ;; Fill and close the ring
11084 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11085 (dotimes (_ org-mark-ring-length)
11086 (push (make-marker) org-mark-ring))
11087 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11090 (defun org-mark-ring-push (&optional pos buffer)
11091 "Put the current position or POS into the mark ring and rotate it."
11093 (setq pos (or pos (point)))
11094 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11095 (move-marker (car org-mark-ring)
11097 (or buffer (current-buffer)))
11099 (substitute-command-keys
11100 "Position saved to mark ring, go back with \
11101 `\\[org-mark-ring-goto]'.")))
11103 (defun org-mark-ring-goto (&optional n)
11104 "Jump to the previous position in the mark ring.
11105 With prefix arg N, jump back that many stored positions. When
11106 called several times in succession, walk through the entire ring.
11107 Org mode commands jumping to a different position in the current file,
11108 or to another Org file, automatically push the old position onto the ring."
11111 (if (eq last-command this-command)
11112 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11113 (setq p org-mark-ring))
11114 (setq org-mark-ring-last-goto p)
11116 (pop-to-buffer-same-window (marker-buffer m))
11118 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11120 (defun org-add-angle-brackets (s)
11121 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11122 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11125 ;;; Following specific links
11127 (defvar org-agenda-buffer-tmp-name)
11128 (defvar org-agenda-start-on-weekday)
11129 (defun org-follow-timestamp-link ()
11130 "Open an agenda view for the time-stamp date/range at point."
11132 ((org-at-date-range-p t)
11133 (let ((org-agenda-start-on-weekday)
11134 (t1 (match-string 1))
11135 (t2 (match-string 2)) tt1 tt2)
11136 (setq tt1 (time-to-days (org-time-string-to-time t1))
11137 tt2 (time-to-days (org-time-string-to-time t2)))
11138 (let ((org-agenda-buffer-tmp-name
11139 (format "*Org Agenda(a:%s)"
11140 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11141 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11142 ((org-at-timestamp-p 'lax)
11143 (let ((org-agenda-buffer-tmp-name
11144 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11145 (org-agenda-list nil (time-to-days (org-time-string-to-time
11146 (substring (match-string 1) 0 10)))
11148 (t (error "This should not happen"))))
11151 ;;; Following file links
11152 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11153 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11154 (declare-function mailcap-mime-info
11155 "mailcap" (string &optional request no-decode))
11156 (defvar org-wait nil)
11157 (defun org-open-file (path &optional in-emacs line search)
11158 "Open the file at PATH.
11159 First, this expands any special file name abbreviations. Then the
11160 configuration variable `org-file-apps' is checked if it contains an
11161 entry for this file type, and if yes, the corresponding command is launched.
11163 If no application is found, Emacs simply visits the file.
11165 With optional prefix argument IN-EMACS, Emacs will visit the file.
11166 With a double \\[universal-argument] \\[universal-argument] \
11167 prefix arg, Org tries to avoid opening in Emacs
11168 and to use an external application to visit the file.
11170 Optional LINE specifies a line to go to, optional SEARCH a string
11171 to search for. If LINE or SEARCH is given, the file will be
11172 opened in Emacs, unless an entry from org-file-apps that makes
11173 use of groups in a regexp matches.
11175 If you want to change the way frames are used when following a
11176 link, please customize `org-link-frame-setup'.
11178 If the file does not exist, an error is thrown."
11179 (let* ((file (if (equal path "")
11181 (substitute-in-file-name (expand-file-name path))))
11182 (file-apps (append org-file-apps (org-default-apps)))
11183 (apps (cl-remove-if
11184 'org-file-apps-entry-match-against-dlink-p file-apps))
11185 (apps-dlink (cl-remove-if-not
11186 'org-file-apps-entry-match-against-dlink-p file-apps))
11187 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11188 (dirp (unless remp (file-directory-p file)))
11189 (file (if (and dirp org-open-directory-means-index-dot-org)
11190 (concat (file-name-as-directory file) "index.org")
11192 (a-m-a-p (assq 'auto-mode apps))
11193 (dfile (downcase file))
11194 ;; Reconstruct the original link from the PATH, LINE and
11196 (link (cond (line (concat file "::" (number-to-string line)))
11197 (search (concat file "::" search))
11199 (dlink (downcase link))
11201 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11202 (match-string 1 dfile)))
11203 (save-position-maybe
11204 (let ((old-buffer (current-buffer))
11206 (old-mode major-mode))
11208 (and (derived-mode-p 'org-mode)
11209 (eq old-mode 'org-mode)
11210 (or (not (eq old-buffer (current-buffer)))
11211 (not (eq old-pos (point))))
11212 (org-mark-ring-push old-pos old-buffer)))))
11213 cmd link-match-data)
11215 ((member in-emacs '((16) system))
11216 (setq cmd (cdr (assq 'system apps))))
11217 (in-emacs (setq cmd 'emacs))
11219 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11220 (and dirp (cdr (assq 'directory apps)))
11221 ;; First, try matching against apps-dlink if we
11222 ;; get a match here, store the match data for
11224 (let ((match (assoc-default dlink apps-dlink
11227 (progn (setq link-match-data (match-data))
11229 (progn (setq in-emacs (or in-emacs line search))
11230 nil))) ; if we have no match in apps-dlink,
11231 ; always open the file in emacs if line or search
11232 ; is given (for backwards compatibility)
11233 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11235 (cdr (assoc ext apps))
11236 (cdr (assq t apps))))))
11237 (when (eq cmd 'system)
11238 (setq cmd (cdr (assq 'system apps))))
11239 (when (eq cmd 'default)
11240 (setq cmd (cdr (assoc t apps))))
11241 (when (eq cmd 'mailcap)
11243 (mailcap-parse-mailcaps)
11244 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11245 (command (mailcap-mime-info mime-type)))
11246 (if (stringp command)
11248 (setq cmd 'emacs))))
11249 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11250 (not (file-exists-p file))
11251 (not org-open-non-existing-files))
11252 (user-error "No such file: %s" file))
11254 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11255 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11256 (while (string-match "['\"]%s['\"]" cmd)
11257 (setq cmd (replace-match "%s" t t cmd)))
11258 (setq cmd (replace-regexp-in-string
11260 (shell-quote-argument (convert-standard-filename file))
11264 ;; Replace "%1", "%2" etc. in command with group matches from regex
11266 (let ((match-index 1)
11267 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11268 (set-match-data link-match-data)
11269 (while (<= match-index number-of-groups)
11270 (let ((regex (concat "%" (number-to-string match-index)))
11271 (replace-with (match-string match-index dlink)))
11272 (while (string-match regex cmd)
11273 (setq cmd (replace-match replace-with t t cmd))))
11274 (setq match-index (+ match-index 1)))))
11276 (save-window-excursion
11277 (message "Running %s...done" cmd)
11278 (start-process-shell-command cmd nil cmd)
11279 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11282 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11284 (cond (line (org-goto-line line)
11285 (when (derived-mode-p 'org-mode) (org-reveal)))
11286 (search (condition-case err
11287 (org-link-search search)
11288 ;; Save position before error-ing out so user
11289 ;; can easily move back to the original buffer.
11290 (error (funcall save-position-maybe)
11291 (error (nth 1 err)))))))
11294 (set-match-data link-match-data)
11295 (condition-case nil
11296 (funcall cmd file link)
11297 ;; FIXME: Remove this check when most default installations
11298 ;; of Emacs have at least Org 9.0.
11299 ((debug wrong-number-of-arguments wrong-type-argument
11301 (user-error "Please see Org News for version 9.0 about \
11302 `org-file-apps'--Lisp error: %S" cmd)))))
11304 ;; FIXME: Remove this check when most default installations of
11305 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11306 ;; fall back to `org-link-frame-setup' for an old usage of
11307 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11308 (user-error "Please see Org News for version 9.0 about \
11309 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11310 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11311 (funcall save-position-maybe)))
11313 (defun org-file-apps-entry-match-against-dlink-p (entry)
11314 "This function returns non-nil if `entry' uses a regular
11315 expression which should be matched against the whole link by
11318 It assumes that is the case when the entry uses a regular
11319 expression which has at least one grouping construct and the
11320 action is either a lisp form or a command string containing
11321 `%1', i.e. using at least one subexpression match as a
11323 (let ((selector (car entry))
11324 (action (cdr entry)))
11325 (if (stringp selector)
11326 (and (> (regexp-opt-depth selector) 0)
11327 (or (and (stringp action)
11328 (string-match "%[0-9]" action))
11332 (defun org-default-apps ()
11333 "Return the default applications for this operating system."
11335 ((eq system-type 'darwin)
11336 org-file-apps-defaults-macosx)
11337 ((eq system-type 'windows-nt)
11338 org-file-apps-defaults-windowsnt)
11339 (t org-file-apps-defaults-gnu)))
11341 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11342 "Convert extensions to regular expressions in the cars of LIST.
11343 Also, weed out any non-string entries, because the return value is used
11344 only for regexp matching.
11345 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11346 point to the symbol `emacs', indicating that the file should
11347 be opened in Emacs."
11350 (mapcar (lambda (x)
11351 (unless (not (stringp (car x)))
11352 (if (string-match "\\W" (car x))
11354 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11356 (when add-auto-mode
11357 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11359 (defvar ange-ftp-name-format)
11360 (defun org-file-remote-p (file)
11361 "Test whether FILE specifies a location on a remote system.
11362 Return non-nil if the location is indeed remote.
11364 For example, the filename \"/user@host:/foo\" specifies a location
11365 on the system \"/user@host:\"."
11366 (cond ((fboundp 'file-remote-p)
11367 (file-remote-p file))
11368 ((fboundp 'tramp-handle-file-remote-p)
11369 (tramp-handle-file-remote-p file))
11370 ((and (boundp 'ange-ftp-name-format)
11371 (string-match (car ange-ftp-name-format) file))
11377 (defun org-get-org-file ()
11378 "Read a filename, with default directory `org-directory'."
11379 (let ((default (or org-default-notes-file remember-data-file)))
11380 (read-file-name (format "File name [%s]: " default)
11381 (file-name-as-directory org-directory)
11384 (defun org-notes-order-reversed-p ()
11385 "Check if the current file should receive notes in reversed order."
11387 ((not org-reverse-note-order) nil)
11388 ((eq t org-reverse-note-order) t)
11389 ((not (listp org-reverse-note-order)) nil)
11391 (dolist (entry org-reverse-note-order)
11392 (when (string-match (car entry) buffer-file-name)
11393 (throw 'exit (cdr entry))))))))
11395 (defvar org-refile-target-table nil
11396 "The list of refile targets, created by `org-refile'.")
11398 (defvar org-agenda-new-buffers nil
11399 "Buffers created to visit agenda files.")
11401 (defvar org-refile-cache nil
11402 "Cache for refile targets.")
11404 (defvar org-refile-markers nil
11405 "All the markers used for caching refile locations.")
11407 (defun org-refile-marker (pos)
11408 "Get a new refile marker, but only if caching is in use."
11409 (if (not org-refile-use-cache)
11411 (let ((m (make-marker)))
11412 (move-marker m pos)
11413 (push m org-refile-markers)
11416 (defun org-refile-cache-clear ()
11417 "Clear the refile cache and disable all the markers."
11418 (dolist (m org-refile-markers) (move-marker m nil))
11419 (setq org-refile-markers nil)
11420 (setq org-refile-cache nil)
11421 (message "Refile cache has been cleared"))
11423 (defun org-refile-cache-check-set (set)
11424 "Check if all the markers in the cache still have live buffers."
11427 (while (and set (setq marker (nth 3 (pop set))))
11428 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11429 (when (and marker (null (marker-buffer marker)))
11430 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11432 (throw 'exit nil)))
11435 (defun org-refile-cache-put (set &rest identifiers)
11436 "Push the refile targets SET into the cache, under IDENTIFIERS."
11437 (let* ((key (sha1 (prin1-to-string identifiers)))
11438 (entry (assoc key org-refile-cache)))
11441 (push (cons key set) org-refile-cache))))
11443 (defun org-refile-cache-get (&rest identifiers)
11444 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11446 ((not org-refile-cache) nil)
11447 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11449 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11450 org-refile-cache))))
11451 (and set (org-refile-cache-check-set set) set)))))
11453 (defvar org-outline-path-cache nil
11454 "Alist between buffer positions and outline paths.
11455 It value is an alist (POSITION . PATH) where POSITION is the
11456 buffer position at the beginning of an entry and PATH is a list
11457 of strings describing the outline path for that entry, in reverse
11460 (defun org-refile-get-targets (&optional default-buffer)
11461 "Produce a table with refile targets."
11462 (let ((case-fold-search nil)
11463 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11464 (entries (or org-refile-targets '((nil . (:level . 1)))))
11465 targets tgs files desc descre)
11466 (message "Getting targets...")
11467 (with-current-buffer (or default-buffer (current-buffer))
11468 (dolist (entry entries)
11469 (setq files (car entry) desc (cdr entry))
11471 ((null files) (setq files (list (current-buffer))))
11472 ((eq files 'org-agenda-files)
11473 (setq files (org-agenda-files 'unrestricted)))
11474 ((and (symbolp files) (fboundp files))
11475 (setq files (funcall files)))
11476 ((and (symbolp files) (boundp files))
11477 (setq files (symbol-value files))))
11478 (when (stringp files) (setq files (list files)))
11480 ((eq (car desc) :tag)
11481 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11482 ((eq (car desc) :todo)
11483 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11484 ((eq (car desc) :regexp)
11485 (setq descre (cdr desc)))
11486 ((eq (car desc) :level)
11487 (setq descre (concat "^\\*\\{" (number-to-string
11488 (if org-odd-levels-only
11489 (1- (* 2 (cdr desc)))
11492 ((eq (car desc) :maxlevel)
11493 (setq descre (concat "^\\*\\{1," (number-to-string
11494 (if org-odd-levels-only
11495 (1- (* 2 (cdr desc)))
11498 (t (error "Bad refiling target description %s" desc)))
11500 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11502 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11505 (setq f (buffer-file-name (buffer-base-buffer f))))
11506 (setq f (and f (expand-file-name f)))
11507 (when (eq org-refile-use-outline-path 'file)
11508 (push (list (file-name-nondirectory f) f nil nil) tgs))
11509 (when (eq org-refile-use-outline-path 'buffer-name)
11510 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11511 (when (eq org-refile-use-outline-path 'full-file-path)
11512 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11513 (org-with-wide-buffer
11514 (goto-char (point-min))
11515 (setq org-outline-path-cache nil)
11516 (while (re-search-forward descre nil t)
11517 (beginning-of-line)
11518 (let ((case-fold-search nil))
11519 (looking-at org-complex-heading-regexp))
11520 (let ((begin (point))
11521 (heading (match-string-no-properties 4)))
11523 org-refile-target-verify-function
11525 (funcall org-refile-target-verify-function)))
11527 (let ((re (format org-complex-heading-regexp-format
11528 (regexp-quote heading)))
11530 (if (not org-refile-use-outline-path) heading
11534 (pcase org-refile-use-outline-path
11535 (`file (list (file-name-nondirectory
11537 (buffer-base-buffer)))))
11539 (list (buffer-file-name
11540 (buffer-base-buffer))))
11543 (buffer-base-buffer))))
11545 (mapcar (lambda (s) (replace-regexp-in-string
11546 "/" "\\/" s nil t))
11547 (org-get-outline-path t t)))
11549 (push (list target f re (org-refile-marker (point)))
11551 (when (= (point) begin)
11552 ;; Verification function has not moved point.
11553 (end-of-line)))))))
11554 (when org-refile-use-cache
11555 (org-refile-cache-put tgs (buffer-file-name) descre))
11556 (setq targets (append tgs targets))))))
11557 (message "Getting targets...done")
11558 (delete-dups (nreverse targets))))
11560 (defun org--get-outline-path-1 (&optional use-cache)
11561 "Return outline path to current headline.
11563 Outline path is a list of strings, in reverse order. When
11564 optional argument USE-CACHE is non-nil, make use of a cache. See
11565 `org-get-outline-path' for details.
11567 Assume buffer is widened and point is on a headline."
11568 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11570 (heading (let ((case-fold-search nil))
11571 (looking-at org-complex-heading-regexp)
11572 (if (not (match-end 4)) ""
11573 ;; Remove statistics cookies.
11575 (org-link-display-format
11576 (replace-regexp-in-string
11577 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11578 (match-string-no-properties 4))))))))
11579 (if (org-up-heading-safe)
11580 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11582 (push (cons p path) org-outline-path-cache))
11584 ;; This is a new root node. Since we assume we are moving
11585 ;; forward, we can drop previous cache so as to limit number
11586 ;; of associations there.
11587 (let ((path (list heading)))
11588 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11591 (defun org-get-outline-path (&optional with-self use-cache)
11592 "Return the outline path to the current entry.
11594 An outline path is a list of ancestors for current headline, as
11595 a list of strings. Statistics cookies are removed and links are
11596 replaced with their description, if any, or their path otherwise.
11598 When optional argument WITH-SELF is non-nil, the path also
11599 includes the current headline.
11601 When optional argument USE-CACHE is non-nil, cache outline paths
11602 between calls to this function so as to avoid backtracking. This
11603 argument is useful when planning to find more than one outline
11604 path in the same document. In that case, there are two
11605 conditions to satisfy:
11606 - `org-outline-path-cache' is set to nil before starting the
11608 - outline paths are computed by increasing buffer positions."
11609 (org-with-wide-buffer
11610 (and (or (and with-self (org-back-to-heading t))
11611 (org-up-heading-safe))
11612 (reverse (org--get-outline-path-1 use-cache)))))
11614 (defun org-format-outline-path (path &optional width prefix separator)
11615 "Format the outline path PATH for display.
11616 WIDTH is the maximum number of characters that is available.
11617 PREFIX is a prefix to be included in the returned string,
11618 such as the file name.
11619 SEPARATOR is inserted between the different parts of the path,
11620 the default is \"/\"."
11621 (setq width (or width 79))
11622 (setq path (delq nil path))
11623 (unless (> width 0)
11624 (user-error "Argument `width' must be positive"))
11625 (setq separator (or separator "/"))
11626 (let* ((org-odd-levels-only nil)
11628 prefix (and prefix path separator)
11630 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11631 (cl-loop for head in path
11633 collect (org-add-props
11635 (nth (% n org-n-level-faces) org-level-faces)))
11637 (when (> (length fpath) width)
11639 ;; It's unlikely that `width' will be this small, but don't
11640 ;; waste characters by adding ".." if it is.
11641 (setq fpath (substring fpath 0 width))
11642 (setf (substring fpath (- width 2)) "..")))
11645 (defun org-display-outline-path (&optional file current separator just-return-string)
11646 "Display the current outline path in the echo area.
11648 If FILE is non-nil, prepend the output with the file name.
11649 If CURRENT is non-nil, append the current heading to the output.
11650 SEPARATOR is passed through to `org-format-outline-path'. It separates
11651 the different parts of the path and defaults to \"/\".
11652 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11654 (let* (case-fold-search
11655 (bfn (buffer-file-name (buffer-base-buffer)))
11656 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11658 (when current (setq path (append path
11660 (org-back-to-heading t)
11661 (when (looking-at org-complex-heading-regexp)
11662 (list (match-string 4)))))))
11664 (org-format-outline-path
11667 (and file bfn (concat (file-name-nondirectory bfn) separator))
11669 (if just-return-string
11670 (org-no-properties res)
11671 (org-unlogged-message "%s" res))))
11673 (defvar org-refile-history nil
11674 "History for refiling operations.")
11676 (defvar org-after-refile-insert-hook nil
11677 "Hook run after `org-refile' has inserted its stuff at the new location.
11678 Note that this is still *before* the stuff will be removed from
11679 the *old* location.")
11681 (defvar org-capture-last-stored-marker)
11682 (defvar org-refile-keep nil
11683 "Non-nil means `org-refile' will copy instead of refile.")
11686 "Like `org-refile', but copy."
11688 (let ((org-refile-keep t))
11689 (funcall 'org-refile nil nil nil "Copy")))
11691 (defun org-refile (&optional arg default-buffer rfloc msg)
11692 "Move the entry or entries at point to another heading.
11694 The list of target headings is compiled using the information in
11695 `org-refile-targets', which see.
11697 At the target location, the entry is filed as a subitem of the
11698 target heading. Depending on `org-reverse-note-order', the new
11699 subitem will either be the first or the last subitem.
11701 If there is an active region, all entries in that region will be
11702 refiled. However, the region must fulfill the requirement that
11703 the first heading sets the top-level of the moved text.
11705 With a `\\[universal-argument]' ARG, the command will only visit the target \
11707 and not actually move anything.
11709 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11710 location where the last
11711 refiling operation has put the subtree.
11713 With a numeric prefix argument of `2', refile to the running clock.
11715 With a numeric prefix argument of `3', emulate `org-refile-keep'
11716 being set to t and copy to the target location, don't move it.
11717 Beware that keeping refiled entries may result in duplicated ID
11720 RFLOC can be a refile location obtained in a different way.
11722 MSG is a string to replace \"Refile\" in the default prompt with
11723 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11725 See also `org-refile-use-outline-path'.
11727 If you are using target caching (see `org-refile-use-cache'), you
11728 have to clear the target cache in order to find new targets.
11729 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11730 prefix argument (`C-u C-u C-u C-c C-w')."
11732 (if (member arg '(0 (64)))
11733 (org-refile-cache-clear)
11734 (let* ((actionmsg (cond (msg msg)
11735 ((equal arg 3) "Refile (and keep)")
11737 (regionp (org-region-active-p))
11738 (region-start (and regionp (region-beginning)))
11739 (region-end (and regionp (region-end)))
11740 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11741 pos it nbuf file level reversed)
11742 (setq last-command nil)
11744 (goto-char region-start)
11745 (or (bolp) (goto-char (point-at-bol)))
11746 (setq region-start (point))
11747 (unless (or (org-kill-is-subtree-p
11748 (buffer-substring region-start region-end))
11749 (prog1 org-refile-active-region-within-subtree
11750 (let ((s (point-at-eol)))
11751 (org-toggle-heading)
11752 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11753 (user-error "The region is not a (sequence of) subtree(s)")))
11754 (if (equal arg '(16))
11755 (org-refile-goto-last-stored)
11758 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11760 (setq it (list (or org-clock-heading "running clock")
11762 (marker-buffer org-clock-hd-marker))
11764 (marker-position org-clock-hd-marker)))
11768 (let (heading-text)
11770 (unless (and arg (listp arg))
11771 (org-back-to-heading t)
11773 (replace-regexp-in-string
11774 org-bracket-link-regexp
11776 (or (nth 4 (org-heading-components))
11778 (org-refile-get-location
11779 (cond ((and arg (listp arg)) "Goto")
11780 (regionp (concat actionmsg " region to"))
11781 (t (concat actionmsg " subtree \""
11782 heading-text "\" to")))
11784 (and (not (equal '(4) arg))
11785 org-refile-allow-creating-parent-nodes)))))))
11786 (setq file (nth 1 it)
11788 (when (and (not arg)
11790 (equal (buffer-file-name) file)
11792 (and (>= pos region-start)
11793 (<= pos region-end))
11794 (and (>= pos (point))
11795 (< pos (save-excursion
11796 (org-end-of-subtree t t))))))
11797 (error "Cannot refile to position inside the tree or region"))
11798 (setq nbuf (or (find-buffer-visiting file)
11799 (find-file-noselect file)))
11800 (if (and arg (not (equal arg 3)))
11802 (pop-to-buffer-same-window nbuf)
11803 (goto-char (cond (pos)
11804 ((org-notes-order-reversed-p) (point-min))
11806 (org-show-context 'org-goto))
11809 (org-kill-new (buffer-substring region-start region-end))
11810 (org-save-markers-in-region region-start region-end))
11811 (org-copy-subtree 1 nil t))
11812 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11813 (find-file-noselect file)))
11814 (setq reversed (org-notes-order-reversed-p))
11815 (org-with-wide-buffer
11819 (setq level (org-get-valid-level (funcall outline-level) 1))
11822 (or (outline-next-heading) (point-max))
11823 (or (save-excursion (org-get-next-sibling))
11824 (org-end-of-subtree t t)
11828 (goto-char (point-max))
11829 (goto-char (point-min))
11830 (or (outline-next-heading) (goto-char (point-max)))))
11831 (unless (bolp) (newline))
11832 (org-paste-subtree level nil nil t)
11833 (when org-log-refile
11834 (org-add-log-setup 'refile nil nil org-log-refile)
11835 (unless (eq org-log-refile 'note)
11836 (save-excursion (org-add-log-note))))
11837 (and org-auto-align-tags
11838 (let ((org-loop-over-headlines-in-active-region nil))
11839 (org-set-tags nil t)))
11840 (let ((bookmark-name (plist-get org-bookmark-names-plist
11842 (when bookmark-name
11843 (with-demoted-errors
11844 (bookmark-set bookmark-name))))
11845 ;; If we are refiling for capture, make sure that the
11846 ;; last-capture pointers point here
11847 (when (bound-and-true-p org-capture-is-refiling)
11848 (let ((bookmark-name (plist-get org-bookmark-names-plist
11849 :last-capture-marker)))
11850 (when bookmark-name
11851 (with-demoted-errors
11852 (bookmark-set bookmark-name))))
11853 (move-marker org-capture-last-stored-marker (point)))
11854 (when (fboundp 'deactivate-mark) (deactivate-mark))
11855 (run-hooks 'org-after-refile-insert-hook)))
11856 (unless org-refile-keep
11858 (delete-region (point) (+ (point) (- region-end region-start)))
11860 (and (org-back-to-heading t) (point))
11861 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11862 (when (featurep 'org-inlinetask)
11863 (org-inlinetask-remove-END-maybe))
11864 (setq org-markers-to-move nil)
11865 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11867 (defun org-refile-goto-last-stored ()
11868 "Go to the location where the last refile was stored."
11870 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11871 (message "This is the location of the last refile"))
11873 (defun org-refile--get-location (refloc tbl)
11874 "When user refile to REFLOC, find the associated target in TBL.
11875 Also check `org-refile-target-table'."
11879 (lambda (r) (or (assoc r tbl)
11880 (assoc r org-refile-target-table)))
11881 (list (replace-regexp-in-string "/$" "" refloc)
11882 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11884 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11885 "Prompt the user for a refile location, using PROMPT.
11886 PROMPT should not be suffixed with a colon and a space, because
11887 this function appends the default value from
11888 `org-refile-history' automatically, if that is not empty."
11889 (let ((org-refile-targets org-refile-targets)
11890 (org-refile-use-outline-path org-refile-use-outline-path))
11891 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11892 (unless org-refile-target-table
11893 (user-error "No refile targets"))
11894 (let* ((cbuf (current-buffer))
11895 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11896 (cfunc (if (and org-refile-use-outline-path
11897 org-outline-path-complete-in-steps)
11898 #'org-olpath-completing-read
11899 #'completing-read))
11900 (extra (if org-refile-use-outline-path "/" ""))
11901 (cbnex (concat (buffer-name) extra))
11902 (filename (and cfn (expand-file-name cfn)))
11905 (if (and (not (member org-refile-use-outline-path
11906 '(file full-file-path)))
11907 (not (equal filename (nth 1 x))))
11908 (cons (concat (car x) extra " ("
11909 (file-name-nondirectory (nth 1 x)) ")")
11911 (cons (concat (car x) extra) (cdr x))))
11912 org-refile-target-table))
11913 (completion-ignore-case t)
11915 (prompt (concat prompt
11916 (or (and (car org-refile-history)
11917 (concat " (default " (car org-refile-history) ")"))
11918 (and (assoc cbnex tbl) (setq cdef cbnex)
11919 (concat " (default " cbnex ")"))) ": "))
11920 pa answ parent-target child parent old-hist)
11921 (setq old-hist org-refile-history)
11922 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11923 nil 'org-refile-history (or cdef (car org-refile-history))))
11924 (if (setq pa (org-refile--get-location answ tbl))
11926 (org-refile-check-position pa)
11927 (when (or (not org-refile-history)
11928 (not (eq old-hist org-refile-history))
11929 (not (equal (car pa) (car org-refile-history))))
11930 (setq org-refile-history
11931 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11933 (cdr org-refile-history))))
11934 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11935 (pop org-refile-history)))
11937 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11939 (setq parent (match-string 1 answ)
11940 child (match-string 2 answ))
11941 (setq parent-target (org-refile--get-location parent tbl))
11942 (when (and parent-target
11943 (or (eq new-nodes t)
11944 (and (eq new-nodes 'confirm)
11945 (y-or-n-p (format "Create new node \"%s\"? "
11947 (org-refile-new-child parent-target child)))
11948 (user-error "Invalid target location")))))
11950 (declare-function org-string-nw-p "org-macs" (s))
11951 (defun org-refile-check-position (refile-pointer)
11952 "Check if the refile pointer matches the headline to which it points."
11953 (let* ((file (nth 1 refile-pointer))
11954 (re (nth 2 refile-pointer))
11955 (pos (nth 3 refile-pointer))
11957 (if (and (not (markerp pos)) (not file))
11958 (user-error "Please indicate a target file in the refile path")
11959 (when (org-string-nw-p re)
11960 (setq buffer (if (markerp pos)
11961 (marker-buffer pos)
11962 (or (find-buffer-visiting file)
11963 (find-file-noselect file))))
11964 (with-current-buffer buffer
11965 (org-with-wide-buffer
11967 (beginning-of-line 1)
11968 (unless (looking-at-p re)
11969 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11971 (defun org-refile-new-child (parent-target child)
11972 "Use refile target PARENT-TARGET to add new CHILD below it."
11973 (unless parent-target
11974 (error "Cannot find parent for new node"))
11975 (let ((file (nth 1 parent-target))
11976 (pos (nth 3 parent-target))
11978 (with-current-buffer (or (find-buffer-visiting file)
11979 (find-file-noselect file))
11980 (org-with-wide-buffer
11983 (goto-char (point-max))
11984 (unless (bolp) (newline)))
11985 (when (looking-at org-outline-regexp)
11986 (setq level (funcall outline-level))
11987 (org-end-of-subtree t t))
11988 (org-back-over-empty-lines)
11989 (insert "\n" (make-string
11990 (if pos (org-get-valid-level level 1) 1) ?*)
11992 (beginning-of-line 0)
11993 (list (concat (car parent-target) "/" child) file "" (point))))))
11995 (defun org-olpath-completing-read (prompt collection &rest args)
11996 "Read an outline path like a file name."
11997 (let ((thetable collection))
11998 (apply #'completing-read
12000 (lambda (string predicate &optional flag)
12002 ((eq flag nil) (try-completion string thetable))
12004 (let ((l (length string)))
12005 (mapcar (lambda (x)
12006 (let ((r (substring x l))
12007 (f (if (string-match " ([^)]*)$" x)
12010 (if (string-match "/" r)
12011 (concat string (substring r 0 (match-end 0)) f)
12013 (all-completions string thetable predicate))))
12015 ((eq flag 'lambda) (assoc string thetable))))
12018 ;;;; Dynamic blocks
12020 (defun org-find-dblock (name)
12021 "Find the first dynamic block with name NAME in the buffer.
12022 If not found, stay at current position and return nil."
12023 (let ((case-fold-search t) pos)
12025 (goto-char (point-min))
12026 (setq pos (and (re-search-forward
12027 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12028 (match-beginning 0))))
12029 (when pos (goto-char pos))
12032 (defun org-create-dblock (plist)
12033 "Create a dynamic block section, with parameters taken from PLIST.
12034 PLIST must contain a :name entry which is used as the name of the block."
12035 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12038 (let ((col (current-column))
12039 (name (plist-get plist :name)))
12040 (insert "#+BEGIN: " name)
12042 (if (eq (car plist) :name)
12043 (setq plist (cddr plist))
12044 (insert " " (prin1-to-string (pop plist)))))
12045 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12046 (beginning-of-line -2)))
12048 (defun org-prepare-dblock ()
12049 "Prepare dynamic block for refresh.
12050 This empties the block, puts the cursor at the insert position and returns
12051 the property list including an extra property :name with the block name."
12052 (unless (looking-at org-dblock-start-re)
12053 (user-error "Not at a dynamic block"))
12054 (let* ((begdel (1+ (match-end 0)))
12055 (name (org-no-properties (match-string 1)))
12056 (params (append (list :name name)
12057 (read (concat "(" (match-string 3) ")")))))
12059 (beginning-of-line 1)
12060 (skip-chars-forward " \t")
12061 (setq params (plist-put params :indentation-column (current-column))))
12062 (unless (re-search-forward org-dblock-end-re nil t)
12063 (error "Dynamic block not terminated"))
12066 (list :content (buffer-substring
12067 begdel (match-beginning 0)))))
12068 (delete-region begdel (match-beginning 0))
12073 (defun org-map-dblocks (&optional command)
12074 "Apply COMMAND to all dynamic blocks in the current buffer.
12075 If COMMAND is not given, use `org-update-dblock'."
12076 (let ((cmd (or command 'org-update-dblock)))
12078 (goto-char (point-min))
12079 (while (re-search-forward org-dblock-start-re nil t)
12080 (goto-char (match-beginning 0))
12082 (condition-case nil
12084 (error (message "Error during update of dynamic block"))))
12085 (unless (re-search-forward org-dblock-end-re nil t)
12086 (error "Dynamic block not terminated"))))))
12088 (defun org-dblock-update (&optional arg)
12089 "User command for updating dynamic blocks.
12090 Update the dynamic block at point. With prefix ARG, update all dynamic
12091 blocks in the buffer."
12094 (org-update-all-dblocks)
12095 (or (looking-at org-dblock-start-re)
12096 (org-beginning-of-dblock))
12097 (org-update-dblock)))
12099 (defun org-update-dblock ()
12100 "Update the dynamic block at point.
12101 This means to empty the block, parse for parameters and then call
12102 the correct writing function."
12105 (let* ((win (selected-window))
12107 (line (org-current-line))
12108 (params (org-prepare-dblock))
12109 (name (plist-get params :name))
12110 (indent (plist-get params :indentation-column))
12111 (cmd (intern (concat "org-dblock-write:" name))))
12112 (message "Updating dynamic block `%s' at line %d..." name line)
12113 (funcall cmd params)
12114 (message "Updating dynamic block `%s' at line %d...done" name line)
12116 (when (and indent (> indent 0))
12117 (setq indent (make-string indent ?\ ))
12119 (select-window win)
12120 (org-beginning-of-dblock)
12122 (while (not (looking-at org-dblock-end-re))
12124 (beginning-of-line 2))
12125 (when (looking-at org-dblock-end-re)
12126 (and (looking-at "[ \t]+")
12127 (replace-match ""))
12128 (insert indent)))))))
12130 (defun org-beginning-of-dblock ()
12131 "Find the beginning of the dynamic block at point.
12132 Error if there is no such block at point."
12133 (let ((pos (point))
12136 (if (and (re-search-backward org-dblock-start-re nil t)
12137 (setq beg (match-beginning 0))
12138 (re-search-forward org-dblock-end-re nil t)
12139 (> (match-end 0) pos))
12142 (error "Not in a dynamic block"))))
12144 (defun org-update-all-dblocks ()
12145 "Update all dynamic blocks in the buffer.
12146 This function can be used in a hook."
12148 (when (derived-mode-p 'org-mode)
12149 (org-map-dblocks 'org-update-dblock)))
12154 (declare-function org-export-backend-options "ox" (cl-x) t)
12155 (defun org-get-export-keywords ()
12156 "Return a list of all currently understood export keywords.
12157 Export keywords include options, block names, attributes and
12158 keywords relative to each registered export back-end."
12161 (bound-and-true-p org-export-registered-backends)
12162 (delq nil keywords))
12163 ;; Back-end name (for keywords, like #+LATEX:)
12164 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12165 (dolist (option-entry (org-export-backend-options backend))
12166 ;; Back-end options.
12167 (push (nth 1 option-entry) keywords)))))
12169 (defconst org-options-keywords
12170 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12171 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12172 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12173 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12174 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12176 (defcustom org-structure-template-alist
12177 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12178 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12179 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12180 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12181 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12182 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12183 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12184 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12186 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12188 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12191 ("I" "#+INCLUDE: %file ?"))
12192 "Structure completion elements.
12193 This is a list of abbreviation keys and values. The value gets inserted
12194 if you type `<' followed by the key and then press the completion key,
12195 usually `TAB'. %file will be replaced by a file name after prompting
12196 for the file using completion. The cursor will be placed at the position
12197 of the `?' in the template.
12198 There are two templates for each key, the first uses the original Org syntax,
12199 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12200 the default when the /org-mtags.el/ module has been loaded. See also the
12201 variable `org-mtags-prefer-muse-templates'."
12202 :group 'org-edit-structure
12205 (string :tag "Key")
12206 (string :tag "Template")))
12208 :package-version '(Org . "8.3"))
12210 (defun org-try-structure-completion ()
12211 "Try to complete a structure template before point.
12212 This looks for strings like \"<e\" on an otherwise empty line and
12214 (let ((l (buffer-substring (point-at-bol) (point)))
12216 (when (and (looking-at "[ \t]*$")
12217 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12218 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12219 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12220 (match-beginning 1)) a)
12223 (defun org-complete-expand-structure-template (start cell)
12224 "Expand a structure template."
12225 (let ((rpl (nth 1 cell))
12227 (delete-region start (point))
12228 (when (string-match "\\`[ \t]*#\\+" rpl)
12231 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12232 (setq ind (buffer-substring (point-at-bol) (point))))
12234 (setq start (point))
12235 (when (string-match "%file" rpl)
12236 (setq rpl (replace-match
12240 (abbreviate-file-name (read-file-name "Include file: ")))
12243 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12244 (concat "\n" ind)))
12246 (when (re-search-backward "\\?" start t) (delete-char 1))))
12248 ;;;; TODO, DEADLINE, Comments
12250 (defun org-toggle-comment ()
12251 "Change the COMMENT state of an entry."
12254 (org-back-to-heading)
12255 (let ((case-fold-search nil))
12256 (looking-at org-complex-heading-regexp))
12257 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12258 (skip-chars-forward " \t")
12259 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12260 (if (org-in-commented-heading-p t)
12261 (delete-region (point)
12262 (progn (search-forward " " (line-end-position) 'move)
12263 (skip-chars-forward " \t")
12265 (insert org-comment-string)
12266 (unless (eolp) (insert " ")))))
12268 (defvar org-last-todo-state-is-todo nil
12269 "This is non-nil when the last TODO state change led to a TODO state.
12270 If the last change removed the TODO tag or switched to DONE, then
12273 (defvar org-setting-tags nil) ; dynamically skipped
12275 (defvar org-todo-setup-filter-hook nil
12276 "Hook for functions that pre-filter todo specs.
12277 Each function takes a todo spec and returns either nil or the spec
12278 transformed into canonical form." )
12280 (defvar org-todo-get-default-hook nil
12281 "Hook for functions that get a default item for todo.
12282 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12283 nil or a string to be used for the todo mark." )
12285 (defvar org-agenda-headline-snapshot-before-repeat)
12287 (defun org-current-effective-time ()
12288 "Return current time adjusted for `org-extend-today-until' variable."
12289 (let* ((ct (org-current-time))
12290 (dct (decode-time ct))
12293 (org-use-last-clock-out-time-as-effective-time
12294 (or (org-clock-get-last-clock-out-time) ct))
12295 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12296 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12300 (defun org-todo-yesterday (&optional arg)
12301 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12303 (if (eq major-mode 'org-agenda-mode)
12304 (apply 'org-agenda-todo-yesterday arg)
12305 (let* ((org-use-effective-time t)
12306 (hour (nth 2 (decode-time (org-current-time))))
12307 (org-extend-today-until (1+ hour)))
12310 (defvar org-block-entry-blocking ""
12311 "First entry preventing the TODO state change.")
12313 (defun org-cancel-repeater ()
12314 "Cancel a repeater by setting its numeric value to zero."
12317 (org-back-to-heading t)
12318 (let ((bound1 (point))
12319 (bound0 (save-excursion (outline-next-heading) (point))))
12320 (when (and (re-search-forward
12321 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12322 org-deadline-time-regexp "\\)\\|\\("
12323 org-ts-regexp "\\)")
12325 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12327 (replace-match "0" t nil nil 1)))))
12330 (defvar org-blocked-by-checkboxes)
12331 (defun org-todo (&optional arg)
12332 "Change the TODO state of an item.
12334 The state of an item is given by a keyword at the start of the heading,
12336 *** TODO Write paper
12339 The different keywords are specified in the variable `org-todo-keywords'.
12340 By default the available states are \"TODO\" and \"DONE\". So, for this
12341 example: when the item starts with TODO, it is changed to DONE.
12342 When it starts with DONE, the DONE is removed. And when neither TODO nor
12343 DONE are present, add TODO at the beginning of the heading.
12345 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12347 With numeric prefix ARG, switch to that state.
12348 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12350 keywords (nextset).
12351 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12352 prefix, circumvent any state blocking.
12353 With a numeric prefix arg of 0, inhibit note taking for the change.
12354 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12356 When called through ELisp, arg is also interpreted in the following way:
12357 `none' -> empty state
12358 \"\" -> switch to empty state
12359 `done' -> switch to DONE
12360 `nextset' -> switch to the next set of keywords
12361 `previousset' -> switch to the previous set of keywords
12362 \"WAITING\" -> switch to the specified keyword, but only if it
12363 really is a member of `org-todo-keywords'."
12365 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12366 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12367 'region-start-level 'region))
12368 org-loop-over-headlines-in-active-region)
12371 org-loop-over-headlines-in-active-region
12372 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12373 (when (equal arg '(16)) (setq arg 'nextset))
12374 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12375 (let ((org-blocker-hook org-blocker-hook)
12378 (when (equal arg '(64))
12379 (setq arg nil org-blocker-hook nil))
12380 (when (and org-blocker-hook
12381 (or org-inhibit-blocking
12382 (org-entry-get nil "NOBLOCKING")))
12383 (setq org-blocker-hook nil))
12386 (org-back-to-heading t)
12387 (when (org-in-commented-heading-p t)
12388 (org-toggle-comment)
12390 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12391 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12392 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12393 (let* ((match-data (match-data))
12394 (startpos (copy-marker (line-beginning-position)))
12395 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12396 (org-log-done org-log-done)
12397 (org-log-repeat org-log-repeat)
12398 (org-todo-log-states org-todo-log-states)
12399 (org-inhibit-logging
12401 (progn (setq arg nil) 'note) org-inhibit-logging))
12402 (this (match-string 1))
12403 (hl-pos (match-beginning 0))
12404 (head (org-get-todo-sequence-head this))
12405 (ass (assoc head org-todo-kwd-alist))
12406 (interpret (nth 1 ass))
12407 (done-word (nth 3 ass))
12408 (final-done-word (nth 4 ass))
12409 (org-last-state (or this ""))
12410 (completion-ignore-case t)
12411 (member (member this org-todo-keywords-1))
12412 (tail (cdr member))
12414 ((and org-todo-key-trigger
12415 (or (and (equal arg '(4))
12416 (eq org-use-fast-todo-selection 'prefix))
12417 (and (not arg) org-use-fast-todo-selection
12418 (not (eq org-use-fast-todo-selection
12420 ;; Use fast selection.
12421 (org-fast-todo-selection))
12422 ((and (equal arg '(4))
12423 (or (not org-use-fast-todo-selection)
12424 (not org-todo-key-trigger)))
12425 ;; Read a state with completion.
12427 "State: " (mapcar #'list org-todo-keywords-1)
12431 (if tail (car tail) nil)
12432 (car org-todo-keywords-1)))
12434 (unless (equal member org-todo-keywords-1)
12436 (nth (- (length org-todo-keywords-1)
12438 org-todo-keywords-1)
12439 (org-last org-todo-keywords-1))))
12440 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12441 (setq arg nil))) ;hack to fall back to cycling
12443 ;; User or caller requests a specific state.
12445 ((equal arg "") nil)
12446 ((eq arg 'none) nil)
12447 ((eq arg 'done) (or done-word (car org-done-keywords)))
12449 (or (car (cdr (member head org-todo-heads)))
12450 (car org-todo-heads)))
12451 ((eq arg 'previousset)
12452 (let ((org-todo-heads (reverse org-todo-heads)))
12453 (or (car (cdr (member head org-todo-heads)))
12454 (car org-todo-heads))))
12455 ((car (member arg org-todo-keywords-1)))
12457 (user-error "State `%s' not valid in this file" arg))
12458 ((nth (1- (prefix-numeric-value arg))
12459 org-todo-keywords-1))))
12460 ((null member) (or head (car org-todo-keywords-1)))
12461 ((equal this final-done-word) nil) ;-> make empty
12462 ((null tail) nil) ;-> first entry
12463 ((memq interpret '(type priority))
12464 (if (eq this-command last-command)
12466 (if (> (length tail) 0)
12467 (or done-word (car org-done-keywords))
12472 (run-hook-with-args-until-success
12473 'org-todo-get-default-hook org-state org-last-state)
12475 (next (if org-state (concat " " org-state " ") " "))
12476 (change-plist (list :type 'todo-state-change :from this :to org-state
12477 :position startpos))
12479 (when org-blocker-hook
12480 (let (org-blocked-by-checkboxes block-reason)
12481 (setq org-last-todo-state-is-todo
12482 (not (member this org-done-keywords)))
12483 (unless (save-excursion
12485 (org-with-wide-buffer
12486 (run-hook-with-args-until-failure
12487 'org-blocker-hook change-plist))))
12488 (setq block-reason (if org-blocked-by-checkboxes
12489 "contained checkboxes"
12490 (format "\"%s\"" org-block-entry-blocking)))
12491 (if (called-interactively-p 'interactive)
12492 (user-error "TODO state change from %s to %s blocked (by %s)"
12493 this org-state block-reason)
12495 (message "TODO state change from %s to %s blocked (by %s)"
12496 this org-state block-reason)
12497 (throw 'exit nil)))))
12498 (store-match-data match-data)
12499 (replace-match next t t)
12500 (cond ((equal this org-state)
12501 (message "TODO state was already %s" (org-trim next)))
12502 ((not (pos-visible-in-window-p hl-pos))
12503 (message "TODO state changed to %s" (org-trim next))))
12505 (setq head (org-get-todo-sequence-head org-state)
12506 ass (assoc head org-todo-kwd-alist)
12507 interpret (nth 1 ass)
12508 done-word (nth 3 ass)
12509 final-done-word (nth 4 ass)))
12510 (when (memq arg '(nextset previousset))
12511 (message "Keyword-Set %d/%d: %s"
12512 (- (length org-todo-sets) -1
12513 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12514 (length org-todo-sets)
12515 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12516 (setq org-last-todo-state-is-todo
12517 (not (member org-state org-done-keywords)))
12518 (setq now-done-p (and (member org-state org-done-keywords)
12519 (not (member this org-done-keywords))))
12520 (and logging (org-local-logging logging))
12521 (when (and (or org-todo-log-states org-log-done)
12522 (not (eq org-inhibit-logging t))
12523 (not (memq arg '(nextset previousset))))
12524 ;; We need to look at recording a time and note.
12525 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12526 (nth 2 (assoc this org-todo-log-states))))
12527 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12528 (setq dolog 'time))
12529 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12531 (member org-state org-not-done-keywords)
12532 (not (member this org-not-done-keywords))))
12533 ;; This is now a todo state and was not one before
12534 ;; If there was a CLOSED time stamp, get rid of it.
12535 (org-add-planning-info nil nil 'closed))
12536 (when (and now-done-p org-log-done)
12537 ;; It is now done, and it was not done before.
12538 (org-add-planning-info 'closed (org-current-effective-time))
12539 (when (and (not dolog) (eq 'note org-log-done))
12540 (org-add-log-setup 'done org-state this 'note)))
12541 (when (and org-state dolog)
12542 ;; This is a non-nil state, and we need to log it.
12543 (org-add-log-setup 'state org-state this dolog)))
12544 ;; Fixup tag positioning.
12545 (org-todo-trigger-tag-changes org-state)
12546 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12547 (when org-provide-todo-statistics
12548 (org-update-parent-todo-statistics))
12549 (run-hooks 'org-after-todo-state-change-hook)
12550 (when (and arg (not (member org-state org-done-keywords)))
12551 (setq head (org-get-todo-sequence-head org-state)))
12552 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12553 ;; Do we need to trigger a repeat?
12555 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12556 ;; This is for the agenda, take a snapshot of the headline.
12558 (setq org-agenda-headline-snapshot-before-repeat
12559 (org-get-heading))))
12560 (org-auto-repeat-maybe org-state))
12561 ;; Fixup cursor location if close to the keyword.
12562 (when (and (outline-on-heading-p)
12564 (save-excursion (beginning-of-line 1)
12565 (looking-at org-todo-line-regexp))
12566 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12567 (goto-char (or (match-end 2) (match-end 1)))
12568 (and (looking-at " ") (just-one-space)))
12569 (when org-trigger-hook
12571 (run-hook-with-args 'org-trigger-hook change-plist)))
12572 (when commentp (org-toggle-comment))))))))
12574 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12575 "Block turning an entry into a TODO, using the hierarchy.
12576 This checks whether the current task should be blocked from state
12577 changes. Such blocking occurs when:
12579 1. The task has children which are not all in a completed state.
12581 2. A task has a parent with the property :ORDERED:, and there
12582 are siblings prior to the current task with incomplete
12585 3. The parent of the task is blocked because it has siblings that should
12586 be done first, or is child of a block grandparent TODO entry."
12588 (if (not org-enforce-todo-dependencies)
12589 t ; if locally turned off don't block
12591 ;; If this is not a todo state change, or if this entry is already DONE,
12593 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12594 (member (plist-get change-plist :from)
12595 (cons 'done org-done-keywords))
12596 (member (plist-get change-plist :to)
12597 (cons 'todo org-not-done-keywords))
12598 (not (plist-get change-plist :to)))
12599 (throw 'dont-block t))
12600 ;; If this task has children, and any are undone, it's blocked
12602 (org-back-to-heading t)
12603 (let ((this-level (funcall outline-level)))
12604 (outline-next-heading)
12605 (let ((child-level (funcall outline-level)))
12606 (while (and (not (eobp))
12607 (> child-level this-level))
12608 ;; this todo has children, check whether they are all
12610 (when (and (not (org-entry-is-done-p))
12611 (org-entry-is-todo-p))
12612 (setq org-block-entry-blocking (org-get-heading))
12613 (throw 'dont-block nil))
12614 (outline-next-heading)
12615 (setq child-level (funcall outline-level))))))
12616 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12617 ;; any previous siblings are undone, it's blocked
12619 (org-back-to-heading t)
12620 (let* ((pos (point))
12621 (parent-pos (and (org-up-heading-safe) (point)))
12622 (case-fold-search nil))
12623 (unless parent-pos (throw 'dont-block t)) ; no parent
12624 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12626 (re-search-forward org-not-done-heading-regexp pos t))
12627 (setq org-block-entry-blocking (match-string 0))
12628 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12629 ;; Search further up the hierarchy, to see if an ancestor is blocked
12631 (goto-char parent-pos)
12632 (unless (looking-at org-not-done-heading-regexp)
12633 (throw 'dont-block t)) ; do not block, parent is not a TODO
12635 (setq parent-pos (and (org-up-heading-safe) (point)))
12636 (unless parent-pos (throw 'dont-block t)) ; no parent
12637 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12639 (re-search-forward org-not-done-heading-regexp pos t)
12640 (setq org-block-entry-blocking (org-get-heading)))
12641 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12643 (defcustom org-track-ordered-property-with-tag nil
12644 "Should the ORDERED property also be shown as a tag?
12645 The ORDERED property decides if an entry should require subtasks to be
12646 completed in sequence. Since a property is not very visible, setting
12647 this option means that toggling the ORDERED property with the command
12648 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12649 not relevant for the behavior, but it makes things more visible.
12651 Note that toggling the tag with tags commands will not change the property
12652 and therefore not influence behavior!
12654 This can be t, meaning the tag ORDERED should be used, It can also be a
12655 string to select a different tag for this task."
12658 (const :tag "No tracking" nil)
12659 (const :tag "Track with ORDERED tag" t)
12660 (string :tag "Use other tag")))
12662 (defun org-toggle-ordered-property ()
12663 "Toggle the ORDERED property of the current entry.
12664 For better visibility, you can track the value of this property with a tag.
12665 See variable `org-track-ordered-property-with-tag'."
12667 (let* ((t1 org-track-ordered-property-with-tag)
12668 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12670 (org-back-to-heading)
12671 (if (org-entry-get nil "ORDERED")
12673 (org-delete-property "ORDERED")
12674 (and tag (org-toggle-tag tag 'off))
12675 (message "Subtasks can be completed in arbitrary order"))
12676 (org-entry-put nil "ORDERED" "t")
12677 (and tag (org-toggle-tag tag 'on))
12678 (message "Subtasks must be completed in sequence")))))
12680 (defun org-block-todo-from-checkboxes (change-plist)
12681 "Block turning an entry into a TODO, using checkboxes.
12682 This checks whether the current task should be blocked from state
12683 changes because there are unchecked boxes in this entry."
12684 (if (not org-enforce-todo-checkbox-dependencies)
12685 t ; if locally turned off don't block
12687 ;; If this is not a todo state change, or if this entry is already DONE,
12689 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12690 (member (plist-get change-plist :from)
12691 (cons 'done org-done-keywords))
12692 (member (plist-get change-plist :to)
12693 (cons 'todo org-not-done-keywords))
12694 (not (plist-get change-plist :to)))
12695 (throw 'dont-block t))
12696 ;; If this task has checkboxes that are not checked, it's blocked
12698 (org-back-to-heading t)
12699 (let ((beg (point)) end)
12700 (outline-next-heading)
12703 (when (org-list-search-forward
12704 (concat (org-item-beginning-re)
12705 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12708 (when (boundp 'org-blocked-by-checkboxes)
12709 (setq org-blocked-by-checkboxes t))
12710 (throw 'dont-block nil))))
12711 t))) ; do not block
12713 (defun org-entry-blocked-p ()
12714 "Non-nil if entry at point is blocked."
12715 (and (not (org-entry-get nil "NOBLOCKING"))
12716 (member (org-entry-get nil "TODO") org-not-done-keywords)
12717 (not (run-hook-with-args-until-failure
12719 (list :type 'todo-state-change
12724 (defun org-update-statistics-cookies (all)
12725 "Update the statistics cookie, either from TODO or from checkboxes.
12726 This should be called with the cursor in a line with a statistics
12727 cookie. When called with a \\[universal-argument] prefix, update
12728 all statistics cookies in the buffer."
12732 (org-update-checkbox-count 'all)
12733 (org-map-entries 'org-update-parent-todo-statistics))
12734 (if (not (org-at-heading-p))
12735 (org-update-checkbox-count)
12736 (let ((pos (point-marker))
12738 (ignore-errors (org-back-to-heading t))
12739 (if (not (org-at-heading-p))
12740 (org-update-checkbox-count)
12741 (setq l1 (org-outline-level))
12742 (setq end (save-excursion
12743 (outline-next-heading)
12744 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12746 (if (and (save-excursion
12748 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12749 (not (save-excursion (re-search-forward
12750 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12751 (org-update-checkbox-count)
12752 (if (and l2 (> l2 l1))
12755 (org-update-parent-todo-statistics))
12757 (beginning-of-line 1)
12758 (while (re-search-forward
12759 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12761 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12763 (move-marker pos nil)))))
12765 (defvar org-entry-property-inherited-from) ;; defined below
12766 (defun org-update-parent-todo-statistics ()
12767 "Update any statistics cookie in the parent of the current headline.
12768 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12769 the entire subtree and this will travel up the hierarchy and update
12770 statistics everywhere."
12771 (let* ((prop (save-excursion (org-up-heading-safe)
12772 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12773 (recursive (or (not org-hierarchical-todo-statistics)
12774 (and prop (string-match "\\<recursive\\>" prop))))
12775 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12778 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12779 level ltoggle l1 new ndel
12780 (cnt-all 0) (cnt-done 0) is-percent kwd
12781 checkbox-beg cookie-present)
12784 (beginning-of-line 1)
12785 (setq ltoggle (funcall outline-level))
12786 ;; Three situations are to consider:
12788 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12789 ;; to the top-level ancestor on the headline;
12791 ;; 2. If parent has "recursive" property, repeat up to the
12792 ;; headline setting that property, taking inheritance into
12795 ;; 3. Else, move up to direct parent and proceed only once.
12796 (while (and (setq level (org-up-heading-safe))
12797 (or recursive first)
12799 (setq first nil cookie-present nil)
12803 (downcase (or (org-entry-get nil "COOKIE_DATA")
12806 (while (re-search-forward box-re (point-at-eol) t)
12807 (setq cnt-all 0 cnt-done 0 cookie-present t)
12808 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12810 (unless (outline-next-heading) (throw 'exit nil))
12811 (while (and (looking-at org-complex-heading-regexp)
12812 (> (setq l1 (length (match-string 1))) level))
12813 (setq kwd (and (or recursive (= l1 ltoggle))
12815 (if (or (eq org-provide-todo-statistics 'all-headlines)
12816 (and (eq org-provide-todo-statistics t)
12817 (or (member kwd org-done-keywords)))
12818 (and (listp org-provide-todo-statistics)
12819 (stringp (car org-provide-todo-statistics))
12820 (or (member kwd org-provide-todo-statistics)
12821 (member kwd org-done-keywords)))
12822 (and (listp org-provide-todo-statistics)
12823 (listp (car org-provide-todo-statistics))
12824 (or (member kwd (car org-provide-todo-statistics))
12825 (and (member kwd org-done-keywords)
12826 (member kwd (cadr org-provide-todo-statistics))))))
12827 (setq cnt-all (1+ cnt-all))
12828 (and (eq org-provide-todo-statistics t)
12830 (setq cnt-all (1+ cnt-all))))
12831 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12832 (member kwd org-done-keywords))
12833 (and (listp org-provide-todo-statistics)
12834 (listp (car org-provide-todo-statistics))
12835 (member kwd org-done-keywords)
12836 (member kwd (cadr org-provide-todo-statistics)))
12837 (and (listp org-provide-todo-statistics)
12838 (stringp (car org-provide-todo-statistics))
12839 (member kwd org-done-keywords)))
12840 (setq cnt-done (1+ cnt-done)))
12841 (outline-next-heading)))
12844 (format "[%d%%]" (floor (* 100.0 cnt-done)
12846 (format "[%d/%d]" cnt-done cnt-all))
12847 ndel (- (match-end 0) checkbox-beg))
12848 (goto-char checkbox-beg)
12850 (delete-region (point) (+ (point) ndel))
12851 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12852 (when cookie-present
12853 (run-hook-with-args 'org-after-todo-statistics-hook
12854 cnt-done (- cnt-all cnt-done))))))
12855 (run-hooks 'org-todo-statistics-hook)))
12857 (defvar org-after-todo-statistics-hook nil
12858 "Hook that is called after a TODO statistics cookie has been updated.
12859 Each function is called with two arguments: the number of not-done entries
12860 and the number of done entries.
12862 For example, the following function, when added to this hook, will switch
12863 an entry to DONE when all children are done, and back to TODO when new
12864 entries are set to a TODO status. Note that this hook is only called
12865 when there is a statistics cookie in the headline!
12867 (defun org-summary-todo (n-done n-not-done)
12868 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12869 (let (org-log-done org-log-states) ; turn off logging
12870 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12873 (defvar org-todo-statistics-hook nil
12874 "Hook that is run whenever Org thinks TODO statistics should be updated.
12875 This hook runs even if there is no statistics cookie present, in which case
12876 `org-after-todo-statistics-hook' would not run.")
12878 (defun org-todo-trigger-tag-changes (state)
12879 "Apply the changes defined in `org-todo-state-tags-triggers'."
12880 (let ((l org-todo-state-tags-triggers)
12882 (when (or (not state) (equal state ""))
12883 (setq changes (append changes (cdr (assoc "" l)))))
12884 (when (and (stringp state) (> (length state) 0))
12885 (setq changes (append changes (cdr (assoc state l)))))
12886 (when (member state org-not-done-keywords)
12887 (setq changes (append changes (cdr (assq 'todo l)))))
12888 (when (member state org-done-keywords)
12889 (setq changes (append changes (cdr (assq 'done l)))))
12890 (dolist (c changes)
12891 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12893 (defun org-local-logging (value)
12894 "Get logging settings from a property VALUE."
12895 ;; Directly set the variables, they are already local.
12896 (setq org-log-done nil
12898 org-todo-log-states nil)
12899 (dolist (w (split-string value))
12902 ((setq a (assoc w org-startup-options))
12903 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12904 (set (nth 1 a) (nth 2 a))))
12905 ((setq a (org-extract-log-state-settings w))
12906 (and (member (car a) org-todo-keywords-1)
12907 (push a org-todo-log-states)))))))
12909 (defun org-get-todo-sequence-head (kwd)
12910 "Return the head of the TODO sequence to which KWD belongs.
12911 If KWD is not set, check if there is a text property remembering the
12916 (or (get-text-property (point-at-bol) 'org-todo-head)
12918 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12919 nil (point-at-eol)))
12920 (get-text-property p 'org-todo-head))))
12921 ((not (member kwd org-todo-keywords-1))
12922 (car org-todo-keywords-1))
12923 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12925 (defun org-fast-todo-selection ()
12926 "Fast TODO keyword selection with single keys.
12927 Returns the new TODO keyword, or nil if no state change should occur."
12928 (let* ((fulltable org-todo-key-alist)
12929 (done-keywords org-done-keywords) ;; needed for the faces.
12930 (maxlen (apply 'max (mapcar
12932 (if (stringp (car x)) (string-width (car x)) 0))
12935 (fwidth (+ maxlen 3 1 3))
12936 (ncol (/ (- (window-width) 4) fwidth))
12940 (save-window-excursion
12942 (set-buffer (get-buffer-create " *Org todo*"))
12943 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12945 (setq-local org-done-keywords done-keywords)
12946 (setq tbl fulltable cnt 0)
12947 (while (setq e (pop tbl))
12949 ((equal e '(:startgroup))
12950 (push '() groups) (setq ingroup t)
12955 ((equal e '(:endgroup))
12956 (setq ingroup nil cnt 0)
12958 ((equal e '(:newline))
12963 (while (equal (car tbl) '(:newline))
12965 (setq tbl (cdr tbl)))))
12967 (setq tg (car e) c (cdr e))
12968 (when ingroup (push tg (car groups)))
12969 (setq tg (org-add-props tg nil 'face
12970 (org-get-todo-face tg)))
12971 (when (and (= cnt 0) (not ingroup)) (insert " "))
12972 (insert "[" c "] " tg (make-string
12973 (- fwidth 4 (length tg)) ?\ ))
12974 (when (= (setq cnt (1+ cnt)) ncol)
12976 (when ingroup (insert " "))
12979 (goto-char (point-min))
12980 (unless expert (org-fit-window-to-buffer))
12981 (message "[a-z..]:Set [SPC]:clear")
12982 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12985 (and (= c ?q) (not (rassoc c fulltable))))
12986 (setq quit-flag t))
12988 ((setq e (rassoc c fulltable) tg (car e))
12990 (t (setq quit-flag t)))))))
12992 (defun org-entry-is-todo-p ()
12993 (member (org-get-todo-state) org-not-done-keywords))
12995 (defun org-entry-is-done-p ()
12996 (member (org-get-todo-state) org-done-keywords))
12998 (defun org-get-todo-state ()
12999 "Return the TODO keyword of the current subtree."
13001 (org-back-to-heading t)
13002 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13004 (match-string 2))))
13006 (defun org-at-date-range-p (&optional inactive-ok)
13007 "Non-nil if point is inside a date range.
13009 When optional argument INACTIVE-OK is non-nil, also consider
13010 inactive time ranges.
13012 When this function returns a non-nil value, match data is set
13013 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13018 (let ((pos (point)))
13019 (skip-chars-backward "^[<\r\n")
13020 (skip-chars-backward "<[")
13021 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13022 (>= (match-end 0) pos)
13024 (skip-chars-backward "^<[\r\n")
13025 (skip-chars-backward "<[")
13026 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13027 (>= (match-end 0) pos)
13031 (defun org-get-repeat (&optional timestamp)
13032 "Check if there is a time-stamp with repeater in this entry.
13034 Return the repeater, as a string, or nil. Also return nil when
13035 this function is called before first heading.
13037 When optional argument TIMESTAMP is a string, extract the
13038 repeater from there instead."
13041 (and (string-match org-repeat-re timestamp)
13042 (match-string-no-properties 1 timestamp)))
13043 ((org-before-first-heading-p) nil)
13046 (org-back-to-heading t)
13047 (let ((end (org-entry-end-position)))
13049 (while (re-search-forward org-repeat-re end t)
13050 (when (save-match-data (org-at-timestamp-p 'agenda))
13051 (throw :repeat (match-string-no-properties 1)))))))))))
13053 (defvar org-last-changed-timestamp)
13054 (defvar org-last-inserted-timestamp)
13055 (defvar org-log-post-message)
13056 (defvar org-log-note-purpose)
13057 (defvar org-log-note-how nil)
13058 (defvar org-log-note-extra)
13059 (defun org-auto-repeat-maybe (done-word)
13060 "Check if the current headline contains a repeated time-stamp.
13062 If yes, set TODO state back to what it was and change the base date
13063 of repeating deadline/scheduled time stamps to new date.
13065 This function is run automatically after each state change to a DONE state."
13066 (let* ((repeat (org-get-repeat))
13067 (aa (assoc org-last-state org-todo-kwd-alist))
13068 (interpret (nth 1 aa))
13070 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13071 (msg "Entry repeats: ")
13073 (org-todo-log-states nil)
13074 (end (copy-marker (org-entry-end-position))))
13076 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13077 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13078 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13079 org-todo-repeat-to-state)))
13081 ((and to-state (member to-state org-todo-keywords-1))
13083 ((eq interpret 'type) org-last-state)
13086 (org-back-to-heading t)
13087 (org-add-planning-info nil nil 'closed)
13088 ;; When `org-log-repeat' is non-nil or entry contains
13089 ;; a clock, set LAST_REPEAT property.
13090 (when (or org-log-repeat
13093 (while (re-search-forward org-clock-line-re end t)
13094 (when (org-at-clock-log-p) (throw :clock t))))))
13095 (org-entry-put nil "LAST_REPEAT" (format-time-string
13096 (org-time-stamp-format t t)
13098 (when org-log-repeat
13099 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13100 (memq 'org-add-log-note post-command-hook))
13101 ;; We are already setup for some record.
13102 (when (eq org-log-repeat 'note)
13103 ;; Make sure we take a note, not only a time stamp.
13104 (setq org-log-note-how 'note))
13105 ;; Set up for taking a record.
13106 (org-add-log-setup 'state
13107 (or done-word (car org-done-keywords))
13110 (let ((planning-re (regexp-opt
13111 (list org-scheduled-string org-deadline-string))))
13112 (while (re-search-forward org-ts-regexp end t)
13113 (let* ((ts (match-string 0))
13114 (planning? (org-at-planning-p))
13115 (type (if (not planning?) "Plain:"
13117 (re-search-backward
13118 planning-re (line-beginning-position) t)
13119 (match-string 0)))))
13121 ;; Ignore fake time-stamps (e.g., within comments).
13122 ((not (org-at-timestamp-p 'agenda)))
13123 ;; Time-stamps without a repeater are usually
13124 ;; skipped. However, a SCHEDULED time-stamp without
13125 ;; one is removed, as they are no longer relevant.
13126 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13128 (when (equal type org-scheduled-string)
13129 (org-remove-timestamp-with-keyword type)))
13131 (let ((n (string-to-number (match-string 2 ts)))
13132 (what (match-string 3 ts)))
13133 (when (equal what "w") (setq n (* n 7) what "d"))
13134 (when (and (equal what "h")
13135 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13138 "Cannot repeat in Repeat in %d hour(s) because no hour \
13141 ;; Preparation, see if we need to modify the start
13142 ;; date for the change.
13143 (when (match-end 1)
13144 (let ((time (save-match-data
13145 (org-time-string-to-time ts))))
13147 ((equal (match-string 1 ts) ".")
13148 ;; Shift starting date to today
13149 (org-timestamp-change
13150 (- (org-today) (time-to-days time))
13152 ((equal (match-string 1 ts) "+")
13153 (let ((nshiftmax 10)
13155 (while (or (= nshift 0)
13156 (not (time-less-p (current-time) time)))
13157 (when (= (cl-incf nshift) nshiftmax)
13159 (format "%d repeater intervals were not \
13160 enough to shift date past today. Continue? "
13162 (user-error "Abort")))
13163 (org-timestamp-change n (cdr (assoc what whata)))
13164 (org-in-regexp org-ts-regexp3)
13165 (setq ts (match-string 1))
13168 (org-time-string-to-time ts)))))
13169 (org-timestamp-change (- n) (cdr (assoc what whata)))
13170 ;; Rematch, so that we have everything in place
13171 ;; for the real shift.
13172 (org-in-regexp org-ts-regexp3)
13173 (setq ts (match-string 1))
13174 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13177 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13180 msg type " " org-last-changed-timestamp " "))))))))
13181 (setq org-log-post-message msg)
13182 (message "%s" msg))
13183 (set-marker end nil))))
13185 (defun org-show-todo-tree (arg)
13186 "Make a compact tree which shows all headlines marked with TODO.
13187 The tree will show the lines where the regexp matches, and all higher
13188 headlines above the match.
13189 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13190 With a numeric prefix N, construct a sparse tree for the Nth element
13191 of `org-todo-keywords-1'."
13193 (let ((case-fold-search nil)
13195 (cond ((null arg) org-not-done-regexp)
13198 (completing-read "Keyword (or KWD1|KWD2|...): "
13199 (mapcar #'list org-todo-keywords-1))))
13201 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13203 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13204 (regexp-quote (nth (1- (prefix-numeric-value arg))
13205 org-todo-keywords-1)))
13206 (t (user-error "Invalid prefix argument: %s" arg)))))
13207 (message "%d TODO entries found"
13208 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13210 (defun org--deadline-or-schedule (arg type time)
13211 "Insert DEADLINE or SCHEDULE information in current entry.
13212 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13213 `org-schedule' for information about ARG and TIME arguments."
13214 (let* ((deadline? (eq type 'deadline))
13215 (keyword (if deadline? org-deadline-string org-scheduled-string))
13216 (log (if deadline? org-log-redeadline org-log-reschedule))
13217 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13218 (old-date-time (and old-date (org-time-string-to-time old-date)))
13219 ;; Save repeater cookie from either TIME or current scheduled
13220 ;; time stamp. We are going to insert it back at the end of
13222 (repeater (or (and (org-string-nw-p time)
13223 ;; We use `org-repeat-re' because we need
13224 ;; to tell the difference between a real
13225 ;; repeater and a time delta, e.g. "+2d".
13226 (string-match org-repeat-re time)
13227 (match-string 1 time))
13228 (and (org-string-nw-p old-date)
13229 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13230 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13232 (match-string 1 old-date)))))
13235 (when (and old-date log)
13236 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13238 (org-remove-timestamp-with-keyword keyword)
13239 (message (if deadline? "Item no longer has a deadline."
13240 "Item is no longer scheduled.")))
13243 (org-back-to-heading t)
13244 (let ((regexp (if deadline? org-deadline-time-regexp
13245 org-scheduled-time-regexp)))
13246 (if (not (re-search-forward regexp (line-end-position 2) t))
13247 (user-error (if deadline? "No deadline information to update"
13248 "No scheduled information to update"))
13249 (let* ((rpl0 (match-string 1))
13250 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13251 (msg (if deadline? "Warn starting from" "Delay until")))
13256 (abs (- (time-to-days
13259 nil t nil msg old-date-time)))
13260 (time-to-days old-date-time))))
13263 (org-add-planning-info type time 'closed)
13264 (when (and old-date
13266 (not (equal old-date org-last-inserted-timestamp)))
13267 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13268 org-last-inserted-timestamp
13273 (org-back-to-heading t)
13274 (when (re-search-forward
13275 (concat keyword " " org-last-inserted-timestamp)
13276 (line-end-position 2)
13278 (goto-char (1- (match-end 0)))
13279 (insert " " repeater)
13280 (setq org-last-inserted-timestamp
13281 (concat (substring org-last-inserted-timestamp 0 -1)
13283 (substring org-last-inserted-timestamp -1))))))
13284 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13285 org-last-inserted-timestamp)))))
13287 (defun org-deadline (arg &optional time)
13288 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13289 With one universal prefix argument, remove any deadline from the item.
13290 With two universal prefix arguments, prompt for a warning delay.
13291 With argument TIME, set the deadline at the corresponding date. TIME
13292 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13294 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13296 (lambda () (org--deadline-or-schedule arg 'deadline time))
13298 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13299 'region-start-level
13301 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13302 (org--deadline-or-schedule arg 'deadline time)))
13304 (defun org-schedule (arg &optional time)
13305 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13306 With one universal prefix argument, remove any scheduling date from the item.
13307 With two universal prefix arguments, prompt for a delay cookie.
13308 With argument TIME, scheduled at the corresponding date. TIME can
13309 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13311 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13313 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13315 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13316 'region-start-level
13318 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13319 (org--deadline-or-schedule arg 'scheduled time)))
13321 (defun org-get-scheduled-time (pom &optional inherit)
13322 "Get the scheduled time as a time tuple, of a format suitable
13323 for calling org-schedule with, or if there is no scheduling,
13325 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13327 (apply 'encode-time (org-parse-time-string time)))))
13329 (defun org-get-deadline-time (pom &optional inherit)
13330 "Get the deadline as a time tuple, of a format suitable for
13331 calling org-deadline with, or if there is no scheduling, returns
13333 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13335 (apply 'encode-time (org-parse-time-string time)))))
13337 (defun org-remove-timestamp-with-keyword (keyword)
13338 "Remove all time stamps with KEYWORD in the current entry."
13339 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13342 (org-back-to-heading t)
13344 (outline-next-heading)
13345 (while (re-search-backward re beg t)
13347 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13348 (equal (char-before) ?\ ))
13349 (backward-delete-char 1)
13350 (when (string-match "^[ \t]*$" (buffer-substring
13351 (point-at-bol) (point-at-eol)))
13352 (delete-region (point-at-bol)
13353 (min (point-max) (1+ (point-at-eol))))))))))
13355 (defvar org-time-was-given) ; dynamically scoped parameter
13356 (defvar org-end-time-was-given) ; dynamically scoped parameter
13358 (defun org-at-planning-p ()
13359 "Non-nil when point is on a planning info line."
13360 ;; This is as accurate and faster than `org-element-at-point' since
13361 ;; planning info location is fixed in the section.
13362 (org-with-wide-buffer
13363 (beginning-of-line)
13364 (and (looking-at-p org-planning-line-re)
13367 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13368 (org-back-to-heading t)
13369 (org-with-limited-levels (org-back-to-heading t)))
13370 (line-beginning-position 2))))))
13372 (defun org-add-planning-info (what &optional time &rest remove)
13373 "Insert new timestamp with keyword in the planning line.
13374 WHAT indicates what kind of time stamp to add. It is a symbol
13375 among `closed', `deadline', `scheduled' and nil. TIME indicates
13376 the time to use. If none is given, the user is prompted for
13377 a date. REMOVE indicates what kind of entries to remove. An old
13378 WHAT entry will also be removed."
13379 (let (org-time-was-given org-end-time-was-given default-time default-input)
13381 (when (and (memq what '(scheduled deadline))
13383 (and (stringp time)
13384 (string-match "^[-+]+[0-9]" time))))
13385 ;; Try to get a default date/time from existing timestamp
13387 (org-back-to-heading t)
13388 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13389 (when (re-search-forward (if (eq what 'scheduled)
13390 org-scheduled-time-regexp
13391 org-deadline-time-regexp)
13393 (setq ts (match-string 1)
13394 default-time (apply 'encode-time (org-parse-time-string ts))
13395 default-input (and ts (org-get-compact-tod ts)))))))
13399 ;; This is a string (relative or absolute), set
13401 (apply #'encode-time
13402 (org-read-date-analyze
13403 time default-time (decode-time default-time)))
13404 ;; If necessary, get the time from the user
13405 (or time (org-read-date nil 'to-time nil nil
13406 default-time default-input)))))
13408 (org-with-wide-buffer
13409 (org-back-to-heading t)
13411 (unless (bolp) (insert "\n"))
13412 (cond ((looking-at-p org-planning-line-re)
13413 ;; Move to current indentation.
13414 (skip-chars-forward " \t")
13415 ;; Check if we have to remove something.
13416 (dolist (type (if what (cons what remove) remove))
13418 (when (re-search-forward
13420 (closed org-closed-time-regexp)
13421 (deadline org-deadline-time-regexp)
13422 (scheduled org-scheduled-time-regexp)
13424 (error "Invalid planning type: %s" type)))
13425 (line-end-position) t)
13426 ;; Delete until next keyword or end of line.
13428 (match-beginning 0)
13429 (if (re-search-forward org-keyword-time-not-clock-regexp
13430 (line-end-position)
13432 (match-beginning 0)
13433 (line-end-position))))))
13434 ;; If there is nothing more to add and no more keyword
13435 ;; is left, remove the line completely.
13436 (if (and (looking-at-p "[ \t]*$") (not what))
13437 (delete-region (line-beginning-position)
13438 (line-beginning-position 2))
13439 ;; If we removed last keyword, do not leave trailing
13440 ;; white space at the end of line.
13444 (unless (= (skip-chars-backward " \t" p) 0)
13445 (delete-region (point) (line-end-position)))))))
13446 ((not what) (throw 'exit nil)) ; Nothing to do.
13447 (t (insert-before-markers "\n")
13449 (when org-adapt-indentation
13450 (indent-to-column (1+ (org-outline-level))))))
13452 ;; Insert planning keyword.
13453 (insert (cl-case what
13454 (closed org-closed-string)
13455 (deadline org-deadline-string)
13456 (scheduled org-scheduled-string)
13457 (otherwise (error "Invalid planning type: %s" what)))
13459 ;; Insert associated timestamp.
13460 (let ((ts (org-insert-time-stamp
13462 (or org-time-was-given
13463 (and (eq what 'closed) org-log-done-with-time))
13465 nil nil (list org-end-time-was-given))))
13466 (unless (eolp) (insert " "))
13469 (defvar org-log-note-marker (make-marker)
13470 "Marker pointing at the entry where the note is to be inserted.")
13471 (defvar org-log-note-purpose nil)
13472 (defvar org-log-note-state nil)
13473 (defvar org-log-note-previous-state nil)
13474 (defvar org-log-note-extra nil)
13475 (defvar org-log-note-window-configuration nil)
13476 (defvar org-log-note-return-to (make-marker))
13477 (defvar org-log-note-effective-time nil
13478 "Remembered current time so that dynamically scoped
13479 `org-extend-today-until' affects timestamps in state change log")
13481 (defvar org-log-post-message nil
13482 "Message to be displayed after a log note has been stored.
13483 The auto-repeater uses this.")
13485 (defun org-add-note ()
13486 "Add a note to the current entry.
13487 This is done in the same way as adding a state change note."
13489 (org-add-log-setup 'note))
13491 (defun org-log-beginning (&optional create)
13492 "Return expected start of log notes in current entry.
13493 When optional argument CREATE is non-nil, the function creates
13494 a drawer to store notes, if necessary. Returned position ignores
13496 (org-with-wide-buffer
13497 (let ((drawer (org-log-into-drawer)))
13500 (org-end-of-meta-data)
13501 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13502 (end (if (org-at-heading-p) (point)
13503 (save-excursion (outline-next-heading) (point))))
13504 (case-fold-search t))
13506 ;; Try to find existing drawer.
13507 (while (re-search-forward regexp end t)
13508 (let ((element (org-element-at-point)))
13509 (when (eq (org-element-type element) 'drawer)
13510 (let ((cend (org-element-property :contents-end element)))
13511 (when (and (not org-log-states-order-reversed) cend)
13513 (throw 'exit nil))))
13514 ;; No drawer found. Create one, if permitted.
13516 (unless (bolp) (insert "\n"))
13517 (let ((beg (point)))
13518 (insert ":" drawer ":\n:END:\n")
13519 (org-indent-region beg (point)))
13520 (end-of-line -1)))))
13522 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13523 (skip-chars-forward " \t\n")
13524 (beginning-of-line)
13525 (unless org-log-states-order-reversed
13526 (org-skip-over-state-notes)
13527 (skip-chars-backward " \t\n")
13529 (if (bolp) (point) (line-beginning-position 2))))
13531 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13532 "Set up the post command hook to take a note.
13533 If this is about to TODO state change, the new state is expected in STATE.
13534 HOW is an indicator what kind of note should be created.
13535 EXTRA is additional text that will be inserted into the notes buffer."
13536 (move-marker org-log-note-marker (point))
13537 (setq org-log-note-purpose purpose
13538 org-log-note-state state
13539 org-log-note-previous-state prev-state
13540 org-log-note-how how
13541 org-log-note-extra extra
13542 org-log-note-effective-time (org-current-effective-time))
13543 (add-hook 'post-command-hook 'org-add-log-note 'append))
13545 (defun org-skip-over-state-notes ()
13546 "Skip past the list of State notes in an entry."
13547 (when (ignore-errors (goto-char (org-in-item-p)))
13548 (let* ((struct (org-list-struct))
13549 (prevs (org-list-prevs-alist struct))
13551 (concat "[ \t]*- +"
13552 (replace-regexp-in-string
13554 (org-replace-escapes
13555 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13556 `(("%d" . ,org-ts-regexp-inactive)
13557 ("%D" . ,org-ts-regexp)
13558 ("%s" . "\"\\S-+\"")
13559 ("%S" . "\"\\S-+\"")
13560 ("%t" . ,org-ts-regexp-inactive)
13561 ("%T" . ,org-ts-regexp)
13563 ("%U" . ".*?")))))))
13564 (while (looking-at-p regexp)
13565 (goto-char (or (org-list-get-next-item (point) struct prevs)
13566 (org-list-get-item-end (point) struct)))))))
13568 (defun org-add-log-note (&optional _purpose)
13569 "Pop up a window for taking a note, and add this note later."
13570 (remove-hook 'post-command-hook 'org-add-log-note)
13571 (setq org-log-note-window-configuration (current-window-configuration))
13572 (delete-other-windows)
13573 (move-marker org-log-note-return-to (point))
13574 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13575 (goto-char org-log-note-marker)
13576 (org-switch-to-buffer-other-window "*Org Note*")
13578 (if (memq org-log-note-how '(time state))
13579 (org-store-log-note)
13580 (let ((org-inhibit-startup t)) (org-mode))
13581 (insert (format "# Insert note for %s.
13582 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13584 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13585 ((eq org-log-note-purpose 'done) "closed todo item")
13586 ((eq org-log-note-purpose 'state)
13587 (format "state change from \"%s\" to \"%s\""
13588 (or org-log-note-previous-state "")
13589 (or org-log-note-state "")))
13590 ((eq org-log-note-purpose 'reschedule)
13592 ((eq org-log-note-purpose 'delschedule)
13593 "no longer scheduled")
13594 ((eq org-log-note-purpose 'redeadline)
13595 "changing deadline")
13596 ((eq org-log-note-purpose 'deldeadline)
13597 "removing deadline")
13598 ((eq org-log-note-purpose 'refile)
13600 ((eq org-log-note-purpose 'note)
13602 (t (error "This should not happen")))))
13603 (when org-log-note-extra (insert org-log-note-extra))
13604 (setq-local org-finish-function 'org-store-log-note)
13605 (run-hooks 'org-log-buffer-setup-hook)))
13607 (defvar org-note-abort nil) ; dynamically scoped
13608 (defun org-store-log-note ()
13609 "Finish taking a log note, and insert it to where it belongs."
13610 (let ((txt (prog1 (buffer-string)
13612 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13614 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13615 (setq txt (replace-match "" t t txt)))
13616 (when (string-match "\\s-+\\'" txt)
13617 (setq txt (replace-match "" t t txt)))
13618 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13619 (when (org-string-nw-p note)
13621 (org-replace-escapes
13623 (list (cons "%u" (user-login-name))
13624 (cons "%U" user-full-name)
13625 (cons "%t" (format-time-string
13626 (org-time-stamp-format 'long 'inactive)
13627 org-log-note-effective-time))
13628 (cons "%T" (format-time-string
13629 (org-time-stamp-format 'long nil)
13630 org-log-note-effective-time))
13631 (cons "%d" (format-time-string
13632 (org-time-stamp-format nil 'inactive)
13633 org-log-note-effective-time))
13634 (cons "%D" (format-time-string
13635 (org-time-stamp-format nil nil)
13636 org-log-note-effective-time))
13638 ((not org-log-note-state) "")
13639 ((string-match-p org-ts-regexp
13640 org-log-note-state)
13642 (substring org-log-note-state 1 -1)))
13643 (t (format "\"%s\"" org-log-note-state))))
13646 ((not org-log-note-previous-state) "")
13647 ((string-match-p org-ts-regexp
13648 org-log-note-previous-state)
13651 org-log-note-previous-state 1 -1)))
13652 (t (format "\"%s\""
13653 org-log-note-previous-state)))))))
13654 (when lines (setq note (concat note " \\\\")))
13656 (when (and lines (not org-note-abort))
13657 (with-current-buffer (marker-buffer org-log-note-marker)
13658 (org-with-wide-buffer
13659 ;; Find location for the new note.
13660 (goto-char org-log-note-marker)
13661 (set-marker org-log-note-marker nil)
13662 ;; Note associated to a clock is to be located right after
13663 ;; the clock. Do not move point.
13664 (unless (eq org-log-note-purpose 'clock-out)
13665 (goto-char (org-log-beginning t)))
13666 ;; Make sure point is at the beginning of an empty line.
13667 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13668 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13669 ;; In an existing list, add a new item at the top level.
13670 ;; Otherwise, indent line like a regular one.
13671 (let ((itemp (org-in-item-p)))
13674 (let ((struct (save-excursion
13675 (goto-char itemp) (org-list-struct))))
13676 (org-list-get-ind (org-list-get-top-point struct) struct)))
13677 (org-indent-line)))
13678 (insert (org-list-bullet-string "-") (pop lines))
13679 (let ((ind (org-list-item-body-column (line-beginning-position))))
13680 (dolist (line lines)
13682 (indent-line-to ind)
13684 (message "Note stored")
13685 (org-back-to-heading t)
13686 (org-cycle-hide-drawers 'children))
13687 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13688 ;; from within `org-add-log-note' because `buffer-undo-list'
13689 ;; is then modified outside of `org-with-remote-undo'.
13690 (when (eq this-command 'org-agenda-todo)
13691 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13692 ;; Don't add undo information when called from `org-agenda-todo'.
13693 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13694 (set-window-configuration org-log-note-window-configuration)
13695 (with-current-buffer (marker-buffer org-log-note-return-to)
13696 (goto-char org-log-note-return-to))
13697 (move-marker org-log-note-return-to nil)
13698 (when org-log-post-message (message "%s" org-log-post-message))))
13700 (defun org-remove-empty-drawer-at (pos)
13701 "Remove an empty drawer at position POS.
13702 POS may also be a marker."
13703 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13704 (org-with-wide-buffer
13706 (let ((drawer (org-element-at-point)))
13707 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13708 (not (org-element-property :contents-begin drawer)))
13709 (delete-region (org-element-property :begin drawer)
13710 (progn (goto-char (org-element-property :end drawer))
13711 (skip-chars-backward " \r\t\n")
13715 (defvar org-ts-type nil)
13716 (defun org-sparse-tree (&optional arg type)
13717 "Create a sparse tree, prompt for the details.
13718 This command can create sparse trees. You first need to select the type
13719 of match used to create the tree:
13721 t Show all TODO entries.
13722 T Show entries with a specific TODO keyword.
13723 m Show entries selected by a tags/property match.
13724 p Enter a property name and its value (both with completion on existing
13725 names/values) and show entries with that property.
13726 r Show entries matching a regular expression (`/' can be used as well).
13727 b Show deadlines and scheduled items before a date.
13728 a Show deadlines and scheduled items after a date.
13729 d Show deadlines due within `org-deadline-warning-days'.
13730 D Show deadlines and scheduled items between a date range."
13732 (setq type (or type org-sparse-tree-default-date-type))
13733 (setq org-ts-type type)
13734 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13735 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13736 \[c]ycle through date types: %s"
13738 (all "all timestamps")
13739 (scheduled "only scheduled")
13740 (deadline "only deadline")
13741 (active "only active timestamps")
13742 (inactive "only inactive timestamps")
13743 (closed "with a closed time-stamp")
13744 (otherwise "scheduled/deadline")))
13745 (let ((answer (read-char-exclusive)))
13751 (memq type '(nil all scheduled deadline active inactive closed)))))
13752 (?d (call-interactively 'org-check-deadlines))
13753 (?b (call-interactively 'org-check-before-date))
13754 (?a (call-interactively 'org-check-after-date))
13755 (?D (call-interactively 'org-check-dates-range))
13756 (?t (call-interactively 'org-show-todo-tree))
13757 (?T (org-show-todo-tree '(4)))
13758 (?m (call-interactively 'org-match-sparse-tree))
13760 (let* ((kwd (completing-read
13761 "Property: " (mapcar #'list (org-buffer-property-keys))))
13762 (value (completing-read
13763 "Value: " (mapcar #'list (org-property-values kwd)))))
13764 (unless (string-match "\\`{.*}\\'" value)
13765 (setq value (concat "\"" value "\"")))
13766 (org-match-sparse-tree arg (concat kwd "=" value))))
13767 ((?r ?R ?/) (call-interactively 'org-occur))
13768 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13770 (defvar-local org-occur-highlights nil
13771 "List of overlays used for occur matches.")
13772 (defvar-local org-occur-parameters nil
13773 "Parameters of the active org-occur calls.
13774 This is a list, each call to org-occur pushes as cons cell,
13775 containing the regular expression and the callback, onto the list.
13776 The list can contain several entries if `org-occur' has been called
13777 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13778 will only contain one set of parameters. When the highlights are
13779 removed (for example with `C-c C-c', or with the next edit (depending
13780 on `org-remove-highlights-with-change'), this variable is emptied
13783 (defun org-occur (regexp &optional keep-previous callback)
13784 "Make a compact tree which shows all matches of REGEXP.
13786 The tree will show the lines where the regexp matches, and any other context
13787 defined in `org-show-context-detail', which see.
13789 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13790 done by a previous call to `org-occur' will be kept, to allow stacking of
13791 calls to this command.
13793 Optional argument CALLBACK can be a function of no argument. In this case,
13794 it is called with point at the end of the match, match data being set
13795 accordingly. Current match is shown only if the return value is non-nil.
13796 The function must neither move point nor alter narrowing."
13797 (interactive "sRegexp: \nP")
13798 (when (equal regexp "")
13799 (user-error "Regexp cannot be empty"))
13800 (unless keep-previous
13801 (org-remove-occur-highlights nil nil t))
13802 (push (cons regexp callback) org-occur-parameters)
13805 (goto-char (point-min))
13806 (when (or (not keep-previous) ; do not want to keep
13807 (not org-occur-highlights)) ; no previous matches
13810 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13811 (isearch-no-upper-case-p regexp t)
13812 org-occur-case-fold-search)))
13813 (while (re-search-forward regexp nil t)
13814 (when (or (not callback)
13815 (save-match-data (funcall callback)))
13816 (setq cnt (1+ cnt))
13817 (when org-highlight-sparse-tree-matches
13818 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13819 (org-show-context 'occur-tree)))))
13820 (when org-remove-highlights-with-change
13821 (add-hook 'before-change-functions 'org-remove-occur-highlights
13823 (unless org-sparse-tree-open-archived-trees
13824 (org-hide-archived-subtrees (point-min) (point-max)))
13825 (run-hooks 'org-occur-hook)
13826 (when (called-interactively-p 'interactive)
13827 (message "%d match(es) for regexp %s" cnt regexp))
13830 (defun org-occur-next-match (&optional n _reset)
13831 "Function for `next-error-function' to find sparse tree matches.
13832 N is the number of matches to move, when negative move backwards.
13833 This function always goes back to the starting point when no
13835 (let* ((limit (if (< n 0) (point-min) (point-max)))
13836 (search-func (if (< n 0)
13837 'previous-single-char-property-change
13838 'next-single-char-property-change))
13843 (while (setq p1 (funcall search-func (point) 'org-type))
13844 (when (equal p1 limit)
13846 (user-error "No more matches"))
13847 (when (equal (get-char-property p1 'org-type) 'org-occur)
13851 (throw 'exit (point))))
13854 (user-error "No more matches"))))
13856 (defun org-show-context (&optional key)
13857 "Make sure point and context are visible.
13858 Optional argument KEY, when non-nil, is a symbol. See
13859 `org-show-context-detail' for allowed values and how much is to
13861 (org-show-set-visibility
13862 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13863 ((cdr (assq key org-show-context-detail)))
13864 (t (cdr (assq 'default org-show-context-detail))))))
13866 (defun org-show-set-visibility (detail)
13867 "Set visibility around point according to DETAIL.
13868 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13869 `tree', `canonical' or t. See `org-show-context-detail' for more
13871 ;; Show current heading and possibly its entry, following headline
13872 ;; or all children.
13873 (if (and (org-at-heading-p) (not (eq detail 'local)))
13874 (org-flag-heading nil)
13876 ;; If point is hidden within a drawer or a block, make sure to
13878 (dolist (o (overlays-at (point)))
13879 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13880 (delete-overlay o)))
13881 (unless (org-before-first-heading-p)
13882 (org-with-limited-levels
13884 ((tree canonical t) (org-show-children))
13885 ((nil minimal ancestors))
13887 (outline-next-heading)
13888 (org-flag-heading nil)))))))
13889 ;; Show all siblings.
13890 (when (eq detail 'lineage) (org-show-siblings))
13891 ;; Show ancestors, possibly with their children.
13892 (when (memq detail '(ancestors lineage tree canonical t))
13894 (while (org-up-heading-safe)
13895 (org-flag-heading nil)
13896 (when (memq detail '(canonical t)) (org-show-entry))
13897 (when (memq detail '(tree canonical t)) (org-show-children))))))
13899 (defvar org-reveal-start-hook nil
13900 "Hook run before revealing a location.")
13902 (defun org-reveal (&optional siblings)
13903 "Show current entry, hierarchy above it, and the following headline.
13905 This can be used to show a consistent set of context around
13906 locations exposed with `org-show-context'.
13908 With optional argument SIBLINGS, on each level of the hierarchy all
13909 siblings are shown. This repairs the tree structure to what it would
13910 look like when opened with hierarchical calls to `org-cycle'.
13912 With a \\[universal-argument] \\[universal-argument] prefix, \
13913 go to the parent and show the entire tree."
13915 (run-hooks 'org-reveal-start-hook)
13916 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13917 ((equal siblings '(16))
13919 (when (org-up-heading-safe)
13921 (run-hook-with-args 'org-cycle-hook 'subtree))))
13922 (t (org-show-set-visibility 'lineage))))
13924 (defun org-highlight-new-match (beg end)
13925 "Highlight from BEG to END and mark the highlight is an occur headline."
13926 (let ((ov (make-overlay beg end)))
13927 (overlay-put ov 'face 'secondary-selection)
13928 (overlay-put ov 'org-type 'org-occur)
13929 (push ov org-occur-highlights)))
13931 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13932 "Remove the occur highlights from the buffer.
13933 BEG and END are ignored. If NOREMOVE is nil, remove this function
13934 from the `before-change-functions' in the current buffer."
13936 (unless org-inhibit-highlight-removal
13937 (mapc #'delete-overlay org-occur-highlights)
13938 (setq org-occur-highlights nil)
13939 (setq org-occur-parameters nil)
13941 (remove-hook 'before-change-functions
13942 'org-remove-occur-highlights 'local))))
13946 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13947 "Regular expression matching the priority indicator.")
13949 (defvar org-remove-priority-next-time nil)
13951 (defun org-priority-up ()
13952 "Increase the priority of the current item."
13954 (org-priority 'up))
13956 (defun org-priority-down ()
13957 "Decrease the priority of the current item."
13959 (org-priority 'down))
13961 (defun org-priority (&optional action _show)
13962 "Change the priority of an item.
13963 ACTION can be `set', `up', `down', or a character."
13965 (if (equal action '(4))
13966 (org-show-priority)
13967 (unless org-enable-priority-commands
13968 (user-error "Priority commands are disabled"))
13969 (setq action (or action 'set))
13970 (let (current new news have remove)
13972 (org-back-to-heading t)
13973 (when (looking-at org-priority-regexp)
13974 (setq current (string-to-char (match-string 2))
13977 ((eq action 'remove)
13978 (setq remove t new ?\ ))
13979 ((or (eq action 'set)
13981 (if (not (eq action 'set))
13983 (message "Priority %c-%c, SPC to remove: "
13984 org-highest-priority org-lowest-priority)
13986 (setq new (read-char-exclusive))))
13987 (when (and (= (upcase org-highest-priority) org-highest-priority)
13988 (= (upcase org-lowest-priority) org-lowest-priority))
13989 (setq new (upcase new)))
13990 (cond ((equal new ?\ ) (setq remove t))
13991 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13992 (user-error "Priority must be between `%c' and `%c'"
13993 org-highest-priority org-lowest-priority))))
13996 (1- current) ; normal cycling
13997 ;; last priority was empty
13998 (if (eq last-command this-command)
13999 org-lowest-priority ; wrap around empty to lowest
14001 (if org-priority-start-cycle-with-default
14002 org-default-priority
14003 (1- org-default-priority))))))
14006 (1+ current) ; normal cycling
14007 ;; last priority was empty
14008 (if (eq last-command this-command)
14009 org-highest-priority ; wrap around empty to highest
14011 (if org-priority-start-cycle-with-default
14012 org-default-priority
14013 (1+ org-default-priority))))))
14014 (t (user-error "Invalid action")))
14015 (when (or (< (upcase new) org-highest-priority)
14016 (> (upcase new) org-lowest-priority))
14017 (if (and (memq action '(up down))
14018 (not have) (not (eq last-command this-command)))
14019 ;; `new' is from default priority
14021 "The default can not be set, see `org-default-priority' why")
14022 ;; normal cycling: `new' is beyond highest/lowest priority
14023 ;; and is wrapped around to the empty priority
14025 (setq news (format "%c" new))
14028 (replace-match "" t t nil 1)
14029 (replace-match news t t nil 2))
14031 (user-error "No priority cookie found in line")
14032 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14035 (goto-char (match-end 2))
14036 (insert " [#" news "]"))
14037 (goto-char (match-beginning 3))
14038 (insert "[#" news "] "))))
14039 (org-set-tags nil 'align))
14041 (message "Priority removed")
14042 (message "Priority of current item set to %s" news)))))
14044 (defun org-show-priority ()
14045 "Show the priority of the current item.
14046 This priority is composed of the main priority given with the [#A] cookies,
14047 and by additional input from the age of a schedules or deadline entry."
14049 (let ((pri (if (eq major-mode 'org-agenda-mode)
14050 (org-get-at-bol 'priority)
14053 (beginning-of-line)
14054 (and (looking-at org-heading-regexp)
14055 (org-get-priority (match-string 0))))))))
14056 (message "Priority is %d" (if pri pri -1000))))
14058 (defun org-get-priority (s)
14059 "Find priority cookie and return priority."
14061 (if (functionp org-get-priority-function)
14062 (funcall org-get-priority-function)
14063 (if (not (string-match org-priority-regexp s))
14064 (* 1000 (- org-lowest-priority org-default-priority))
14065 (* 1000 (- org-lowest-priority
14066 (string-to-char (match-string 2 s))))))))
14070 (defvar org-agenda-archives-mode)
14071 (defvar org-map-continue-from nil
14072 "Position from where mapping should continue.
14073 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14075 (defvar org-scanner-tags nil
14076 "The current tag list while the tags scanner is running.")
14078 (defvar org-trust-scanner-tags nil
14079 "Should `org-get-tags-at' use the tags for the scanner.
14080 This is for internal dynamical scoping only.
14081 When this is non-nil, the function `org-get-tags-at' will return the value
14082 of `org-scanner-tags' instead of building the list by itself. This
14083 can lead to large speed-ups when the tags scanner is used in a file with
14084 many entries, and when the list of tags is retrieved, for example to
14085 obtain a list of properties. Building the tags list for each entry in such
14086 a file becomes an N^2 operation - but with this variable set, it scales
14089 (defvar org--matcher-tags-todo-only nil)
14091 (defun org-scan-tags (action matcher todo-only &optional start-level)
14092 "Scan headline tags with inheritance and produce output ACTION.
14094 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14095 or `agenda' to produce an entry list for an agenda view. It can also be
14096 a Lisp form or a function that should be called at each matched headline, in
14097 this case the return value is a list of all return values from these calls.
14099 MATCHER is a function accepting three arguments, returning
14100 a non-nil value whenever a given set of tags qualifies a headline
14101 for inclusion. See `org-make-tags-matcher' for more information.
14102 As a special case, it can also be set to t (respectively nil) in
14103 order to match all (respectively none) headline.
14105 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14106 included in the output.
14108 START-LEVEL can be a string with asterisks, reducing the scope to
14109 headlines matching this string."
14110 (require 'org-agenda)
14111 (let* ((re (concat "^"
14113 ;; Get the correct level to match
14114 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14115 org-outline-regexp)
14117 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14118 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14119 (props (list 'face 'default
14120 'done-face 'org-agenda-done
14121 'undone-face 'default
14122 'mouse-face 'highlight
14123 'org-not-done-regexp org-not-done-regexp
14124 'org-todo-regexp org-todo-regexp
14125 'org-complex-heading-regexp org-complex-heading-regexp
14127 (format "mouse-2 or RET jump to org file %s"
14128 (abbreviate-file-name
14129 (or (buffer-file-name (buffer-base-buffer))
14130 (buffer-name (buffer-base-buffer)))))))
14131 (org-map-continue-from nil)
14132 lspos tags tags-list
14133 (tags-alist (list (cons 0 org-file-tags)))
14134 (llast 0) rtn rtn1 level category i txt
14135 todo marker entry priority
14136 ts-date ts-date-type ts-date-pair)
14137 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14138 (setq action (list 'lambda nil action)))
14140 (goto-char (point-min))
14141 (when (eq action 'sparse-tree)
14143 (org-remove-occur-highlights))
14144 (while (let (case-fold-search)
14145 (re-search-forward re nil t))
14146 (setq org-map-continue-from nil)
14149 ;; TODO: is the 1-2 difference a bug?
14150 (when (match-end 1) (match-string-no-properties 2))
14151 tags (when (match-end 4) (match-string-no-properties 4)))
14152 (goto-char (setq lspos (match-beginning 0)))
14153 (setq level (org-reduced-level (org-outline-level))
14154 category (org-get-category))
14155 (when (eq action 'agenda)
14156 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14157 ts-date (car ts-date-pair)
14158 ts-date-type (cdr ts-date-pair)))
14159 (setq i llast llast level)
14160 ;; remove tag lists from same and sublevels
14161 (while (>= i level)
14162 (when (setq entry (assoc i tags-alist))
14163 (setq tags-alist (delete entry tags-alist)))
14165 ;; add the next tags
14167 (setq tags (org-split-string tags ":")
14169 (cons (cons level tags) tags-alist)))
14170 ;; compile tags for current headline
14172 (if org-use-tag-inheritance
14173 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14175 org-scanner-tags tags-list)
14176 (when org-use-tag-inheritance
14177 (setcdr (car tags-alist)
14178 (mapcar (lambda (x)
14179 (setq x (copy-sequence x))
14180 (org-add-prop-inherited x))
14181 (cdar tags-alist))))
14182 (when (and tags org-use-tag-inheritance
14183 (or (not (eq t org-use-tag-inheritance))
14184 org-tags-exclude-from-inheritance))
14185 ;; Selective inheritance, remove uninherited ones.
14186 (setcdr (car tags-alist)
14187 (org-remove-uninherited-tags (cdar tags-alist))))
14190 ;; eval matcher only when the todo condition is OK
14191 (and (or (not todo-only) (member todo org-todo-keywords-1))
14192 (if (functionp matcher)
14193 (let ((case-fold-search t) (org-trust-scanner-tags t))
14194 (funcall matcher todo tags-list level))
14197 ;; Call the skipper, but return t if it does not
14198 ;; skip, so that the `and' form continues evaluating.
14200 (unless (eq action 'sparse-tree) (org-agenda-skip))
14203 ;; Check if timestamps are deselecting this entry
14204 (or (not todo-only)
14205 (and (member todo org-todo-keywords-1)
14206 (or (not org-agenda-tags-todo-honor-ignore-options)
14207 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14209 ;; select this headline
14211 ((eq action 'sparse-tree)
14212 (and org-highlight-sparse-tree-matches
14213 (org-get-heading) (match-end 0)
14214 (org-highlight-new-match
14215 (match-beginning 1) (match-end 1)))
14216 (org-show-context 'tags-tree))
14217 ((eq action 'agenda)
14218 (setq txt (org-agenda-format-item
14221 (if (eq org-tags-match-list-sublevels 'indented)
14222 (make-string (1- level) ?.) "")
14224 (make-string level ?\s)
14227 priority (org-get-priority txt))
14229 (setq marker (org-agenda-new-marker))
14230 (org-add-props txt props
14231 'org-marker marker 'org-hd-marker marker 'org-category category
14235 'type (concat "tagsmatch" ts-date-type))
14237 ((functionp action)
14238 (setq org-map-continue-from nil)
14240 (setq rtn1 (funcall action))
14242 (t (user-error "Invalid action")))
14244 ;; if we are to skip sublevels, jump to end of subtree
14245 (unless org-tags-match-list-sublevels
14246 (org-end-of-subtree t)
14247 (backward-char 1))))
14248 ;; Get the correct position from where to continue
14249 (if org-map-continue-from
14250 (goto-char org-map-continue-from)
14251 (and (= (point) lspos) (end-of-line 1)))))
14252 (when (and (eq action 'sparse-tree)
14253 (not org-sparse-tree-open-archived-trees))
14254 (org-hide-archived-subtrees (point-min) (point-max)))
14257 (defun org-remove-uninherited-tags (tags)
14258 "Remove all tags that are not inherited from the list TAGS."
14260 ((eq org-use-tag-inheritance t)
14261 (if org-tags-exclude-from-inheritance
14262 (org-delete-all org-tags-exclude-from-inheritance tags)
14264 ((not org-use-tag-inheritance) nil)
14265 ((stringp org-use-tag-inheritance)
14268 (if (and (string-match org-use-tag-inheritance x)
14269 (not (member x org-tags-exclude-from-inheritance)))
14272 ((listp org-use-tag-inheritance)
14275 (if (member x org-use-tag-inheritance) x nil))
14278 (defun org-match-sparse-tree (&optional todo-only match)
14279 "Create a sparse tree according to tags string MATCH.
14281 MATCH is a string with match syntax. It can contain a selection
14282 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14283 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14284 those. See the manual for details.
14286 If optional argument TODO-ONLY is non-nil, only select lines that
14287 are also TODO tasks."
14289 (org-agenda-prepare-buffers (list (current-buffer)))
14290 (let ((org--matcher-tags-todo-only todo-only))
14291 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14292 org--matcher-tags-todo-only)))
14294 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14296 (defvar org-cached-props nil)
14297 (defun org-cached-entry-get (pom property)
14298 (if (or (eq t org-use-property-inheritance)
14299 (and (stringp org-use-property-inheritance)
14300 (let ((case-fold-search t))
14301 (string-match-p org-use-property-inheritance property)))
14302 (and (listp org-use-property-inheritance)
14303 (member-ignore-case property org-use-property-inheritance)))
14304 ;; Caching is not possible, check it directly.
14305 (org-entry-get pom property 'inherit)
14306 ;; Get all properties, so we can do complicated checks easily.
14307 (cdr (assoc-string property
14308 (or org-cached-props
14309 (setq org-cached-props (org-entry-properties pom)))
14312 (defun org-global-tags-completion-table (&optional files)
14313 "Return the list of all tags in all agenda buffer/files.
14314 Optional FILES argument is a list of files which can be used
14315 instead of the agenda files."
14322 (set-buffer (find-file-noselect file))
14323 (mapcar (lambda (x)
14324 (and (stringp (car-safe x))
14325 (list (car-safe x))))
14326 (or org-current-tag-alist (org-get-buffer-tags))))
14327 (if (car-safe files) files
14328 (org-agenda-files))))))))
14330 (defun org-make-tags-matcher (match)
14331 "Create the TAGS/TODO matcher form for the selection string MATCH.
14333 Returns a cons of the selection string MATCH and a function
14334 implementing the matcher.
14336 The matcher is to be called at an Org entry, with point on the
14337 headline, and returns non-nil if the entry matches the selection
14338 string MATCH. It must be called with three arguments: the TODO
14339 keyword at the entry (or nil if none), the list of all tags at
14340 the entry including inherited ones and the reduced level of the
14341 headline. Additionally, the category of the entry, if any, must
14342 be specified as the text property `org-category' on the headline.
14344 This function sets the variable `org--matcher-tags-todo-only' to
14345 a non-nil value if the matcher restricts matching to TODO
14346 entries, otherwise it is not touched.
14348 See also `org-scan-tags'."
14350 ;; Get a new match request, with completion against the global
14351 ;; tags table and the local tags in current buffer.
14352 (let ((org-last-tags-completion-table
14354 (delq nil (append (org-get-buffer-tags)
14355 (org-global-tags-completion-table))))))
14359 'org-tags-completion-function nil nil nil 'org-tags-history))))
14361 (let ((match0 match)
14362 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14364 tagsmatch todomatch tagsmatcher todomatcher)
14366 ;; Expand group tags.
14367 (setq match (org-tags-expand match))
14369 ;; Check if there is a TODO part of this match, which would be the
14370 ;; part after a "/". To make sure that this slash is not part of
14371 ;; a property value to be matched against, we also check that
14372 ;; there is no / after that slash. First, find the last slash.
14374 (while (string-match "/+" match s)
14375 (setq start (match-beginning 0))
14376 (setq s (match-end 0))))
14377 (if (and (string-match "/+" match start)
14378 (not (string-match-p "\"" match start)))
14379 ;; Match contains also a TODO-matching request.
14381 (setq tagsmatch (substring match 0 (match-beginning 0)))
14382 (setq todomatch (substring match (match-end 0)))
14383 (when (string-prefix-p "!" todomatch)
14384 (setq org--matcher-tags-todo-only t)
14385 (setq todomatch (substring todomatch 1)))
14386 (when (string-match "\\`\\s-*\\'" todomatch)
14387 (setq todomatch nil)))
14388 ;; Only matching tags.
14389 (setq tagsmatch match)
14390 (setq todomatch nil))
14392 ;; Make the tags matcher.
14393 (when (org-string-nw-p tagsmatch)
14395 (orterms (org-split-string tagsmatch "|"))
14397 (while (setq term (pop orterms))
14398 (while (and (equal (substring term -1) "\\") orterms)
14399 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14400 (while (string-match re term)
14401 (let* ((rest (substring term (match-end 0)))
14402 (minus (and (match-end 1)
14403 (equal (match-string 1 term) "-")))
14404 (tag (save-match-data
14405 (replace-regexp-in-string
14406 "\\\\-" "-" (match-string 2 term))))
14407 (regexp (eq (string-to-char tag) ?{))
14408 (levelp (match-end 4))
14409 (propp (match-end 5))
14412 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14414 `(,(org-op-to-function (match-string 3 term))
14416 ,(string-to-number (match-string 4 term))))
14418 (let* ((gv (pcase (upcase (match-string 5 term))
14420 '(get-text-property (point) 'org-category))
14422 (p `(org-cached-entry-get nil ,p))))
14423 (pv (match-string 7 term))
14424 (regexp (eq (string-to-char pv) ?{))
14425 (strp (eq (string-to-char pv) ?\"))
14426 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14427 (po (org-op-to-function (match-string 6 term)
14428 (if timep 'time strp))))
14429 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14430 (when timep (setq pv (org-matcher-time pv)))
14431 (cond ((and regexp (eq po 'org<>))
14432 `(not (string-match ,pv (or ,gv ""))))
14433 (regexp `(string-match ,pv (or ,gv "")))
14434 (strp `(,po (or ,gv "") ,pv))
14437 (string-to-number (or ,gv ""))
14438 ,(string-to-number pv))))))
14439 (t `(member ,tag tags-list)))))
14440 (push (if minus `(not ,mm) mm) tagsmatcher)
14442 (push `(and ,@tagsmatcher) orlist)
14443 (setq tagsmatcher nil))
14444 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14446 ;; Make the TODO matcher.
14447 (when (org-string-nw-p todomatch)
14448 (let ((orlist nil))
14449 (dolist (term (org-split-string todomatch "|"))
14450 (while (string-match re term)
14451 (let* ((minus (and (match-end 1)
14452 (equal (match-string 1 term) "-")))
14453 (kwd (match-string 2 term))
14454 (regexp (eq (string-to-char kwd) ?{))
14455 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14456 `(equal todo ,kwd))))
14457 (push (if minus `(not ,mm) mm) todomatcher))
14458 (setq term (substring term (match-end 0))))
14459 (push (if (> (length todomatcher) 1)
14460 (cons 'and todomatcher)
14463 (setq todomatcher nil))
14464 (setq todomatcher (cons 'or orlist))))
14466 ;; Return the string and function of the matcher. If no
14467 ;; tags-specific or todo-specific matcher exists, match
14469 (let ((matcher (if (and tagsmatcher todomatcher)
14470 `(and ,tagsmatcher ,todomatcher)
14471 (or tagsmatcher todomatcher t))))
14472 (when org--matcher-tags-todo-only
14473 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14474 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14476 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14477 "Expand group tags in MATCH.
14479 This replaces every group tag in MATCH with a regexp tag search.
14480 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14481 will be replaced like this:
14483 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14484 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14485 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14487 Replacing by a regexp preserves the structure of the match.
14488 E.g., this expansion
14490 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14492 will match anything tagged with \"Lab\" and \"Home\", or tagged
14493 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14495 A group tag in MATCH can contain regular expressions of its own.
14496 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14497 will be replaced like this:
14499 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14501 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14502 assumed to be a single group tag, and the function will return
14503 the list of tags in this group.
14505 When DOWNCASE is non-nil, expand downcased TAGS."
14507 (let* ((case-fold-search t)
14508 (stable org-mode-syntax-table)
14509 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14510 (taggroups (if downcased
14511 (mapcar (lambda (tg) (mapcar #'downcase tg))
14514 (taggroups-keys (mapcar #'car taggroups))
14515 (return-match (if downcased (downcase match) match))
14517 (work-already-expanded tags-already-expanded)
14518 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14519 ;; @ and _ are allowed as word-components in tags.
14520 (modify-syntax-entry ?@ "w" stable)
14521 (modify-syntax-entry ?_ "w" stable)
14522 ;; Temporarily replace regexp-expressions in the match-expression.
14523 (while (string-match "{.+?}" return-match)
14525 (push (match-string 0 return-match) regexps-in-match)
14526 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14527 (while (and taggroups-keys
14528 (with-syntax-table stable
14530 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14531 (regexp-opt taggroups-keys) "\\>\\)")
14533 (let* ((dir (match-string 1 return-match))
14534 (tag (match-string 2 return-match))
14535 (tag (if downcased (downcase tag) tag)))
14536 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14537 (member tag work-already-expanded))
14538 (setq tags-in-group (assoc tag taggroups))
14539 (push tag work-already-expanded)
14540 ;; Recursively expand each tag in the group, if the tag hasn't
14541 ;; already been expanded. Restore the match-data after all recursive calls.
14543 (let (tags-expanded)
14544 (dolist (x (cdr tags-in-group))
14545 (if (and (member x taggroups-keys)
14546 (not (member x work-already-expanded)))
14547 (setq tags-expanded
14550 (org-tags-expand x t downcased
14551 work-already-expanded)
14553 (setq tags-expanded
14554 (append (list x) tags-expanded)))
14555 (setq work-already-expanded
14557 (append tags-expanded
14558 work-already-expanded))))
14559 (setq tags-in-group
14560 (delete-dups (cons (car tags-in-group)
14562 ;; Filter tag-regexps from tags.
14563 (setq regexp-in-group-escaped
14564 (delq nil (mapcar (lambda (x)
14566 (and (equal "{" (substring x 0 1))
14567 (equal "}" (substring x -1))
14572 (mapcar (lambda (x)
14573 (substring x 1 -1))
14574 regexp-in-group-escaped)
14576 (delq nil (mapcar (lambda (x)
14578 (and (not (equal "{" (substring x 0 1)))
14579 (not (equal "}" (substring x -1)))
14583 ;; If single-as-list, do no more in the while-loop.
14584 (if (not single-as-list)
14586 (when regexp-in-group
14587 (setq regexp-in-group
14589 (mapconcat 'identity regexp-in-group
14591 (setq tags-in-group
14594 (regexp-opt tags-in-group)
14598 (when (stringp tags-in-group)
14599 (org-add-props tags-in-group '(grouptag t)))
14601 (replace-match tags-in-group t t return-match)))
14602 (setq tags-in-group
14603 (append regexp-in-group-escaped tags-in-group))))
14604 (setq taggroups-keys (delete tag taggroups-keys))))
14605 ;; Add the regular expressions back into the match-expression again.
14606 (while regexps-in-match
14607 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14608 (pop regexps-in-match)
14612 (if tags-in-group tags-in-group (list return-match))
14615 (list (if downcased (downcase match) match))
14618 (defun org-op-to-function (op &optional stringp)
14619 "Turn an operator into the appropriate function."
14622 ((equal op "<" ) '(< string< org-time<))
14623 ((equal op ">" ) '(> org-string> org-time>))
14624 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14625 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14626 ((member op '("=" "==")) '(= string= org-time=))
14627 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14628 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14630 (defun org<> (a b) (not (= a b)))
14631 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14632 (defun org-string>= (a b) (not (string< a b)))
14633 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14634 (defun org-string<> (a b) (not (string= 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) (<= a b)))
14638 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14639 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14640 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14642 "Convert S to a floating point time.
14643 If S is already a number, just return it. If it is a string, parse
14644 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14648 (condition-case nil
14649 (float-time (apply #'encode-time (org-parse-time-string s)))
14653 (defun org-time-today ()
14654 "Time in seconds today at 0:00.
14655 Returns the float number of seconds since the beginning of the
14656 epoch to the beginning of today (00:00)."
14657 (float-time (apply 'encode-time
14658 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14660 (defun org-matcher-time (s)
14661 "Interpret a time comparison value."
14664 ((string= s "<now>") (float-time))
14665 ((string= s "<today>") (org-time-today))
14666 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14667 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14668 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14669 (+ (org-time-today)
14670 (* (string-to-number (match-string 1 s))
14671 (cdr (assoc (match-string 2 s)
14672 '(("d" . 86400.0) ("w" . 604800.0)
14673 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14676 (defun org-match-any-p (re list)
14677 "Does re match any element of list?"
14678 (setq list (mapcar (lambda (x) (string-match re x)) list))
14681 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14682 (defvar org-tags-overlay (make-overlay 1 1))
14683 (delete-overlay org-tags-overlay)
14685 (defun org-get-local-tags-at (&optional pos)
14686 "Get a list of tags defined in the current headline."
14687 (org-get-tags-at pos 'local))
14689 (defun org-get-local-tags ()
14690 "Get a list of tags defined in the current headline."
14691 (org-get-tags-at nil 'local))
14693 (defun org-get-tags-at (&optional pos local)
14694 "Get a list of all headline tags applicable at POS.
14695 POS defaults to point. If tags are inherited, the list contains
14696 the targets in the same sequence as the headlines appear, i.e.
14697 the tags of the current headline come last.
14698 When LOCAL is non-nil, only return tags from the current headline,
14699 ignore inherited ones."
14701 (if (and org-trust-scanner-tags
14702 (or (not pos) (equal pos (point)))
14705 (let (tags ltags lastpos parent)
14709 (goto-char (or pos (point)))
14712 (condition-case nil
14714 (org-back-to-heading t)
14715 (while (not (equal lastpos (point)))
14716 (setq lastpos (point))
14717 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14718 (setq ltags (org-split-string
14719 (match-string-no-properties 1) ":"))
14721 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14724 (org-remove-uninherited-tags ltags)
14727 (or org-use-tag-inheritance (throw 'done t))
14728 (when local (throw 'done t))
14729 (or (org-up-heading-safe) (error nil))
14734 (reverse (delete-dups
14736 (org-remove-uninherited-tags
14740 (defun org-add-prop-inherited (s)
14741 (add-text-properties 0 (length s) '(inherited t) s)
14744 (defun org-toggle-tag (tag &optional onoff)
14745 "Toggle the tag TAG for the current line.
14746 If ONOFF is `on' or `off', don't toggle but set to this state."
14748 (org-back-to-heading t)
14750 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14751 (line-end-position) t)
14752 (let ((tags (match-string 1)))
14753 ;; Clear current tags.
14755 ;; Reverse the tags list so any new tag is appended to
14756 ;; the current list of tags.
14757 (nreverse (org-split-string tags ":")))))
14760 (`off (setq current (delete tag current)))
14761 ((or `on (guard (not (member tag current))))
14763 (cl-pushnew tag current :test #'equal))
14764 (_ (setq current (delete tag current))))
14768 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14769 (org-set-tags nil t))
14770 (delete-horizontal-space))
14771 (run-hooks 'org-after-tags-change-hook)
14774 (defun org--align-tags-here (to-col)
14775 "Align tags on the current headline to TO-COL.
14776 Assume point is on a headline."
14777 (let ((pos (point)))
14778 (beginning-of-line)
14779 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14780 (>= pos (match-beginning 2)))
14781 ;; No tags or point within tags: do not align.
14783 (goto-char (match-beginning 1))
14784 (let ((shift (max (- (if (>= to-col 0) to-col
14785 (- (abs to-col) (string-width (match-string 2))))
14788 (replace-match (make-string shift ?\s) nil nil nil 1)
14789 ;; Preserve initial position, if possible. In any case, stop
14791 (when (< pos (point)) (goto-char pos))))))
14793 (defun org-set-tags-command (&optional arg just-align)
14794 "Call the set-tags command for the current entry."
14796 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14797 (org-set-tags arg just-align)
14799 (unless (and (org-region-active-p)
14800 org-loop-over-headlines-in-active-region)
14801 (org-back-to-heading t))
14802 (org-set-tags arg just-align))))
14804 (defun org-set-tags-to (data)
14805 "Set the tags of the current entry to DATA, replacing the current tags.
14806 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14807 If DATA is nil or the empty string, any tags will be removed."
14808 (interactive "sTags: ")
14812 ((equal data "") "")
14814 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14817 (concat ":" (mapconcat 'identity data ":") ":"))))
14820 (org-back-to-heading t)
14821 (when (let ((case-fold-search nil))
14822 (looking-at org-complex-heading-regexp))
14825 (goto-char (match-beginning 5))
14827 (delete-region (point) (point-at-eol))
14828 (org-set-tags nil 'align))
14829 (goto-char (point-at-eol))
14831 (org-set-tags nil 'align)))
14832 (beginning-of-line 1)
14833 (when (looking-at ".*?\\([ \t]+\\)$")
14834 (delete-region (match-beginning 1) (match-end 1))))))
14836 (defun org-align-all-tags ()
14837 "Align the tags in all headings."
14840 (or (ignore-errors (org-back-to-heading t))
14841 (outline-next-heading))
14842 (if (org-at-heading-p)
14844 (message "No headings"))))
14846 (defvar org-indent-indentation-per-level)
14847 (defun org-set-tags (&optional arg just-align)
14848 "Set the tags for the current headline.
14849 With prefix ARG, realign all tags in headings in the current buffer.
14850 When JUST-ALIGN is non-nil, only align tags."
14852 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14853 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14854 'region-start-level
14856 org-loop-over-headlines-in-active-region)
14858 ;; We don't use ARG and JUST-ALIGN here because these args
14859 ;; are not useful when looping over headlines.
14861 org-loop-over-headlines-in-active-region
14863 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14864 (let ((org-setting-tags t))
14867 (goto-char (point-min))
14868 (while (re-search-forward org-outline-regexp-bol nil t)
14869 (org-set-tags nil t)
14871 (message "All tags realigned to column %d" org-tags-column))
14872 (let* ((current (org-get-tags-string))
14874 (if just-align current
14875 ;; Get a new set of tags from the user.
14880 org-last-tags-completion-table
14881 ;; Uniquify tags in alists, yet preserve
14882 ;; structure (i.e., keywords).
14886 (let ((head (car pair)))
14887 (cond ((symbolp head) pair)
14888 ((member head seen) nil)
14889 (t (push head seen)
14892 (or org-current-tag-alist
14893 (org-get-buffer-tags))
14895 org-complete-tags-always-offer-all-agenda-tags
14896 (org-global-tags-completion-table
14897 (org-agenda-files))))))))
14898 (current-tags (org-split-string current ":"))
14900 (nreverse (nthcdr (length current-tags)
14901 (nreverse (org-get-tags-at))))))
14902 (replace-regexp-in-string
14905 (if (or (eq t org-use-fast-tag-selection)
14906 (and org-use-fast-tag-selection
14907 (delq nil (mapcar #'cdr table))))
14908 (org-fast-tag-selection
14909 current-tags inherited-tags table
14910 (and org-fast-tag-selection-include-todo
14911 org-todo-key-alist))
14912 (let ((org-add-colon-after-tag-completion
14913 (< 1 (length table))))
14917 #'org-tags-completion-function
14918 nil nil current 'org-tags-history))))))))))
14920 (when org-tags-sort-function
14924 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14925 org-tags-sort-function)
14928 (if (or (string= ":" tags)
14929 (string= "::" tags))
14931 (if (not (org-string-nw-p tags)) (setq tags "")
14932 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14933 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14935 ;; Insert new tags at the correct column.
14936 (unless (equal current tags)
14938 (beginning-of-line)
14939 (let ((case-fold-search nil))
14940 (looking-at org-complex-heading-regexp))
14941 ;; Remove current tags, if any.
14942 (when (match-end 5) (replace-match "" nil nil nil 5))
14943 ;; Insert new tags, if any. Otherwise, remove trailing
14946 (if (not (equal tags ""))
14947 ;; When text is being inserted on an invisible
14948 ;; region boundary, it can be inadvertently sucked
14949 ;; into invisibility.
14950 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14951 (skip-chars-backward " \t")
14952 (delete-region (point) (line-end-position)))))
14953 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14955 (unless (equal tags "")
14956 (let* ((level (save-excursion
14957 (beginning-of-line)
14958 (skip-chars-forward "\\*")))
14959 (offset (if (bound-and-true-p org-indent-mode)
14960 (* (1- org-indent-indentation-per-level)
14965 (if (> org-tags-column 0) (- offset) offset))))
14966 (org--align-tags-here tags-column))))
14967 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14969 (defun org-change-tag-in-region (beg end tag off)
14970 "Add or remove TAG for each entry in the region.
14971 This works in the agenda, and also in an Org buffer."
14973 (list (region-beginning) (region-end)
14974 (let ((org-last-tags-completion-table
14975 (if (derived-mode-p 'org-mode)
14977 (delq nil (append (org-get-buffer-tags)
14978 (org-global-tags-completion-table))))
14979 (org-global-tags-completion-table))))
14981 "Tag: " 'org-tags-completion-function nil nil nil
14982 'org-tags-history))
14984 (message "[s]et or
[r]emove? ")
14985 (equal (read-char-exclusive) ?r))))
14986 (when (fboundp 'deactivate-mark) (deactivate-mark))
14987 (let ((agendap (equal major-mode 'org-agenda-mode))
14988 l1 l2 m buf pos newhead (cnt 0))
14990 (setq l2 (1- (org-current-line)))
14992 (setq l1 (org-current-line))
14993 (cl-loop for l from l1 to l2 do
14995 (setq m (get-text-property (point) 'org-hd-marker))
14996 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14998 (setq buf (if agendap (marker-buffer m) (current-buffer))
14999 pos (if agendap m (point)))
15000 (with-current-buffer buf
15004 (setq cnt (1+ cnt))
15005 (org-toggle-tag tag (if off 'off 'on))
15006 (setq newhead (org-get-heading)))))
15007 (and agendap (org-agenda-change-all-lines newhead m))))
15008 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15010 (defun org-tags-completion-function (string _predicate &optional flag)
15011 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15012 (confirm (lambda (x) (stringp (car x)))))
15013 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15014 (setq s1 (match-string 1 string)
15015 s2 (match-string 2 string))
15016 (setq s1 "" s2 string))
15020 (setq rtn (try-completion s2 ctable confirm))
15021 (when (stringp rtn)
15023 (concat s1 s2 (substring rtn (length s2))
15024 (if (and org-add-colon-after-tag-completion
15025 (assoc rtn ctable))
15030 (all-completions s2 ctable confirm))
15033 (assoc s2 ctable)))))
15035 (defun org-fast-tag-insert (kwd tags face &optional end)
15036 "Insert KDW, and the TAGS, the latter with face FACE.
15038 (insert (format "%-12s" (concat kwd ":"))
15039 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15042 (defun org-fast-tag-show-exit (flag)
15045 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15046 (replace-match ""))
15049 (org-move-to-column (- (window-width) 19) t)
15050 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15052 (defun org-set-current-tags-overlay (current prefix)
15053 "Add an overlay to CURRENT tag with PREFIX."
15054 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15055 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15056 (org-overlay-display org-tags-overlay (concat prefix s))))
15058 (defvar org-last-tag-selection-key nil)
15059 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15060 "Fast tag selection with single keys.
15061 CURRENT is the current list of tags in the headline, INHERITED is the
15062 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15063 possibly with grouping information. TODO-TABLE is a similar table with
15064 TODO keywords, should these have keys assigned to them.
15065 If the keys are nil, a-z are automatically assigned.
15066 Returns the new tags string, or nil to not change the current settings."
15067 (let* ((fulltable (append table todo-table))
15068 (maxlen (apply 'max (mapcar
15070 (if (stringp (car x)) (string-width (car x)) 0))
15072 (buf (current-buffer))
15073 (expert (eq org-fast-tag-selection-single-key 'expert))
15075 (fwidth (+ maxlen 3 1 3))
15076 (ncol (/ (- (window-width) 4) fwidth))
15079 tg cnt e c char c1 c2 ntable tbl rtn
15080 ov-start ov-end ov-prefix
15081 (exit-after-next org-fast-tag-selection-single-key)
15082 (done-keywords org-done-keywords)
15083 groups ingroup intaggroup)
15085 (beginning-of-line 1)
15086 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15087 (setq ov-start (match-beginning 1)
15088 ov-end (match-end 1)
15090 (setq ov-start (1- (point-at-eol))
15091 ov-end (1+ ov-start))
15092 (skip-chars-forward "^\n\r")
15095 (buffer-substring (1- (point)) (point))
15096 (if (> (current-column) org-tags-column)
15098 (make-string (- org-tags-column (current-column)) ?\ ))))))
15099 (move-overlay org-tags-overlay ov-start ov-end)
15100 (save-window-excursion
15102 (set-buffer (get-buffer-create " *Org tags*"))
15103 (delete-other-windows)
15104 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15105 (org-switch-to-buffer-other-window " *Org tags*"))
15107 (setq-local org-done-keywords done-keywords)
15108 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15109 (org-fast-tag-insert "Current" current c-face "\n\n")
15110 (org-fast-tag-show-exit exit-after-next)
15111 (org-set-current-tags-overlay current ov-prefix)
15112 (setq tbl fulltable char ?a cnt 0)
15113 (while (setq e (pop tbl))
15115 ((eq (car e) :startgroup)
15116 (push '() groups) (setq ingroup t)
15117 (unless (zerop cnt)
15120 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15121 ((eq (car e) :endgroup)
15122 (setq ingroup nil cnt 0)
15123 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15124 ((eq (car e) :startgrouptag)
15125 (setq intaggroup t)
15126 (unless (zerop cnt)
15130 ((eq (car e) :endgrouptag)
15131 (setq intaggroup nil cnt 0)
15133 ((equal e '(:newline))
15134 (unless (zerop cnt)
15138 (while (equal (car tbl) '(:newline))
15140 (setq tbl (cdr tbl)))))
15141 ((equal e '(:grouptags)) (insert " : "))
15143 (setq tg (copy-sequence (car e)) c2 nil)
15146 ;; automatically assign a character.
15147 (setq c1 (string-to-char
15148 (downcase (substring
15149 tg (if (= (string-to-char tg) ?@) 1 0)))))
15150 (if (or (rassoc c1 ntable) (rassoc c1 table))
15151 (while (or (rassoc char ntable) (rassoc char table))
15152 (setq char (1+ char)))
15154 (setq c (or c2 char)))
15155 (when ingroup (push tg (car groups)))
15156 (setq tg (org-add-props tg nil 'face
15158 ((not (assoc tg table))
15159 (org-get-todo-face tg))
15160 ((member tg current) c-face)
15161 ((member tg inherited) i-face))))
15162 (when (equal (caar tbl) :grouptags)
15163 (org-add-props tg nil 'face 'org-tag-group))
15164 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15165 (insert "[" c "] " tg (make-string
15166 (- fwidth 4 (length tg)) ?\ ))
15167 (push (cons tg c) ntable)
15168 (when (= (cl-incf cnt) ncol)
15170 (when (or ingroup intaggroup) (insert " "))
15172 (setq ntable (nreverse ntable))
15174 (goto-char (point-min))
15175 (unless expert (org-fit-window-to-buffer))
15179 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15180 (if (not groups) "no " "")
15181 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15182 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15183 (setq org-last-tag-selection-key c)
15185 ((= c ?\r) (throw 'exit t))
15187 (setq groups (not groups))
15188 (goto-char (point-min))
15189 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15192 (org-fast-tag-show-exit
15193 (setq exit-after-next (not exit-after-next)))
15195 (delete-other-windows)
15196 (set-window-buffer (split-window-vertically) " *Org tags*")
15197 (org-switch-to-buffer-other-window " *Org tags*")
15198 (org-fit-window-to-buffer)))
15200 (and (= c ?q) (not (rassoc c ntable))))
15201 (delete-overlay org-tags-overlay)
15202 (setq quit-flag t))
15205 (when exit-after-next (setq exit-after-next 'now)))
15207 (condition-case nil
15208 (setq tg (completing-read
15211 (with-current-buffer buf
15213 (org-get-buffer-tags))))))
15214 (quit (setq tg "")))
15215 (when (string-match "\\S-" tg)
15216 (cl-pushnew (list tg) buffer-tags :test #'equal)
15217 (if (member tg current)
15218 (setq current (delete tg current))
15219 (push tg current)))
15220 (when exit-after-next (setq exit-after-next 'now)))
15221 ((setq e (rassoc c todo-table) tg (car e))
15222 (with-current-buffer buf
15223 (save-excursion (org-todo tg)))
15224 (when exit-after-next (setq exit-after-next 'now)))
15225 ((setq e (rassoc c ntable) tg (car e))
15226 (if (member tg current)
15227 (setq current (delete tg current))
15228 (cl-loop for g in groups do
15229 (when (member tg g)
15230 (dolist (x g) (setq current (delete x current)))))
15232 (when exit-after-next (setq exit-after-next 'now))))
15234 ;; Create a sorted list
15238 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15239 (when (eq exit-after-next 'now) (throw 'exit t))
15240 (goto-char (point-min))
15241 (beginning-of-line 2)
15242 (delete-region (point) (point-at-eol))
15243 (org-fast-tag-insert "Current" current c-face)
15244 (org-set-current-tags-overlay current ov-prefix)
15245 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15246 (setq tg (match-string 1))
15247 (add-text-properties
15248 (match-beginning 1) (match-end 1)
15251 ((member tg current) c-face)
15252 ((member tg inherited) i-face)
15253 (t (get-text-property (match-beginning 1) 'face))))))
15254 (goto-char (point-min)))))
15255 (delete-overlay org-tags-overlay)
15257 (mapconcat 'identity current ":")
15260 (defun org-get-tags-string ()
15261 "Get the TAGS string in the current headline."
15262 (unless (org-at-heading-p t)
15263 (user-error "Not on a heading"))
15265 (beginning-of-line 1)
15266 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15267 (match-string-no-properties 1)
15270 (defun org-get-tags ()
15271 "Get the list of tags specified in the current headline."
15272 (org-split-string (org-get-tags-string) ":"))
15274 (defun org-get-buffer-tags ()
15275 "Get a table of all tags used in the buffer, for completion."
15276 (org-with-wide-buffer
15277 (goto-char (point-min))
15278 (let ((tag-re (concat org-outline-regexp-bol
15279 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15281 (while (re-search-forward tag-re nil t)
15282 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15284 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15286 ;;;; The mapping API
15288 (defvar org-agenda-skip-comment-trees)
15289 (defvar org-agenda-skip-function)
15290 (defun org-map-entries (func &optional match scope &rest skip)
15291 "Call FUNC at each headline selected by MATCH in SCOPE.
15293 FUNC is a function or a lisp form. The function will be called without
15294 arguments, with the cursor positioned at the beginning of the headline.
15295 The return values of all calls to the function will be collected and
15296 returned as a list.
15298 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15299 does not need to preserve point. After evaluation, the cursor will be
15300 moved to the end of the line (presumably of the headline of the
15301 processed entry) and search continues from there. Under some
15302 circumstances, this may not produce the wanted results. For example,
15303 if you have removed (e.g. archived) the current (sub)tree it could
15304 mean that the next entry will be skipped entirely. In such cases, you
15305 can specify the position from where search should continue by making
15306 FUNC set the variable `org-map-continue-from' to the desired buffer
15309 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15310 Only headlines that are matched by this query will be considered during
15311 the iteration. When MATCH is nil or t, all headlines will be
15312 visited by the iteration.
15314 SCOPE determines the scope of this command. It can be any of:
15316 nil The current buffer, respecting the restriction if any
15317 tree The subtree started with the entry at point
15318 region The entries within the active region, if any
15320 The entries within the active region, but only those at
15321 the same level than the first one.
15322 file The current buffer, without restriction
15324 The current buffer, and any archives associated with it
15325 agenda All agenda files
15326 agenda-with-archives
15327 All agenda files with any archive files associated with them
15329 If this is a list, all files in the list will be scanned
15331 The remaining args are treated as settings for the skipping facilities of
15332 the scanner. The following items can be given here:
15334 archive skip trees with the archive tag
15335 comment skip trees with the COMMENT keyword
15336 function or Emacs Lisp form:
15337 will be used as value for `org-agenda-skip-function', so
15338 whenever the function returns a position, FUNC will not be
15339 called for that entry and search will continue from the
15342 If your function needs to retrieve the tags including inherited tags
15343 at the *current* entry, you can use the value of the variable
15344 `org-scanner-tags' which will be much faster than getting the value
15345 with `org-get-tags-at'. If your function gets properties with
15346 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15347 to t around the call to `org-entry-properties' to get the same speedup.
15348 Note that if your function moves around to retrieve tags and properties at
15349 a *different* entry, you cannot use these techniques."
15350 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15351 (not (org-region-active-p)))
15352 (let* ((org-agenda-archives-mode nil) ; just to make sure
15353 (org-agenda-skip-archived-trees (memq 'archive skip))
15354 (org-agenda-skip-comment-trees (memq 'comment skip))
15355 (org-agenda-skip-function
15356 (car (org-delete-all '(comment archive) skip)))
15357 (org-tags-match-list-sublevels t)
15358 (start-level (eq scope 'region-start-level))
15360 org-todo-keywords-for-agenda
15361 org-done-keywords-for-agenda
15362 org-todo-keyword-alist-for-agenda
15363 org-tag-alist-for-agenda
15364 org--matcher-tags-todo-only)
15367 ((eq match t) (setq matcher t))
15368 ((eq match nil) (setq matcher t))
15369 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15373 (cond ((eq scope 'tree)
15374 (org-back-to-heading t)
15375 (org-narrow-to-subtree)
15377 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15378 (org-region-active-p))
15379 ;; If needed, set start-level to a string like "2"
15382 (goto-char (region-beginning))
15383 (unless (org-at-heading-p) (outline-next-heading))
15384 (setq start-level (org-current-level))))
15385 (narrow-to-region (region-beginning)
15387 (goto-char (region-end))
15388 (unless (and (bolp) (org-at-heading-p))
15389 (outline-next-heading))
15395 (org-agenda-prepare-buffers
15396 (and buffer-file-name (list buffer-file-name)))
15399 func matcher org--matcher-tags-todo-only start-level)))
15400 ;; Get the right scope
15402 ((and scope (listp scope) (symbolp (car scope)))
15403 (setq scope (eval scope)))
15404 ((eq scope 'agenda)
15405 (setq scope (org-agenda-files t)))
15406 ((eq scope 'agenda-with-archives)
15407 (setq scope (org-agenda-files t))
15408 (setq scope (org-add-archive-files scope)))
15410 (setq scope (and buffer-file-name (list buffer-file-name))))
15411 ((eq scope 'file-with-archives)
15412 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15413 (org-agenda-prepare-buffers scope)
15414 (dolist (file scope)
15415 (with-current-buffer (org-find-base-buffer-visiting file)
15416 (org-with-wide-buffer
15417 (goto-char (point-min))
15422 func matcher org--matcher-tags-todo-only)))))))))
15427 (defconst org-special-properties
15428 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15429 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15430 "The special properties valid in Org mode.
15431 These are properties that are not defined in the property drawer,
15432 but in some other way.")
15434 (defconst org-default-properties
15435 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15436 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15437 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15438 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15439 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15440 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15441 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15442 "Some properties that are used by Org mode for various purposes.
15443 Being in this list makes sure that they are offered for completion.")
15445 (defun org--valid-property-p (property)
15446 "Non nil when string PROPERTY is a valid property name."
15448 (or (equal property "")
15449 (string-match-p "\\s-" property))))
15451 (defun org--update-property-plist (key val props)
15452 "Associate KEY to VAL in alist PROPS.
15453 Modifications are made by side-effect. Return new alist."
15454 (let* ((appending (string= (substring key -1) "+"))
15455 (key (if appending (substring key 0 -1) key))
15456 (old (assoc-string key props t)))
15457 (if (not old) (cons (cons key val) props)
15458 (setcdr old (if appending (concat (cdr old) " " val) val))
15461 (defun org-get-property-block (&optional beg force)
15462 "Return the (beg . end) range of the body of the property drawer.
15463 BEG is the beginning of the current subtree, or of the part
15464 before the first headline. If it is not given, it will be found.
15465 If the drawer does not exist, create it if FORCE is non-nil, or
15467 (org-with-wide-buffer
15468 (when beg (goto-char beg))
15469 (unless (org-before-first-heading-p)
15470 (let ((beg (cond (beg)
15471 ((or (not (featurep 'org-inlinetask))
15472 (org-inlinetask-in-task-p))
15473 (org-back-to-heading t))
15474 (t (org-with-limited-levels (org-back-to-heading t))))))
15476 (when (looking-at-p org-planning-line-re) (forward-line))
15477 (cond ((looking-at org-property-drawer-re)
15479 (cons (point) (progn (goto-char (match-end 0))
15480 (line-beginning-position))))
15483 (org-insert-property-drawer)
15484 (let ((pos (save-excursion (search-forward ":END:")
15485 (line-beginning-position))))
15486 (cons pos pos))))))))
15488 (defun org-at-property-p ()
15489 "Non-nil when point is inside a property drawer.
15490 See `org-property-re' for match data, if applicable."
15492 (beginning-of-line)
15493 (and (looking-at org-property-re)
15494 (let ((property-drawer (save-match-data (org-get-property-block))))
15495 (and property-drawer
15496 (>= (point) (car property-drawer))
15497 (< (point) (cdr property-drawer)))))))
15499 (defun org-property-action ()
15500 "Do an action on properties."
15502 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15503 (let ((c (read-char-exclusive)))
15505 (?s (call-interactively #'org-set-property))
15506 (?d (call-interactively #'org-delete-property))
15507 (?D (call-interactively #'org-delete-property-globally))
15508 (?c (call-interactively #'org-compute-property-at-point))
15509 (otherwise (user-error "No such property action %c" c)))))
15511 (defun org-inc-effort ()
15512 "Increment the value of the effort property in the current entry."
15514 (org-set-effort nil t))
15516 (defvar org-clock-effort) ; Defined in org-clock.el.
15517 (defvar org-clock-current-task) ; Defined in org-clock.el.
15518 (defun org-set-effort (&optional value increment)
15519 "Set the effort property of the current entry.
15520 With numerical prefix arg, use the nth allowed value, 0 stands for the
15521 10th allowed value.
15523 When INCREMENT is non-nil, set the property to the next allowed value."
15525 (when (equal value 0) (setq value 10))
15526 (let* ((completion-ignore-case t)
15527 (prop org-effort-property)
15528 (cur (org-entry-get nil prop))
15529 (allowed (org-property-get-allowed-values nil prop 'table))
15530 (existing (mapcar 'list (org-property-values prop)))
15531 (heading (nth 4 (org-heading-components)))
15534 ((stringp value) value)
15535 ((and allowed (integerp value))
15536 (or (car (nth (1- value) allowed))
15537 (car (org-last allowed))))
15538 ((and allowed increment)
15539 (or (cl-caadr (member (list cur) allowed))
15540 (user-error "Allowed effort values are not set")))
15542 (message "Select 1-9,0, [RET%s]: %s"
15543 (if cur (concat "=" cur) "")
15544 (mapconcat 'car allowed " "))
15545 (setq rpl (read-char-exclusive))
15546 (if (equal rpl ?\r)
15548 (setq rpl (- rpl ?0))
15549 (when (equal rpl 0) (setq rpl 10))
15550 (if (and (> rpl 0) (<= rpl (length allowed)))
15551 (car (nth (1- rpl) allowed))
15552 (org-completing-read "Effort: " allowed nil))))
15554 (org-completing-read
15555 (concat "Effort" (and cur (string-match "\\S-" cur)
15556 (concat " [" cur "]"))
15558 existing nil nil "" nil cur)))))
15559 (unless (equal (org-entry-get nil prop) val)
15560 (org-entry-put nil prop val))
15561 (org-refresh-property
15562 '((effort . identity)
15563 (effort-minutes . org-duration-to-minutes))
15565 (when (equal heading (bound-and-true-p org-clock-current-task))
15566 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15567 (org-clock-update-mode-line))
15568 (message "%s is now %s" prop val)))
15570 (defun org-entry-properties (&optional pom which)
15571 "Get all properties of the current entry.
15573 When POM is a buffer position, get all properties from the entry
15576 This includes the TODO keyword, the tags, time strings for
15577 deadline, scheduled, and clocking, and any additional properties
15578 defined in the entry.
15580 If WHICH is nil or `all', get all properties. If WHICH is
15581 `special' or `standard', only get that subclass. If WHICH is
15582 a string, only get that property.
15584 Return value is an alist. Keys are properties, as upcased
15586 (org-with-point-at pom
15587 (when (and (derived-mode-p 'org-mode)
15588 (ignore-errors (org-back-to-heading t)))
15590 (let* ((beg (point))
15591 (specific (and (stringp which) (upcase which)))
15592 (which (cond ((not specific) which)
15593 ((member specific org-special-properties) 'special)
15596 ;; Get the special properties, like TODO and TAGS.
15597 (when (memq which '(nil all special))
15598 (when (or (not specific) (string= specific "CLOCKSUM"))
15599 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15601 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15603 (when specific (throw 'exit props)))
15604 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15605 (let ((clocksumt (get-text-property (point)
15606 :org-clock-minutes-today)))
15608 (push (cons "CLOCKSUM_T"
15609 (org-duration-from-minutes clocksumt))
15611 (when specific (throw 'exit props)))
15612 (when (or (not specific) (string= specific "ITEM"))
15613 (let ((case-fold-search nil))
15614 (when (looking-at org-complex-heading-regexp)
15616 (let ((title (match-string-no-properties 4)))
15617 (if (org-string-nw-p title)
15618 (org-remove-tabs title)
15621 (when specific (throw 'exit props)))
15622 (when (or (not specific) (string= specific "TODO"))
15623 (let ((case-fold-search nil))
15624 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15625 (push (cons "TODO" (match-string-no-properties 2)) props)))
15626 (when specific (throw 'exit props)))
15627 (when (or (not specific) (string= specific "PRIORITY"))
15628 (push (cons "PRIORITY"
15629 (if (looking-at org-priority-regexp)
15630 (match-string-no-properties 2)
15631 (char-to-string org-default-priority)))
15633 (when specific (throw 'exit props)))
15634 (when (or (not specific) (string= specific "FILE"))
15635 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific) (string= specific "TAGS"))
15639 (let ((value (org-string-nw-p (org-get-tags-string))))
15640 (when value (push (cons "TAGS" value) props)))
15641 (when specific (throw 'exit props)))
15642 (when (or (not specific) (string= specific "ALLTAGS"))
15643 (let ((value (org-get-tags-at)))
15645 (push (cons "ALLTAGS"
15646 (format ":%s:" (mapconcat #'identity value ":")))
15648 (when specific (throw 'exit props)))
15649 (when (or (not specific) (string= specific "BLOCKED"))
15650 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15651 (when specific (throw 'exit props)))
15652 (when (or (not specific)
15653 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15655 (when (looking-at-p org-planning-line-re)
15657 (let ((bol (line-beginning-position))
15658 ;; Backward compatibility: time keywords used to
15659 ;; be configurable (before 8.3). Make sure we
15660 ;; get the correct keyword.
15661 (key-assoc `(("CLOSED" . ,org-closed-string)
15662 ("DEADLINE" . ,org-deadline-string)
15663 ("SCHEDULED" . ,org-scheduled-string))))
15664 (dolist (pair (if specific (list (assoc specific key-assoc))
15667 (when (search-backward (cdr pair) bol t)
15668 (goto-char (match-end 0))
15669 (skip-chars-forward " \t")
15670 (and (looking-at org-ts-regexp-both)
15671 (push (cons (car pair)
15672 (match-string-no-properties 0))
15674 (when specific (throw 'exit props)))
15675 (when (or (not specific)
15676 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15679 ;; Fix next time-stamp before END. TS is the
15680 ;; list of time-stamps found so far.
15683 ((string= specific "TIMESTAMP")
15685 ((string= specific "TIMESTAMP_IA")
15686 org-ts-regexp-inactive)
15687 ((assoc "TIMESTAMP_IA" ts)
15689 ((assoc "TIMESTAMP" ts)
15690 org-ts-regexp-inactive)
15691 (t org-ts-regexp-both))))
15693 (while (re-search-forward regexp end t)
15695 (let ((object (org-element-context)))
15696 ;; Accept to match timestamps in node
15697 ;; properties, too.
15698 (when (memq (org-element-type object)
15699 '(node-property timestamp))
15701 (org-element-property :type object)))
15703 ((and (memq type '(active active-range))
15704 (not (equal specific "TIMESTAMP_IA")))
15705 (unless (assoc "TIMESTAMP" ts)
15706 (push (cons "TIMESTAMP"
15707 (org-element-property
15708 :raw-value object))
15710 (when specific (throw 'exit ts))))
15711 ((and (memq type '(inactive inactive-range))
15712 (not (string= specific "TIMESTAMP")))
15713 (unless (assoc "TIMESTAMP_IA" ts)
15714 (push (cons "TIMESTAMP_IA"
15715 (org-element-property
15716 :raw-value object))
15718 (when specific (throw 'exit ts))))))
15719 ;; Both timestamp types are found,
15720 ;; move to next part.
15721 (when (= (length ts) 2) (throw 'next ts)))))
15724 ;; First look for timestamps within headline.
15725 (let ((ts (funcall find-ts (line-end-position) nil)))
15726 (if (= (length ts) 2) (setq props (nconc ts props))
15727 ;; Then find timestamps in the section, skipping
15729 (let ((end (save-excursion (outline-next-heading))))
15731 (when (looking-at-p org-planning-line-re) (forward-line))
15732 (setq props (nconc (funcall find-ts end ts) props))))))))
15733 ;; Get the standard properties, like :PROP:.
15734 (when (memq which '(nil all standard))
15735 ;; If we are looking after a specific property, delegate
15736 ;; to `org-entry-get', which is faster. However, make an
15737 ;; exception for "CATEGORY", since it can be also set
15738 ;; through keywords (i.e. #+CATEGORY).
15739 (if (and specific (not (equal specific "CATEGORY")))
15740 (let ((value (org-entry-get beg specific nil t)))
15741 (throw 'exit (and value (list (cons specific value)))))
15742 (let ((range (org-get-property-block beg)))
15744 (let ((end (cdr range)) seen-base)
15745 (goto-char (car range))
15746 ;; Unlike to `org--update-property-plist', we
15747 ;; handle the case where base values is found
15748 ;; after its extension. We also forbid standard
15749 ;; properties to be named as special properties.
15750 (while (re-search-forward org-property-re end t)
15751 (let* ((key (upcase (match-string-no-properties 2)))
15752 (extendp (string-match-p "\\+\\'" key))
15753 (key-base (if extendp (substring key 0 -1) key))
15754 (value (match-string-no-properties 3)))
15756 ((member-ignore-case key-base org-special-properties))
15759 (org--update-property-plist key value props)))
15760 ((member key seen-base))
15761 (t (push key seen-base)
15762 (let ((p (assoc-string key props t)))
15763 (if p (setcdr p (concat value " " (cdr p)))
15764 (push (cons key value) props))))))))))))
15765 (unless (assoc "CATEGORY" props)
15766 (push (cons "CATEGORY" (org-get-category beg)) props)
15767 (when (string= specific "CATEGORY") (throw 'exit props)))
15771 (defun org--property-local-values (property literal-nil)
15772 "Return value for PROPERTY in current entry.
15773 Value is a list whose car is the base value for PROPERTY and cdr
15774 a list of accumulated values. Return nil if neither is found in
15775 the entry. Also return nil when PROPERTY is set to \"nil\",
15776 unless LITERAL-NIL is non-nil."
15777 (let ((range (org-get-property-block)))
15779 (goto-char (car range))
15780 (let* ((case-fold-search t)
15785 (let ((v (and (re-search-forward
15786 (org-re-property property nil t) end t)
15787 (match-string-no-properties 3))))
15788 (list (if literal-nil v (org-not-nil v)))))))
15789 ;; Find additional values.
15790 (let* ((property+ (org-re-property (concat property "+") nil t)))
15791 (while (re-search-forward property+ end t)
15792 (push (match-string-no-properties 3) value)))
15793 ;; Return final values.
15794 (and (not (equal value '(nil))) (nreverse value))))))
15796 (defun org--property-global-value (property literal-nil)
15797 "Return value for PROPERTY in current buffer.
15798 Return value is a string. Return nil if property is not set
15799 globally. Also return nil when PROPERTY is set to \"nil\",
15800 unless LITERAL-NIL is non-nil."
15802 (cdr (or (assoc-string property org-file-properties t)
15803 (assoc-string property org-global-properties t)
15804 (assoc-string property org-global-properties-fixed t)))))
15805 (if literal-nil global (org-not-nil global))))
15807 (defun org-entry-get (pom property &optional inherit literal-nil)
15808 "Get value of PROPERTY for entry or content at point-or-marker POM.
15810 If INHERIT is non-nil and the entry does not have the property,
15811 then also check higher levels of the hierarchy. If INHERIT is
15812 the symbol `selective', use inheritance only if the setting in
15813 `org-use-property-inheritance' selects PROPERTY for inheritance.
15815 If the property is present but empty, the return value is the
15816 empty string. If the property is not present at all, nil is
15817 returned. In any other case, return the value as a string.
15818 Search is case-insensitive.
15820 If LITERAL-NIL is set, return the string value \"nil\" as
15821 a string, do not interpret it as the list atom nil. This is used
15822 for inheritance when a \"nil\" value can supersede a non-nil
15823 value higher up the hierarchy."
15824 (org-with-point-at pom
15826 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15827 ;; We need a special property. Use `org-entry-properties' to
15828 ;; retrieve it, but specify the wanted property.
15829 (cdr (assoc-string property (org-entry-properties nil property))))
15831 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15832 (org-entry-get-with-inheritance property literal-nil))
15834 (let* ((local (org--property-local-values property literal-nil))
15835 (value (and local (mapconcat #'identity (delq nil local) " "))))
15836 (if literal-nil value (org-not-nil value)))))))
15838 (defun org-property-or-variable-value (var &optional inherit)
15839 "Check if there is a property fixing the value of VAR.
15840 If yes, return this value. If not, return the current value of the variable."
15841 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15842 (if (and prop (stringp prop) (string-match "\\S-" prop))
15844 (symbol-value var))))
15846 (defun org-entry-delete (pom property)
15847 "Delete PROPERTY from entry at point-or-marker POM.
15848 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15849 non-nil when a property was removed."
15850 (org-with-point-at pom
15851 (pcase (org-get-property-block)
15852 (`(,begin . ,origin)
15853 (let* ((end (copy-marker origin))
15854 (re (org-re-property
15855 (concat (regexp-quote property) "\\+?") t t)))
15857 (while (re-search-forward re end t)
15858 (delete-region (match-beginning 0) (line-beginning-position 2)))
15859 ;; If drawer is empty, remove it altogether.
15860 (when (= begin end)
15861 (delete-region (line-beginning-position 0)
15862 (line-beginning-position 2)))
15863 ;; Return non-nil if some property was removed.
15864 (prog1 (/= end origin) (set-marker end nil))))
15867 ;; Multi-values properties are properties that contain multiple values
15868 ;; These values are assumed to be single words, separated by whitespace.
15869 (defun org-entry-add-to-multivalued-property (pom property value)
15870 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15871 (let* ((old (org-entry-get pom property))
15872 (values (and old (split-string old))))
15873 (setq value (org-entry-protect-space value))
15874 (unless (member value values)
15875 (setq values (append values (list value)))
15876 (org-entry-put pom property (mapconcat #'identity values " ")))))
15878 (defun org-entry-remove-from-multivalued-property (pom property value)
15879 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15880 (let* ((old (org-entry-get pom property))
15881 (values (and old (split-string old))))
15882 (setq value (org-entry-protect-space value))
15883 (when (member value values)
15884 (setq values (delete value values))
15885 (org-entry-put pom property (mapconcat #'identity values " ")))))
15887 (defun org-entry-member-in-multivalued-property (pom property value)
15888 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15889 (let* ((old (org-entry-get pom property))
15890 (values (and old (split-string old))))
15891 (setq value (org-entry-protect-space value))
15892 (member value values)))
15894 (defun org-entry-get-multivalued-property (pom property)
15895 "Return a list of values in a multivalued property."
15896 (let* ((value (org-entry-get pom property))
15897 (values (and value (split-string value))))
15898 (mapcar #'org-entry-restore-space values)))
15900 (defun org-entry-put-multivalued-property (pom property &rest values)
15901 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15902 VALUES should be a list of strings. Spaces will be protected."
15903 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15904 (let* ((value (org-entry-get pom property))
15905 (values (and value (split-string value))))
15906 (mapcar #'org-entry-restore-space values)))
15908 (defun org-entry-protect-space (s)
15909 "Protect spaces and newline in string S."
15910 (while (string-match " " s)
15911 (setq s (replace-match "%20" t t s)))
15912 (while (string-match "\n" s)
15913 (setq s (replace-match "%0A" t t s)))
15916 (defun org-entry-restore-space (s)
15917 "Restore spaces and newline in string S."
15918 (while (string-match "%20" s)
15919 (setq s (replace-match " " t t s)))
15920 (while (string-match "%0A" s)
15921 (setq s (replace-match "\n" t t s)))
15924 (defvar org-entry-property-inherited-from (make-marker)
15925 "Marker pointing to the entry from where a property was inherited.
15926 Each call to `org-entry-get-with-inheritance' will set this marker to the
15927 location of the entry where the inheritance search matched. If there was
15928 no match, the marker will point nowhere.
15929 Note that also `org-entry-get' calls this function, if the INHERIT flag
15932 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15933 "Get PROPERTY of entry or content at point, search higher levels if needed.
15934 The search will stop at the first ancestor which has the property defined.
15935 If the value found is \"nil\", return nil to show that the property
15936 should be considered as undefined (this is the meaning of nil here).
15937 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15938 (move-marker org-entry-property-inherited-from nil)
15939 (org-with-wide-buffer
15943 (let ((v (org--property-local-values property literal-nil)))
15946 (concat (mapconcat #'identity (delq nil v) " ")
15951 (org-back-to-heading t)
15952 (move-marker org-entry-property-inherited-from (point))
15954 ((org-up-heading-safe))
15956 (let ((global (org--property-global-value property literal-nil)))
15957 (cond ((not global))
15958 (value (setq value (concat global " " value)))
15959 (t (setq value global))))
15960 (throw 'exit nil))))))
15961 (if literal-nil value (org-not-nil value)))))
15963 (defvar org-property-changed-functions nil
15964 "Hook called when the value of a property has changed.
15965 Each hook function should accept two arguments, the name of the property
15966 and the new value.")
15968 (defun org-entry-put (pom property value)
15969 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15971 If the value is nil, it is converted to the empty string. If it
15972 is not a string, an error is raised. Also raise an error on
15973 invalid property names.
15975 PROPERTY can be any regular property (see
15976 `org-special-properties'). It can also be \"TODO\",
15977 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15979 For the last two properties, VALUE may have any of the special
15980 values \"earlier\" and \"later\". The function then increases or
15981 decreases scheduled or deadline date by one day."
15982 (cond ((null value) (setq value ""))
15983 ((not (stringp value)) (error "Properties values should be strings"))
15984 ((not (org--valid-property-p property))
15985 (user-error "Invalid property name: \"%s\"" property)))
15986 (org-with-point-at pom
15987 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15988 (org-back-to-heading t)
15989 (org-with-limited-levels (org-back-to-heading t)))
15990 (let ((beg (point)))
15992 ((equal property "TODO")
15993 (cond ((not (org-string-nw-p value)) (setq value 'none))
15994 ((not (member value org-todo-keywords-1))
15995 (user-error "\"%s\" is not a valid TODO state" value)))
15997 (org-set-tags nil 'align))
15998 ((equal property "PRIORITY")
15999 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16000 (org-set-tags nil 'align))
16001 ((equal property "SCHEDULED")
16003 (if (and (looking-at-p org-planning-line-re)
16005 org-scheduled-time-regexp (line-end-position) t))
16006 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16007 ((string= value "later") (org-timestamp-change 1 'day))
16008 ((string= value "") (org-schedule '(4)))
16009 (t (org-schedule nil value)))
16010 (if (member value '("earlier" "later" ""))
16011 (call-interactively #'org-schedule)
16012 (org-schedule nil value))))
16013 ((equal property "DEADLINE")
16015 (if (and (looking-at-p org-planning-line-re)
16017 org-deadline-time-regexp (line-end-position) t))
16018 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16019 ((string= value "later") (org-timestamp-change 1 'day))
16020 ((string= value "") (org-deadline '(4)))
16021 (t (org-deadline nil value)))
16022 (if (member value '("earlier" "later" ""))
16023 (call-interactively #'org-deadline)
16024 (org-deadline nil value))))
16025 ((member property org-special-properties)
16026 (error "The %s property cannot be set with `org-entry-put'" property))
16028 (let* ((range (org-get-property-block beg 'force))
16030 (case-fold-search t))
16031 (goto-char (car range))
16032 (if (re-search-forward (org-re-property property nil t) end t)
16033 (progn (delete-region (match-beginning 0) (match-end 0))
16034 (goto-char (match-beginning 0)))
16038 (insert ":" property ":")
16039 (when value (insert " " value))
16040 (org-indent-line)))))
16041 (run-hook-with-args 'org-property-changed-functions property value)))
16043 (defun org-buffer-property-keys
16044 (&optional specials defaults columns ignore-malformed)
16045 "Get all property keys in the current buffer.
16047 When SPECIALS is non-nil, also list the special properties that
16048 reflect things like tags and TODO state.
16050 When DEFAULTS is non-nil, also include properties that has
16051 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16052 DESCRIPTION, LOCATION, and LOGGING and others.
16054 When COLUMNS in non-nil, also include property names given in
16055 COLUMN formats in the current buffer.
16057 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16058 automatically performed, such drawers will be silently ignored."
16059 (let ((case-fold-search t)
16061 (and specials org-special-properties)
16062 (and defaults (cons org-effort-property org-default-properties))
16064 (org-with-wide-buffer
16065 (goto-char (point-min))
16066 (while (re-search-forward org-property-start-re nil t)
16067 (let ((range (org-get-property-block)))
16070 (when (and (not ignore-malformed)
16071 (not (org-before-first-heading-p))
16072 (y-or-n-p (format "Malformed drawer at %d, repair?"
16073 (line-beginning-position))))
16074 (org-get-property-block nil t))
16076 (goto-char (car range))
16077 (let ((begin (car range))
16079 ;; Make sure that found property block is not located
16080 ;; before current point, as it would generate an infloop.
16081 ;; It can happen, for example, in the following
16088 ;; *************** Inlinetask
16093 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16094 (while (< (point) end)
16095 (let ((p (progn (looking-at org-property-re)
16096 (match-string-no-properties 2))))
16097 ;; Only add true property name, not extension symbol.
16098 (push (if (not (string-match-p "\\+\\'" p)) p
16099 (substring p 0 -1))
16102 (outline-next-heading)))
16104 (goto-char (point-min))
16105 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16106 (let ((element (org-element-at-point)))
16107 (when (memq (org-element-type element) '(keyword node-property))
16108 (let ((value (org-element-property :value element))
16110 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16113 (setq start (match-end 0))
16114 (let ((p (match-string-no-properties 1 value)))
16115 (unless (member-ignore-case p org-special-properties)
16116 (push p props))))))))))
16117 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16119 (defun org-property-values (key)
16120 "List all non-nil values of property KEY in current buffer."
16121 (org-with-wide-buffer
16122 (goto-char (point-min))
16123 (let ((case-fold-search t)
16124 (re (org-re-property key))
16126 (while (re-search-forward re nil t)
16127 (push (org-entry-get (point) key) values))
16128 (delete-dups values))))
16130 (defun org-insert-property-drawer ()
16131 "Insert a property drawer into the current entry."
16132 (org-with-wide-buffer
16133 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16134 (org-back-to-heading t)
16135 (org-with-limited-levels (org-back-to-heading t)))
16137 (when (looking-at-p org-planning-line-re) (forward-line))
16138 (unless (looking-at-p org-property-drawer-re)
16139 ;; Make sure we start editing a line from current entry, not from
16140 ;; next one. It prevents extending text properties or overlays
16141 ;; belonging to the latter.
16142 (when (bolp) (backward-char))
16143 (let ((begin (1+ (point)))
16144 (inhibit-read-only t))
16145 (insert "\n:PROPERTIES:\n:END:")
16146 (when (eobp) (insert "\n"))
16147 (org-indent-region begin (point))))))
16149 (defun org-insert-drawer (&optional arg drawer)
16150 "Insert a drawer at point.
16152 When optional argument ARG is non-nil, insert a property drawer.
16154 Optional argument DRAWER, when non-nil, is a string representing
16155 drawer's name. Otherwise, the user is prompted for a name.
16157 If a region is active, insert the drawer around that region
16160 Point is left between drawer's boundaries."
16162 (let* ((drawer (if arg "PROPERTIES"
16163 (or drawer (read-from-minibuffer "Drawer: ")))))
16165 ;; With C-u, fall back on `org-insert-property-drawer'
16166 (arg (org-insert-property-drawer))
16167 ;; Check validity of suggested drawer's name.
16168 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16169 (user-error "Invalid drawer name"))
16170 ;; With an active region, insert a drawer at point.
16171 ((not (org-region-active-p))
16173 (unless (bolp) (insert "\n"))
16174 (insert (format ":%s:\n\n:END:\n" drawer))
16175 (forward-line -2)))
16176 ;; Otherwise, insert the drawer at point
16178 (let ((rbeg (region-beginning))
16179 (rend (copy-marker (region-end))))
16183 (beginning-of-line)
16184 (when (save-excursion
16185 (re-search-forward org-outline-regexp-bol rend t))
16186 (user-error "Drawers cannot contain headlines"))
16187 ;; Position point at the beginning of the first
16188 ;; non-blank line in region. Insert drawer's opening
16189 ;; there, then indent it.
16190 (org-skip-whitespace)
16191 (beginning-of-line)
16192 (insert ":" drawer ":\n")
16194 (indent-for-tab-command)
16195 ;; Move point to the beginning of the first blank line
16196 ;; after the last non-blank line in region. Insert
16197 ;; drawer's closing, then indent it.
16199 (skip-chars-backward " \r\t\n")
16201 (deactivate-mark t)
16202 (indent-for-tab-command)
16203 (unless (eolp) (insert "\n")))
16204 ;; Clear marker, whatever the outcome of insertion is.
16205 (set-marker rend nil)))))))
16207 (defvar org-property-set-functions-alist nil
16208 "Property set function alist.
16209 Each entry should have the following format:
16211 (PROPERTY . READ-FUNCTION)
16213 The read function will be called with the same argument as
16214 `org-completing-read'.")
16216 (defun org-set-property-function (property)
16217 "Get the function that should be used to set PROPERTY.
16218 This is computed according to `org-property-set-functions-alist'."
16219 (or (cdr (assoc property org-property-set-functions-alist))
16220 'org-completing-read))
16222 (defun org-read-property-value (property)
16223 "Read PROPERTY value from user."
16224 (let* ((completion-ignore-case t)
16225 (allowed (org-property-get-allowed-values nil property 'table))
16226 (cur (org-entry-get nil property))
16227 (prompt (concat property " value"
16228 (if (and cur (string-match "\\S-" cur))
16229 (concat " [" cur "]") "") ": "))
16230 (set-function (org-set-property-function property))
16232 (funcall set-function prompt allowed nil
16233 (not (get-text-property 0 'org-unrestricted
16235 (funcall set-function prompt
16236 (mapcar 'list (org-property-values property))
16237 nil nil "" nil cur))))
16240 (defvar org-last-set-property nil)
16241 (defvar org-last-set-property-value nil)
16242 (defun org-read-property-name ()
16243 "Read a property name."
16244 (let ((completion-ignore-case t)
16245 (default-prop (or (and (org-at-property-p)
16246 (match-string-no-properties 2))
16247 org-last-set-property)))
16248 (org-completing-read
16250 (if default-prop (concat " [" default-prop "]") "")
16252 (mapcar #'list (org-buffer-property-keys nil t t))
16253 nil nil nil nil default-prop)))
16255 (defun org-set-property-and-value (use-last)
16256 "Allow to set [PROPERTY]: [value] direction from prompt.
16257 When use-default, don't even ask, just use the last
16258 \"[PROPERTY]: [value]\" string from the history."
16260 (let* ((completion-ignore-case t)
16261 (pv (or (and use-last org-last-set-property-value)
16262 (org-completing-read
16263 "Enter a \"[Property]: [value]\" pair: "
16264 nil nil nil nil nil
16265 org-last-set-property-value)))
16267 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16268 (setq prop (match-string 1 pv)
16269 val (match-string 2 pv))
16270 (org-set-property prop val))))
16272 (defun org-set-property (property value)
16273 "In the current entry, set PROPERTY to VALUE.
16275 When called interactively, this will prompt for a property name, offering
16276 completion on existing and default properties. And then it will prompt
16277 for a value, offering completion either on allowed values (via an inherited
16278 xxx_ALL property) or on existing values in other instances of this property
16279 in the current file.
16281 Throw an error when trying to set a property with an invalid name."
16282 (interactive (list nil nil))
16283 (let ((property (or property (org-read-property-name))))
16284 ;; `org-entry-put' also makes the following check, but this one
16285 ;; avoids polluting `org-last-set-property' and
16286 ;; `org-last-set-property-value' needlessly.
16287 (unless (org--valid-property-p property)
16288 (user-error "Invalid property name: \"%s\"" property))
16289 (let ((value (or value (org-read-property-value property)))
16290 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16291 (setq org-last-set-property property)
16292 (setq org-last-set-property-value (concat property ": " value))
16293 ;; Possibly postprocess the inserted value:
16294 (when fn (setq value (funcall fn value)))
16295 (unless (equal (org-entry-get nil property) value)
16296 (org-entry-put nil property value)))))
16298 (defun org-find-property (property &optional value)
16299 "Find first entry in buffer that sets PROPERTY.
16301 When optional argument VALUE is non-nil, only consider an entry
16302 if it contains PROPERTY set to this value. If PROPERTY should be
16303 explicitly set to nil, use string \"nil\" for VALUE.
16305 Return position where the entry begins, or nil if there is no
16306 such entry. If narrowing is in effect, only search the visible
16307 part of the buffer."
16309 (goto-char (point-min))
16310 (let ((case-fold-search t)
16311 (re (org-re-property property nil (not value) value)))
16313 (while (re-search-forward re nil t)
16314 (when (if value (org-at-property-p)
16315 (org-entry-get (point) property nil t))
16316 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16318 (defun org-delete-property (property)
16319 "In the current entry, delete PROPERTY."
16321 (let* ((completion-ignore-case t)
16322 (cat (org-entry-get (point) "CATEGORY"))
16323 (props0 (org-entry-properties nil 'standard))
16324 (props (if cat props0
16325 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16326 (prop (if (< 1 (length props))
16327 (completing-read "Property: " props nil t)
16331 (message "No property to delete in this entry")
16332 (org-entry-delete nil property)
16333 (message "Property \"%s\" deleted" property)))
16335 (defun org-delete-property-globally (property)
16336 "Remove PROPERTY globally, from all entries.
16337 This function ignores narrowing, if any."
16339 (let* ((completion-ignore-case t)
16340 (prop (completing-read
16341 "Globally remove property: "
16342 (mapcar #'list (org-buffer-property-keys)))))
16344 (org-with-wide-buffer
16345 (goto-char (point-min))
16347 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16348 (while (re-search-forward re nil t)
16349 (when (org-entry-delete (point) property) (cl-incf count)))
16350 (message "Property \"%s\" removed from %d entries" property count))))
16352 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16354 (defun org-compute-property-at-point ()
16355 "Compute the property at point.
16356 This looks for an enclosing column format, extracts the operator and
16357 then applies it to the property in the column format's scope."
16359 (unless (org-at-property-p)
16360 (user-error "Not at a property"))
16361 (let ((prop (match-string-no-properties 2)))
16362 (org-columns-get-format-and-top-level)
16363 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16364 (user-error "No operator defined for property %s" prop))
16365 (org-columns-compute prop)))
16367 (defvar org-property-allowed-value-functions nil
16368 "Hook for functions supplying allowed values for a specific property.
16369 The functions must take a single argument, the name of the property, and
16370 return a flat list of allowed values. If \":ETC\" is one of
16371 the values, this means that these values are intended as defaults for
16372 completion, but that other values should be allowed too.
16373 The functions must return nil if they are not responsible for this
16376 (defun org-property-get-allowed-values (pom property &optional table)
16377 "Get allowed values for the property PROPERTY.
16378 When TABLE is non-nil, return an alist that can directly be used for
16382 ((equal property "TODO")
16383 (setq vals (org-with-point-at pom
16384 (append org-todo-keywords-1 '("")))))
16385 ((equal property "PRIORITY")
16386 (let ((n org-lowest-priority))
16387 (while (>= n org-highest-priority)
16388 (push (char-to-string n) vals)
16390 ((equal property "CATEGORY"))
16391 ((member property org-special-properties))
16392 ((setq vals (run-hook-with-args-until-success
16393 'org-property-allowed-value-functions property)))
16395 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16396 (when (and vals (string-match "\\S-" vals))
16397 (setq vals (car (read-from-string (concat "(" vals ")"))))
16398 (setq vals (mapcar (lambda (x)
16399 (cond ((stringp x) x)
16400 ((numberp x) (number-to-string x))
16401 ((symbolp x) (symbol-name x))
16404 (when (member ":ETC" vals)
16405 (setq vals (remove ":ETC" vals))
16406 (org-add-props (car vals) '(org-unrestricted t)))
16407 (if table (mapcar 'list vals) vals)))
16409 (defun org-property-previous-allowed-value (&optional _previous)
16410 "Switch to the next allowed value for this property."
16412 (org-property-next-allowed-value t))
16414 (defun org-property-next-allowed-value (&optional previous)
16415 "Switch to the next allowed value for this property."
16417 (unless (org-at-property-p)
16418 (user-error "Not at a property"))
16419 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16420 (key (match-string 2))
16421 (value (match-string 3))
16422 (allowed (or (org-property-get-allowed-values (point) key)
16423 (and (member value '("[ ]" "[-]" "[X]"))
16425 (heading (save-match-data (nth 4 (org-heading-components))))
16428 (user-error "Allowed values for this property have not been defined"))
16429 (when previous (setq allowed (reverse allowed)))
16430 (when (member value allowed)
16431 (setq nval (car (cdr (member value allowed)))))
16432 (setq nval (or nval (car allowed)))
16433 (when (equal nval value)
16434 (user-error "Only one allowed value for this property"))
16435 (org-at-property-p)
16436 (replace-match (concat " :" key ": " nval) t t)
16438 (beginning-of-line 1)
16439 (skip-chars-forward " \t")
16440 (when (equal prop org-effort-property)
16441 (org-refresh-property
16442 '((effort . identity)
16443 (effort-minutes . org-duration-to-minutes))
16445 (when (string= org-clock-current-task heading)
16446 (setq org-clock-effort nval)
16447 (org-clock-update-mode-line)))
16448 (run-hook-with-args 'org-property-changed-functions key nval)))
16450 (defun org-find-olp (path &optional this-buffer)
16451 "Return a marker pointing to the entry at outline path OLP.
16452 If anything goes wrong, throw an error.
16453 You can wrap this call to catch the error like this:
16455 (condition-case msg
16456 (org-mobile-locate-entry (match-string 4))
16457 (error (nth 1 msg)))
16459 The return value will then be either a string with the error message,
16460 or a marker if everything is OK.
16462 If THIS-BUFFER is set, the outline path does not contain a file,
16464 (let* ((file (if this-buffer buffer-file-name (pop path)))
16465 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16470 (unless buffer (error "File not found :%s" file))
16471 (with-current-buffer buffer
16472 (unless (derived-mode-p 'org-mode)
16473 (error "Buffer %s needs to be in Org mode" buffer))
16474 (org-with-wide-buffer
16475 (goto-char (point-min))
16476 (dolist (heading path)
16477 (let ((re (format org-complex-heading-regexp-format
16478 (regexp-quote heading)))
16480 (while (re-search-forward re end t)
16481 (setq level (- (match-end 1) (match-beginning 1)))
16482 (when (and (>= level lmin) (<= level lmax))
16483 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16485 (error "Heading not found on level %d: %s" lmax heading))
16487 (error "Heading not unique on level %d: %s" lmax heading))
16489 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16490 (setq end (save-excursion (org-end-of-subtree t t)))))
16491 (when (org-at-heading-p)
16492 (point-marker))))))
16494 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16495 "Find node HEADING in BUFFER.
16496 Return a marker to the heading if it was found, or nil if not.
16497 If POS-ONLY is set, return just the position instead of a marker.
16499 The heading text must match exact, but it may have a TODO keyword,
16500 a priority cookie and tags in the standard locations."
16501 (with-current-buffer (or buffer (current-buffer))
16502 (org-with-wide-buffer
16503 (goto-char (point-min))
16504 (let (case-fold-search)
16505 (when (re-search-forward
16506 (format org-complex-heading-regexp-format
16507 (regexp-quote heading)) nil t)
16509 (match-beginning 0)
16510 (move-marker (make-marker) (match-beginning 0))))))))
16512 (defun org-find-exact-heading-in-directory (heading &optional dir)
16513 "Find Org node headline HEADING in all .org files in directory DIR.
16514 When the target headline is found, return a marker to this location."
16515 (let ((files (directory-files (or dir default-directory)
16516 t "\\`[^.#].*\\.org\\'"))
16519 (dolist (file files)
16520 (message "trying %s" file)
16521 (setq visiting (org-find-base-buffer-visiting file))
16522 (setq buffer (or visiting (find-file-noselect file)))
16523 (setq m (org-find-exact-headline-in-buffer
16525 (when (and (not m) (not visiting)) (kill-buffer buffer))
16526 (and m (throw 'found m))))))
16528 (defun org-find-entry-with-id (ident)
16529 "Locate the entry that contains the ID property with exact value IDENT.
16530 IDENT can be a string, a symbol or a number, this function will search for
16531 the string representation of it.
16532 Return the position where this entry starts, or nil if there is no such entry."
16533 (interactive "sID: ")
16535 ((stringp ident) ident)
16536 ((symbolp ident) (symbol-name ident))
16537 ((numberp ident) (number-to-string ident))
16538 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16539 (org-with-wide-buffer (org-find-property "ID" id))))
16543 (defvar org-last-changed-timestamp nil)
16544 (defvar org-last-inserted-timestamp nil
16545 "The last time stamp inserted with `org-insert-time-stamp'.")
16547 (defun org-time-stamp (arg &optional inactive)
16548 "Prompt for a date/time and insert a time stamp.
16550 If the user specifies a time like HH:MM or if this command is
16551 called with at least one prefix argument, the time stamp contains
16552 the date and the time. Otherwise, only the date is included.
16554 All parts of a date not specified by the user are filled in from
16555 the timestamp at point, if any, or the current date/time
16558 If there is already a timestamp at the cursor, it is replaced.
16560 With two universal prefix arguments, insert an active timestamp
16561 with the current time without prompting the user.
16563 When called from lisp, the timestamp is inactive if INACTIVE is
16567 ((org-at-date-range-p t)
16568 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16569 ((org-at-timestamp-p 'lax) (match-string 0))))
16570 ;; Default time is either the timestamp at point or today.
16571 ;; When entering a range, only the range start is considered.
16572 (default-time (if (not ts) (current-time)
16573 (apply #'encode-time (org-parse-time-string ts))))
16574 (default-input (and ts (org-get-compact-tod ts)))
16576 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16577 (match-string 0 ts)))
16579 org-end-time-was-given
16581 (and (if (equal arg '(16)) (current-time)
16582 ;; Preserve `this-command' and `last-command'.
16583 (let ((this-command this-command)
16584 (last-command last-command))
16586 arg 'totime nil nil default-time default-input
16590 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16591 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16593 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16595 ;; Make sure we're on a timestamp. When in the middle of a date
16596 ;; range, move arbitrarily to range end.
16597 (unless (org-at-timestamp-p 'lax)
16598 (skip-chars-forward "-")
16599 (org-at-timestamp-p 'lax))
16601 (setq org-last-changed-timestamp
16602 (org-insert-time-stamp
16603 time (or org-time-was-given arg)
16604 inactive nil nil (list org-end-time-was-given)))
16607 (insert " " repeater)
16608 (setq org-last-changed-timestamp
16609 (concat (substring org-last-inserted-timestamp 0 -1)
16610 " " repeater ">")))
16611 (message "Timestamp updated"))
16612 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16613 (t (org-insert-time-stamp
16614 time (or org-time-was-given arg) inactive nil nil
16615 (list org-end-time-was-given))))))
16617 ;; FIXME: can we use this for something else, like computing time differences?
16618 (defun org-get-compact-tod (s)
16619 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16620 (let* ((t1 (match-string 1 s))
16621 (h1 (string-to-number (match-string 2 s)))
16622 (m1 (string-to-number (match-string 3 s)))
16623 (t2 (and (match-end 4) (match-string 5 s)))
16624 (h2 (and t2 (string-to-number (match-string 6 s))))
16625 (m2 (and t2 (string-to-number (match-string 7 s))))
16629 (setq dh (- h2 h1) dm (- m2 m1))
16630 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16631 (concat t1 "+" (number-to-string dh)
16632 (and (/= 0 dm) (format ":%02d" dm)))))))
16634 (defun org-time-stamp-inactive (&optional arg)
16635 "Insert an inactive time stamp.
16636 An inactive time stamp is enclosed in square brackets instead of angle
16637 brackets. It is inactive in the sense that it does not trigger agenda entries,
16638 does not link to the calendar and cannot be changed with the S-cursor keys.
16639 So these are more for recording a certain time/date."
16641 (org-time-stamp arg 'inactive))
16643 (defvar org-date-ovl (make-overlay 1 1))
16644 (overlay-put org-date-ovl 'face 'org-date-selected)
16645 (delete-overlay org-date-ovl)
16647 (defvar org-ans1) ; dynamically scoped parameter
16648 (defvar org-ans2) ; dynamically scoped parameter
16650 (defvar org-plain-time-of-day-regexp) ; defined below
16652 (defvar org-overriding-default-time nil) ; dynamically scoped
16653 (defvar org-read-date-overlay nil)
16654 (defvar org-dcst nil) ; dynamically scoped
16655 (defvar org-read-date-history nil)
16656 (defvar org-read-date-final-answer nil)
16657 (defvar org-read-date-analyze-futurep nil)
16658 (defvar org-read-date-analyze-forced-year nil)
16659 (defvar org-read-date-inactive)
16661 (defvar org-read-date-minibuffer-local-map
16662 (let* ((map (make-sparse-keymap)))
16663 (set-keymap-parent map minibuffer-local-map)
16664 (org-defkey map (kbd ".")
16665 (lambda () (interactive)
16666 ;; Are we at the beginning of the prompt?
16667 (if (looking-back "^[^:]+: "
16668 (let ((inhibit-field-text-motion t))
16669 (line-beginning-position)))
16670 (org-eval-in-calendar '(calendar-goto-today))
16672 (org-defkey map (kbd "C-.")
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-goto-today))))
16675 (org-defkey map [(meta shift left)]
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(calendar-backward-month 1))))
16678 (org-defkey map [(meta shift right)]
16679 (lambda () (interactive)
16680 (org-eval-in-calendar '(calendar-forward-month 1))))
16681 (org-defkey map [(meta shift up)]
16682 (lambda () (interactive)
16683 (org-eval-in-calendar '(calendar-backward-year 1))))
16684 (org-defkey map [(meta shift down)]
16685 (lambda () (interactive)
16686 (org-eval-in-calendar '(calendar-forward-year 1))))
16687 (org-defkey map [?\e (shift left)]
16688 (lambda () (interactive)
16689 (org-eval-in-calendar '(calendar-backward-month 1))))
16690 (org-defkey map [?\e (shift right)]
16691 (lambda () (interactive)
16692 (org-eval-in-calendar '(calendar-forward-month 1))))
16693 (org-defkey map [?\e (shift up)]
16694 (lambda () (interactive)
16695 (org-eval-in-calendar '(calendar-backward-year 1))))
16696 (org-defkey map [?\e (shift down)]
16697 (lambda () (interactive)
16698 (org-eval-in-calendar '(calendar-forward-year 1))))
16699 (org-defkey map [(shift up)]
16700 (lambda () (interactive)
16701 (org-eval-in-calendar '(calendar-backward-week 1))))
16702 (org-defkey map [(shift down)]
16703 (lambda () (interactive)
16704 (org-eval-in-calendar '(calendar-forward-week 1))))
16705 (org-defkey map [(shift left)]
16706 (lambda () (interactive)
16707 (org-eval-in-calendar '(calendar-backward-day 1))))
16708 (org-defkey map [(shift right)]
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(calendar-forward-day 1))))
16711 (org-defkey map "!"
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(diary-view-entries))
16715 (org-defkey map ">"
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-scroll-left 1))))
16718 (org-defkey map "<"
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-scroll-right 1))))
16721 (org-defkey map "\C-v"
16722 (lambda () (interactive)
16723 (org-eval-in-calendar
16724 '(calendar-scroll-left-three-months 1))))
16725 (org-defkey map "\M-v"
16726 (lambda () (interactive)
16727 (org-eval-in-calendar
16728 '(calendar-scroll-right-three-months 1))))
16730 "Keymap for minibuffer commands when using `org-read-date'.")
16733 (defvar org-defdecode)
16734 (defvar org-with-time)
16736 (defvar calendar-setup) ; Dynamically scoped.
16737 (defun org-read-date (&optional with-time to-time from-string prompt
16738 default-time default-input inactive)
16739 "Read a date, possibly a time, and make things smooth for the user.
16740 The prompt will suggest to enter an ISO date, but you can also enter anything
16741 which will at least partially be understood by `parse-time-string'.
16742 Unrecognized parts of the date will default to the current day, month, year,
16743 hour and minute. If this command is called to replace a timestamp at point,
16744 or to enter the second timestamp of a range, the default time is taken
16745 from the existing stamp. Furthermore, the command prefers the future,
16746 so if you are giving a date where the year is not given, and the day-month
16747 combination is already past in the current year, it will assume you
16748 mean next year. For details, see the manual. A few examples:
16750 3-2-5 --> 2003-02-05
16751 feb 15 --> currentyear-02-15
16752 2/15 --> currentyear-02-15
16753 sep 12 9 --> 2009-09-12
16754 12:45 --> today 12:45
16755 22 sept 0:34 --> currentyear-09-22 0:34
16756 12 --> currentyear-currentmonth-12
16757 Fri --> nearest Friday after today
16758 -Tue --> last Tuesday
16761 Furthermore you can specify a relative date by giving, as the *first* thing
16762 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16763 change in days weeks, months, years.
16764 With a single plus or minus, the date is relative to today. With a double
16765 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16766 +4d --> four days from today
16767 +4 --> same as above
16768 +2w --> two weeks from today
16769 ++5 --> five days from default date
16771 The function understands only English month and weekday abbreviations.
16773 While prompting, a calendar is popped up - you can also select the
16774 date with the mouse (button 1). The calendar shows a period of three
16775 months. To scroll it to other months, use the keys `>' and `<'.
16776 If you don't like the calendar, turn it off with
16777 (setq org-read-date-popup-calendar nil)
16779 With optional argument TO-TIME, the date will immediately be converted
16780 to an internal time.
16781 With an optional argument WITH-TIME, the prompt will suggest to
16782 also insert a time. Note that when WITH-TIME is not set, you can
16783 still enter a time, and this function will inform the calling routine
16784 about this change. The calling routine may then choose to change the
16785 format used to insert the time stamp into the buffer to include the time.
16786 With optional argument FROM-STRING, read from this string instead from
16787 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16788 the time/date that is used for everything that is not specified by the
16790 (require 'parse-time)
16791 (let* ((org-with-time with-time)
16792 (org-time-stamp-rounding-minutes
16793 (if (equal org-with-time '(16))
16795 org-time-stamp-rounding-minutes))
16796 (org-dcst org-display-custom-times)
16797 (ct (org-current-time))
16798 (org-def (or org-overriding-default-time default-time ct))
16799 (org-defdecode (decode-time org-def))
16800 (cur-frame (selected-frame))
16801 (mouse-autoselect-window nil) ; Don't let the mouse jump
16803 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16804 (calendar-move-hook nil)
16805 (calendar-view-diary-initially-flag nil)
16806 (calendar-view-holidays-initially-flag nil)
16807 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16808 ;; Rationalize `org-def' and `org-defdecode', if required.
16809 (when (< (nth 2 org-defdecode) org-extend-today-until)
16810 (setf (nth 2 org-defdecode) -1)
16811 (setf (nth 1 org-defdecode) 59)
16812 (setq org-def (apply #'encode-time org-defdecode))
16813 (setq org-defdecode (decode-time org-def)))
16814 (let* ((timestr (format-time-string
16815 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16817 (prompt (concat (if prompt (concat prompt " ") "")
16818 (format "Date+time [%s]: " timestr))))
16820 (from-string (setq ans from-string))
16821 (org-read-date-popup-calendar
16823 (save-window-excursion
16825 (when (eq calendar-setup 'calendar-only)
16827 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16828 (select-frame cal-frame))
16829 (org-eval-in-calendar '(setq cursor-type nil) t)
16832 (calendar-forward-day (- (time-to-days org-def)
16833 (calendar-absolute-from-gregorian
16834 (calendar-current-date))))
16835 (org-eval-in-calendar nil t)
16836 (let* ((old-map (current-local-map))
16837 (map (copy-keymap calendar-mode-map))
16838 (minibuffer-local-map
16839 (copy-keymap org-read-date-minibuffer-local-map)))
16840 (org-defkey map (kbd "RET") 'org-calendar-select)
16841 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16842 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16845 (use-local-map map)
16846 (setq org-read-date-inactive inactive)
16847 (add-hook 'post-command-hook 'org-read-date-display)
16849 (read-string prompt
16851 'org-read-date-history
16853 ;; org-ans0: from prompt
16854 ;; org-ans1: from mouse click
16855 ;; org-ans2: from calendar motion
16857 (concat org-ans0 " " (or org-ans1 org-ans2))))
16858 (remove-hook 'post-command-hook 'org-read-date-display)
16859 (use-local-map old-map)
16860 (when org-read-date-overlay
16861 (delete-overlay org-read-date-overlay)
16862 (setq org-read-date-overlay nil)))))
16863 (bury-buffer "*Calendar*")
16865 (delete-frame cal-frame)
16866 (select-frame-set-input-focus cur-frame))))))
16868 (t ; Naked prompt only
16870 (setq ans (read-string prompt default-input
16871 'org-read-date-history timestr))
16872 (when org-read-date-overlay
16873 (delete-overlay org-read-date-overlay)
16874 (setq org-read-date-overlay nil))))))
16876 (setq final (org-read-date-analyze ans org-def org-defdecode))
16878 (when org-read-date-analyze-forced-year
16879 (message "Year was forced into %s"
16880 (if org-read-date-force-compatible-dates
16881 "compatible range (1970-2037)"
16882 "range representable on this machine"))
16885 ;; One round trip to get rid of 34th of August and stuff like that....
16886 (setq final (decode-time (apply 'encode-time final)))
16888 (setq org-read-date-final-answer ans)
16891 (apply 'encode-time final)
16892 (if (and (boundp 'org-time-was-given) org-time-was-given)
16893 (format "%04d-%02d-%02d %02d:%02d"
16894 (nth 5 final) (nth 4 final) (nth 3 final)
16895 (nth 2 final) (nth 1 final))
16896 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16898 (defun org-read-date-display ()
16899 "Display the current date prompt interpretation in the minibuffer."
16900 (when org-read-date-display-live
16901 (when org-read-date-overlay
16902 (delete-overlay org-read-date-overlay))
16903 (when (minibufferp (current-buffer))
16906 (while (not (equal (buffer-substring
16907 (max (point-min) (- (point) 4)) (point))
16910 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16911 " " (or org-ans1 org-ans2)))
16912 (org-end-time-was-given nil)
16913 (f (org-read-date-analyze ans org-def org-defdecode))
16915 org-time-stamp-custom-formats
16916 org-time-stamp-formats))
16917 (fmt (if (or org-with-time
16918 (and (boundp 'org-time-was-given) org-time-was-given))
16921 (txt (format-time-string fmt (apply 'encode-time f)))
16922 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16923 (txt (concat "=> " txt)))
16924 (when (and org-end-time-was-given
16925 (string-match org-plain-time-of-day-regexp txt))
16926 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16927 org-end-time-was-given
16928 (substring txt (match-end 0)))))
16929 (when org-read-date-analyze-futurep
16930 (setq txt (concat txt " (=>F)")))
16931 (setq org-read-date-overlay
16932 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16933 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16935 (defun org-read-date-analyze (ans def defdecode)
16936 "Analyze the combined answer of the date prompt."
16937 ;; FIXME: cleanup and comment
16938 ;; Pass `current-time' result to `decode-time' (instead of calling
16939 ;; without arguments) so that only `current-time' has to be
16940 ;; overridden in tests.
16941 (let ((org-def def)
16942 (org-defdecode defdecode)
16943 (nowdecode (decode-time (current-time)))
16944 delta deltan deltaw deltadef year month day
16945 hour minute second wday pm h2 m2 tl wday1
16946 iso-year iso-weekday iso-week iso-date futurep kill-year)
16947 (setq org-read-date-analyze-futurep nil
16948 org-read-date-analyze-forced-year nil)
16949 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16952 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16953 (setq ans (replace-match "" t t ans)
16955 deltaw (nth 1 delta)
16956 deltadef (nth 2 delta)))
16958 ;; Check if there is an iso week date in there. If yes, store the
16959 ;; info and postpone interpreting it until the rest of the parsing
16961 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16962 (setq iso-year (when (match-end 1)
16963 (org-small-year-to-year
16964 (string-to-number (match-string 1 ans))))
16965 iso-weekday (when (match-end 3)
16966 (string-to-number (match-string 3 ans)))
16967 iso-week (string-to-number (match-string 2 ans)))
16968 (setq ans (replace-match "" t t ans)))
16970 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16971 (when (string-match
16972 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16973 (setq year (if (match-end 2)
16974 (string-to-number (match-string 2 ans))
16975 (progn (setq kill-year t)
16976 (string-to-number (format-time-string "%Y"))))
16977 month (string-to-number (match-string 3 ans))
16978 day (string-to-number (match-string 4 ans)))
16979 (setq year (org-small-year-to-year year))
16980 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16983 ;; Help matching dotted european dates
16984 (when (string-match
16985 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16986 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16988 (string-to-number (format-time-string "%Y")))
16989 day (string-to-number (match-string 1 ans))
16990 month (string-to-number (match-string 2 ans))
16991 ans (replace-match (format "%04d-%02d-%02d" year month day)
16994 ;; Help matching american dates, like 5/30 or 5/30/7
16995 (when (string-match
16996 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16997 (setq year (if (match-end 4)
16998 (string-to-number (match-string 4 ans))
16999 (progn (setq kill-year t)
17000 (string-to-number (format-time-string "%Y"))))
17001 month (string-to-number (match-string 1 ans))
17002 day (string-to-number (match-string 2 ans)))
17003 (setq year (org-small-year-to-year year))
17004 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17006 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17007 ;; If there is a time with am/pm, and *no* time without it, we convert
17008 ;; so that matching will be successful.
17009 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17010 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17011 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17012 (setq hour (string-to-number (match-string 1 ans))
17013 minute (if (match-end 3)
17014 (string-to-number (match-string 3 ans))
17017 (string-to-char (downcase (match-string 4 ans)))))
17018 (if (and (= hour 12) (not pm))
17020 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17021 (setq ans (replace-match (format "%02d:%02d" hour minute)
17024 ;; Check if a time range is given as a duration
17025 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17026 (setq hour (string-to-number (match-string 1 ans))
17027 h2 (+ hour (string-to-number (match-string 3 ans)))
17028 minute (string-to-number (match-string 2 ans))
17029 m2 (+ minute (if (match-end 5) (string-to-number
17030 (match-string 5 ans))0)))
17031 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17032 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17035 ;; Check if there is a time range
17036 (when (boundp 'org-end-time-was-given)
17037 (setq org-time-was-given nil)
17038 (when (and (string-match org-plain-time-of-day-regexp ans)
17040 (setq org-end-time-was-given (match-string 8 ans))
17041 (setq ans (concat (substring ans 0 (match-beginning 7))
17042 (substring ans (match-end 7))))))
17044 (setq tl (parse-time-string ans)
17045 day (or (nth 3 tl) (nth 3 org-defdecode))
17048 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17049 ;; Day was specified. Make sure DAY+MONTH
17050 ;; combination happens in the future.
17053 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17054 (nth 4 nowdecode)))
17055 (t (nth 4 org-defdecode)))
17057 (cond ((and (not kill-year) (nth 5 tl)))
17058 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17059 ;; Month was guessed in the future and is at least
17060 ;; equal to NOWDECODE's. Fix year accordingly.
17062 (if (or (> month (nth 4 nowdecode))
17063 (>= day (nth 3 nowdecode)))
17065 (1+ (nth 5 nowdecode))))
17066 ;; Month was specified. Make sure MONTH+YEAR
17067 ;; combination happens in the future.
17070 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17071 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17072 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17073 (t (nth 5 nowdecode))))
17074 (t (nth 5 org-defdecode)))
17075 hour (or (nth 2 tl) (nth 2 org-defdecode))
17076 minute (or (nth 1 tl) (nth 1 org-defdecode))
17077 second (or (nth 0 tl) 0)
17080 (when (and (eq org-read-date-prefer-future 'time)
17081 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17082 (equal day (nth 3 nowdecode))
17083 (equal month (nth 4 nowdecode))
17084 (equal year (nth 5 nowdecode))
17086 (or (< (nth 2 tl) (nth 2 nowdecode))
17087 (and (= (nth 2 tl) (nth 2 nowdecode))
17089 (< (nth 1 tl) (nth 1 nowdecode)))))
17093 ;; Special date definitions below
17096 ;; There was an iso week
17099 (setq year (or iso-year year)
17100 day (or iso-weekday wday 1)
17101 wday nil ; to make sure that the trigger below does not match
17102 iso-date (calendar-gregorian-from-absolute
17103 (calendar-iso-to-absolute
17104 (list iso-week day year))))
17105 ; FIXME: Should we also push ISO weeks into the future?
17106 ; (when (and org-read-date-prefer-future
17108 ; (< (calendar-absolute-from-gregorian iso-date)
17109 ; (time-to-days (current-time))))
17110 ; (setq year (1+ year)
17111 ; iso-date (calendar-gregorian-from-absolute
17112 ; (calendar-iso-to-absolute
17113 ; (list iso-week day year)))))
17114 (setq month (car iso-date)
17115 year (nth 2 iso-date)
17116 day (nth 1 iso-date)))
17120 ;; Pass `current-time' result to `decode-time' (instead of
17121 ;; calling without arguments) so that only `current-time' has
17122 ;; to be overridden in tests.
17123 (let ((now (decode-time (current-time))))
17124 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17125 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17126 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17127 ((equal deltaw "m") (setq month (+ month deltan)))
17128 ((equal deltaw "y") (setq year (+ year deltan)))))
17129 ((and wday (not (nth 3 tl)))
17130 ;; Weekday was given, but no day, so pick that day in the week
17131 ;; on or after the derived date.
17132 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17133 (unless (equal wday wday1)
17134 (setq day (+ day (% (- wday wday1 -7) 7))))))
17135 (when (and (boundp 'org-time-was-given)
17137 (setq org-time-was-given t))
17138 (when (< year 100) (setq year (+ 2000 year)))
17139 ;; Check of the date is representable
17140 (if org-read-date-force-compatible-dates
17142 (when (< year 1970)
17143 (setq year 1970 org-read-date-analyze-forced-year t))
17144 (when (> year 2037)
17145 (setq year 2037 org-read-date-analyze-forced-year t)))
17146 (condition-case nil
17147 (ignore (encode-time second minute hour day month year))
17149 (setq year (nth 5 org-defdecode))
17150 (setq org-read-date-analyze-forced-year t))))
17151 (setq org-read-date-analyze-futurep futurep)
17152 (list second minute hour day month year)))
17154 (defvar parse-time-weekdays)
17155 (defun org-read-date-get-relative (s today default)
17156 "Check string S for special relative date string.
17157 TODAY and DEFAULT are internal times, for today and for a default.
17158 Return shift list (N what def-flag)
17159 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17160 N is the number of WHATs to shift.
17161 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17162 the DEFAULT date rather than TODAY."
17163 (require 'parse-time)
17167 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17169 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17170 "\\([ \t]\\|$\\)") s)
17171 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17172 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17173 (string-to-char (substring (match-string 1 s) -1))
17175 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17176 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17177 (what (if (match-end 3) (match-string 3 s) "d"))
17178 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17179 (date (if rel default today))
17180 (wday (nth 6 (decode-time date)))
17184 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17185 (when (= delta 0) (setq delta 7))
17187 (setq delta (- delta 7))
17188 (when (= delta 0) (setq delta -7)))
17189 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17190 (list delta "d" rel))
17191 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17193 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17194 "Turn a user-specified date into the internal representation.
17195 The internal representation needed by the calendar is (month day year).
17196 This is a wrapper to handle the brain-dead convention in calendar that
17197 user function argument order change dependent on argument order."
17198 (pcase calendar-date-style
17199 (`american (list arg1 arg2 arg3))
17200 (`european (list arg2 arg1 arg3))
17201 (`iso (list arg2 arg3 arg1))))
17203 (defun org-eval-in-calendar (form &optional keepdate)
17204 "Eval FORM in the calendar window and return to current window.
17205 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17206 (let ((sf (selected-frame))
17207 (sw (selected-window)))
17208 (select-window (get-buffer-window "*Calendar*" t))
17210 (when (and (not keepdate) (calendar-cursor-to-date))
17211 (let* ((date (calendar-cursor-to-date))
17212 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17213 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17214 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17216 (select-frame-set-input-focus sf)))
17218 (defun org-calendar-select ()
17219 "Return to `org-read-date' with the date currently selected.
17220 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17222 (when (calendar-cursor-to-date)
17223 (let* ((date (calendar-cursor-to-date))
17224 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17225 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17226 (when (active-minibuffer-window) (exit-minibuffer))))
17228 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17229 "Insert a date stamp for the date given by the internal TIME.
17230 See `format-time-string' for the format of TIME.
17231 WITH-HM means use the stamp format that includes the time of the day.
17232 INACTIVE means use square brackets instead of angular ones, so that the
17233 stamp will not contribute to the agenda.
17234 PRE and POST are optional strings to be inserted before and after the
17236 The command returns the inserted time stamp."
17237 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17239 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17240 (insert-before-markers (or pre ""))
17241 (when (listp extra)
17242 (setq extra (car extra))
17243 (if (and (stringp extra)
17244 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17245 (setq extra (format "-%02d:%02d"
17246 (string-to-number (match-string 1 extra))
17247 (string-to-number (match-string 2 extra))))
17250 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17251 (insert-before-markers (setq stamp (format-time-string fmt time)))
17252 (insert-before-markers (or post ""))
17253 (setq org-last-inserted-timestamp stamp)))
17255 (defun org-toggle-time-stamp-overlays ()
17256 "Toggle the use of custom time stamp formats."
17258 (setq org-display-custom-times (not org-display-custom-times))
17259 (unless org-display-custom-times
17260 (let ((p (point-min)) (bmp (buffer-modified-p)))
17261 (while (setq p (next-single-property-change p 'display))
17262 (when (and (get-text-property p 'display)
17263 (eq (get-text-property p 'face) 'org-date))
17264 (remove-text-properties
17265 p (setq p (next-single-property-change p 'display))
17267 (set-buffer-modified-p bmp)))
17268 (org-restart-font-lock)
17269 (setq org-table-may-need-update t)
17270 (if org-display-custom-times
17271 (message "Time stamps are overlaid with custom format")
17272 (message "Time stamp overlays removed")))
17274 (defun org-display-custom-time (beg end)
17275 "Overlay modified time stamp format over timestamp between BEG and END."
17276 (let* ((ts (buffer-substring beg end))
17277 t1 with-hm tf time str (off 0))
17279 (setq t1 (org-parse-time-string ts t))
17280 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17281 (setq off (- (match-end 0) (match-beginning 0)))))
17282 (setq end (- end off))
17283 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17284 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17285 time (org-fix-decoded-time t1)
17287 (format-time-string
17288 (substring tf 1 -1) (apply 'encode-time time))
17289 nil 'mouse-face 'highlight))
17290 (put-text-property beg end 'display str)))
17292 (defun org-fix-decoded-time (time)
17293 "Set 0 instead of nil for the first 6 elements of time.
17294 Don't touch the rest."
17296 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17298 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17299 "Difference between TIMESTAMP-STRING and now in days.
17300 If SECONDS is non-nil, return the difference in seconds."
17301 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17302 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17303 (funcall fdiff (current-time)))))
17305 (defun org-deadline-close-p (timestamp-string &optional ndays)
17306 "Is the time in TIMESTAMP-STRING close to the current date?"
17307 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17308 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17309 (not (org-entry-is-done-p))))
17311 (defun org-get-wdays (ts &optional delay zero-delay)
17312 "Get the deadline lead time appropriate for timestring TS.
17313 When DELAY is non-nil, get the delay time for scheduled items
17314 instead of the deadline lead time. When ZERO-DELAY is non-nil
17315 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17316 don't try to find the delay cookie in the scheduled timestamp."
17317 (let ((tv (if delay org-scheduled-delay-days
17318 org-deadline-warning-days)))
17320 ((or (and delay (< tv 0))
17321 (and delay zero-delay (<= tv 0))
17322 (and (not delay) (<= tv 0)))
17323 ;; Enforce this value no matter what
17325 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17326 ;; lead time is specified.
17327 (floor (* (string-to-number (match-string 1 ts))
17328 (cdr (assoc (match-string 2 ts)
17329 '(("d" . 1) ("w" . 7)
17330 ("m" . 30.4) ("y" . 365.25)
17331 ("h" . 0.041667)))))))
17332 ;; go for the default.
17335 (defun org-calendar-select-mouse (ev)
17336 "Return to `org-read-date' with the date currently selected.
17337 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17339 (mouse-set-point ev)
17340 (when (calendar-cursor-to-date)
17341 (let* ((date (calendar-cursor-to-date))
17342 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17343 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17344 (when (active-minibuffer-window) (exit-minibuffer))))
17346 (defun org-check-deadlines (ndays)
17347 "Check if there are any deadlines due or past due.
17348 A deadline is considered due if it happens within `org-deadline-warning-days'
17349 days from today's date. If the deadline appears in an entry marked DONE,
17350 it is not shown. A numeric prefix argument NDAYS can be used to test that
17351 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17354 (let* ((org-warn-days
17356 ((equal ndays '(4)) 100000)
17357 (ndays (prefix-numeric-value ndays))
17358 (t (abs org-deadline-warning-days))))
17359 (case-fold-search nil)
17360 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17362 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17363 (message "%d deadlines past-due or due within %d days"
17364 (org-occur regexp nil callback)
17367 (defsubst org-re-timestamp (type)
17368 "Return a regexp for timestamp TYPE.
17369 Allowed values for TYPE are:
17371 all: all timestamps
17372 active: only active timestamps (<...>)
17373 inactive: only inactive timestamps ([...])
17374 scheduled: only scheduled timestamps
17375 deadline: only deadline timestamps
17376 closed: only closed time-stamps
17378 When TYPE is nil, fall back on returning a regexp that matches
17379 both scheduled and deadline timestamps."
17381 (all org-ts-regexp-both)
17382 (active org-ts-regexp)
17383 (inactive org-ts-regexp-inactive)
17384 (scheduled org-scheduled-time-regexp)
17385 (deadline org-deadline-time-regexp)
17386 (closed org-closed-time-regexp)
17389 (regexp-opt (list org-deadline-string org-scheduled-string))
17390 " *<\\([^>]+\\)>"))))
17392 (defun org-check-before-date (d)
17393 "Check if there are deadlines or scheduled entries before date D."
17394 (interactive (list (org-read-date)))
17395 (let* ((case-fold-search nil)
17396 (regexp (org-re-timestamp org-ts-type))
17397 (ts-type org-ts-type)
17400 (let ((match (match-string 1)))
17401 (and (if (memq ts-type '(active inactive all))
17402 (eq (org-element-type (save-excursion
17404 (org-element-context)))
17406 (org-at-planning-p))
17408 (org-time-string-to-time match)
17409 (org-time-string-to-time d)))))))
17410 (message "%d entries before %s"
17411 (org-occur regexp nil callback)
17414 (defun org-check-after-date (d)
17415 "Check if there are deadlines or scheduled entries after date D."
17416 (interactive (list (org-read-date)))
17417 (let* ((case-fold-search nil)
17418 (regexp (org-re-timestamp org-ts-type))
17419 (ts-type org-ts-type)
17422 (let ((match (match-string 1)))
17423 (and (if (memq ts-type '(active inactive all))
17424 (eq (org-element-type (save-excursion
17426 (org-element-context)))
17428 (org-at-planning-p))
17430 (org-time-string-to-time match)
17431 (org-time-string-to-time d))))))))
17432 (message "%d entries after %s"
17433 (org-occur regexp nil callback)
17436 (defun org-check-dates-range (start-date end-date)
17437 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17438 (interactive (list (org-read-date nil nil nil "Range starts")
17439 (org-read-date nil nil nil "Range end")))
17440 (let ((case-fold-search nil)
17441 (regexp (org-re-timestamp org-ts-type))
17443 (let ((type org-ts-type))
17445 (let ((match (match-string 1)))
17447 (if (memq type '(active inactive all))
17448 (eq (org-element-type (save-excursion
17450 (org-element-context)))
17452 (org-at-planning-p))
17454 (org-time-string-to-time match)
17455 (org-time-string-to-time start-date)))
17457 (org-time-string-to-time match)
17458 (org-time-string-to-time end-date))))))))
17459 (message "%d entries between %s and %s"
17460 (org-occur regexp nil callback) start-date end-date)))
17462 (defun org-evaluate-time-range (&optional to-buffer)
17463 "Evaluate a time range by computing the difference between start and end.
17464 Normally the result is just printed in the echo area, but with prefix arg
17465 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17466 If the time range is actually in a table, the result is inserted into the
17468 For time difference computation, a year is assumed to be exactly 365
17469 days in order to avoid rounding problems."
17472 (org-clock-update-time-maybe)
17474 (unless (org-at-date-range-p t)
17475 (goto-char (point-at-bol))
17476 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17477 (unless (org-at-date-range-p t)
17478 (user-error "Not at a time-stamp range, and none found in current line")))
17479 (let* ((ts1 (match-string 1))
17480 (ts2 (match-string 2))
17481 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17482 (match-end (match-end 0))
17483 (time1 (org-time-string-to-time ts1))
17484 (time2 (org-time-string-to-time ts2))
17485 (t1 (float-time time1))
17486 (t2 (float-time time2))
17487 (diff (abs (- t2 t1)))
17488 (negative (< (- t2 t1) 0))
17489 ;; (ys (floor (* 365 24 60 60)))
17492 (fy "%dy %dd %02d:%02d")
17494 (fd "%dd %02d:%02d")
17499 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17501 d (floor (/ diff ds)) diff (mod diff ds)
17502 h (floor (/ diff hs)) diff (mod diff hs)
17503 m (floor (/ diff 60)))
17504 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17506 d (floor (+ (/ diff ds) 0.5))
17508 (if (not to-buffer)
17509 (message "%s" (org-make-tdiff-string y d h m))
17510 (if (org-at-table-p)
17512 (goto-char match-end)
17514 (and (looking-at " *|") (goto-char (match-end 0))))
17515 (goto-char match-end))
17517 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17518 (replace-match ""))
17519 (when negative (insert " -"))
17520 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17521 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17522 (insert " " (format fh h m))))
17523 (when align (org-table-align))
17524 (message "Time difference inserted")))))
17526 (defun org-make-tdiff-string (y d h m)
17530 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17533 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17536 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17539 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17541 (apply 'format fmt (nreverse l))))
17543 (defun org-time-string-to-time (s)
17544 "Convert timestamp string S into internal time."
17545 (apply #'encode-time (org-parse-time-string s)))
17547 (defun org-time-string-to-seconds (s)
17548 "Convert a timestamp string S into a number of seconds."
17549 (float-time (org-time-string-to-time s)))
17551 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17553 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17554 "Convert time stamp S to an absolute day number.
17556 If DAYNR in non-nil, and there is a specifier for a cyclic time
17557 stamp, get the closest date to DAYNR. If PREFER is
17558 `past' (respectively `future') return a date past (respectively
17559 after) or equal to DAYNR.
17561 POS is the location of time stamp S, as a buffer position in
17564 Diary sexp timestamps are matched against DAYNR, when non-nil.
17565 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17568 ((string-match "\\`%%\\((.*)\\)" s)
17569 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17570 ;; only able to match individual dates. If it fails, raise an
17573 (org-diary-sexp-entry
17574 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17576 (signal 'org-diary-sexp-no-match (list s))))
17577 (daynr (org-closest-date s daynr prefer))
17579 (condition-case errdata
17580 (apply #'encode-time (org-parse-time-string s))
17581 (error (error "Bad timestamp `%s'%s\nError was: %s"
17583 (if (not (and buffer pos)) ""
17584 (format-message " at %d in buffer `%s'" pos buffer))
17585 (cdr errdata))))))))
17587 (defun org-days-to-iso-week (days)
17588 "Return the iso week number."
17590 (car (calendar-iso-from-absolute days)))
17592 (defun org-small-year-to-year (year)
17593 "Convert 2-digit years into 4-digit years.
17594 YEAR is expanded into one of the 30 next years, if possible, or
17595 into a past one. Any year larger than 99 is returned unchanged."
17596 (if (>= year 100) year
17597 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17598 (century (/ current 100))
17599 (offset (- year (% current 100))))
17600 (cond ((> offset 30) (+ (* (1- century) 100) year))
17601 ((> offset -70) (+ (* century 100) year))
17602 (t (+ (* (1+ century) 100) year))))))
17604 (defun org-time-from-absolute (d)
17605 "Return the time corresponding to date D.
17606 D may be an absolute day number, or a calendar-type list (month day year)."
17607 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17608 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17610 (defvar org-agenda-current-date)
17611 (defun org-calendar-holiday ()
17612 "List of holidays, for Diary display in Org mode."
17613 (require 'holidays)
17614 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17615 (and hl (mapconcat #'identity hl "; "))))
17617 (defun org-diary-sexp-entry (sexp entry d)
17618 "Process a SEXP diary ENTRY for date D."
17619 (require 'diary-lib)
17620 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17622 (let* ((sexp `(let ((entry ,entry)
17624 ,(car (read-from-string sexp))))
17625 (result (if calendar-debug-sexp (eval sexp)
17626 (condition-case nil
17630 (message "Bad sexp at line %d in %s: %s"
17632 (buffer-file-name) sexp)
17634 (cond ((stringp result) (split-string result "; "))
17635 ((and (consp result)
17636 (not (consp (cdr result)))
17637 (stringp (cdr result))) (cdr result))
17638 ((and (consp result)
17639 (stringp (car result))) result)
17642 (defun org-diary-to-ical-string (frombuf)
17643 "Get iCalendar entries from diary entries in buffer FROMBUF.
17644 This uses the icalendar.el library."
17645 (let* ((tmpdir temporary-file-directory)
17646 (tmpfile (make-temp-name
17647 (expand-file-name "orgics" tmpdir)))
17649 (with-current-buffer frombuf
17650 (icalendar-export-region (point-min) (point-max) tmpfile)
17651 (setq buf (find-buffer-visiting tmpfile))
17653 (goto-char (point-min))
17654 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17655 (setq b (match-beginning 0)))
17656 (goto-char (point-max))
17657 (when (re-search-backward "^END:VEVENT" nil t)
17658 (setq e (match-end 0)))
17659 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17661 (delete-file tmpfile)
17664 (defun org-closest-date (start current prefer)
17665 "Return closest date to CURRENT starting from START.
17667 CURRENT and START are both time stamps.
17669 When PREFER is `past', return a date that is either CURRENT or
17670 past. When PREFER is `future', return a date that is either
17673 Only time stamps with a repeater are modified. Any other time
17674 stamp stay unchanged. In any case, return value is an absolute
17676 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17677 ;; No repeater. Do not shift time stamp.
17678 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17679 (let ((value (string-to-number (match-string 1 start)))
17680 (type (match-string 2 start)))
17682 ;; Repeater with a 0-value is considered as void.
17683 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17684 (let* ((base (org-date-to-gregorian start))
17685 (target (org-date-to-gregorian current))
17686 (sday (calendar-absolute-from-gregorian base))
17687 (cday (calendar-absolute-from-gregorian target))
17689 ;; If START is already past CURRENT, just return START.
17690 (if (<= cday sday) sday
17691 ;; Compute closest date before (N1) and closest date past
17695 (let ((missing-hours
17696 (mod (+ (- (* 24 (- cday sday))
17697 (nth 2 (org-parse-time-string start)))
17698 org-extend-today-until)
17700 (setf n1 (if (= missing-hours 0) cday
17701 (- cday (1+ (/ missing-hours 24)))))
17702 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17704 (let ((value (if (equal type "w") (* 7 value) value)))
17705 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17706 (setf n2 (+ n1 value))))
17710 ;; Add N months to gregorian date D, i.e.,
17711 ;; a list (MONTH DAY YEAR). Return a valid
17713 (let ((m (+ (nth 0 d) n)))
17716 (+ (/ m 12) (nth 2 d))))))
17717 (months ; Complete months to TARGET.
17718 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17719 (- (nth 0 target) (nth 0 base))
17720 ;; If START's day is greater than
17721 ;; TARGET's, remove incomplete month.
17722 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17725 (before (funcall add-months base months)))
17726 (setf n1 (calendar-absolute-from-gregorian before))
17728 (calendar-absolute-from-gregorian
17729 (funcall add-months before value)))))
17731 (let* ((d (nth 1 base))
17734 (years ; Complete years to TARGET.
17735 (* (/ (- (nth 2 target)
17737 ;; If START's month and day are
17738 ;; greater than TARGET's, remove
17739 ;; incomplete year.
17740 (if (or (> (nth 0 target) m)
17741 (and (= (nth 0 target) m)
17742 (> (nth 1 target) d)))
17747 (before (list m d (+ y years))))
17748 (setf n1 (calendar-absolute-from-gregorian before))
17749 (setf n2 (calendar-absolute-from-gregorian
17750 (list m d (+ (nth 2 before) value)))))))
17751 ;; Handle PREFER parameter, if any.
17753 ((eq prefer 'past) (if (= cday n2) n2 n1))
17754 ((eq prefer 'future) (if (= cday n1) n1 n2))
17755 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17757 (defun org-date-to-gregorian (d)
17758 "Turn any specification of date D into a Gregorian date for the calendar."
17759 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17760 ((and (listp d) (= (length d) 3)) d)
17762 (let ((d (org-parse-time-string d)))
17763 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17764 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17766 (defun org-parse-time-string (s &optional nodefault)
17767 "Parse the standard Org time string.
17769 This should be a lot faster than the normal `parse-time-string'.
17771 If time is not given, defaults to 0:00. However, with optional
17772 NODEFAULT, hour and minute fields will be nil if not given."
17773 (cond ((string-match org-ts-regexp0 s)
17775 (when (or (match-beginning 8) (not nodefault))
17776 (string-to-number (or (match-string 8 s) "0")))
17777 (when (or (match-beginning 7) (not nodefault))
17778 (string-to-number (or (match-string 7 s) "0")))
17779 (string-to-number (match-string 4 s))
17780 (string-to-number (match-string 3 s))
17781 (string-to-number (match-string 2 s))
17783 ((string-match "^<[^>]+>$" s)
17784 ;; FIXME: `decode-time' needs to be called with ZONE as its
17785 ;; second argument. However, this requires at least Emacs
17786 ;; 25.1. We can do it when we switch to this version as our
17787 ;; minimal requirement.
17788 (decode-time (seconds-to-time (org-matcher-time s))))
17789 (t (error "Not a standard Org time string: %s" s))))
17791 (defun org-timestamp-up (&optional arg)
17792 "Increase the date item at the cursor by one.
17793 If the cursor is on the year, change the year. If it is on the month,
17794 the day or the time, change that.
17795 With prefix ARG, change by that many units."
17797 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17799 (defun org-timestamp-down (&optional arg)
17800 "Decrease the date item at the cursor by one.
17801 If the cursor is on the year, change the year. If it is on the month,
17802 the day or the time, change that.
17803 With prefix ARG, change by that many units."
17805 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17807 (defun org-timestamp-up-day (&optional arg)
17808 "Increase the date in the time stamp by one day.
17809 With prefix ARG, change that many days."
17811 (if (and (not (org-at-timestamp-p 'lax))
17812 (org-at-heading-p))
17814 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17816 (defun org-timestamp-down-day (&optional arg)
17817 "Decrease the date in the time stamp by one day.
17818 With prefix ARG, change that many days."
17820 (if (and (not (org-at-timestamp-p 'lax))
17821 (org-at-heading-p))
17823 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17825 (defun org-at-timestamp-p (&optional extended)
17826 "Non-nil if point is inside a timestamp.
17828 By default, the function only consider syntactically valid active
17829 timestamps. However, the caller may have a broader definition
17830 for timestamps. As a consequence, optional argument EXTENDED can
17831 be set to the following values
17835 Include also syntactically valid inactive timestamps.
17839 Include timestamps allowed in Agenda, i.e., those in
17840 properties drawers, planning lines and clock lines.
17844 Ignore context. The function matches any part of the
17845 document looking like a timestamp. This includes comments,
17848 For backward-compatibility with Org 9.0, every other non-nil
17849 value is equivalent to `inactive'.
17851 When at a timestamp, return the position of the point as a symbol
17852 among `bracket', `after', `year', `month', `hour', `minute',
17853 `day' or a number of character from the last know part of the
17856 When matching, the match groups are the following:
17859 group 3: day number
17861 group 5: hours, if any
17862 group 6: minutes, if any"
17863 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17866 (let ((boundaries (org-in-regexp regexp)))
17868 (cond ((null boundaries) nil)
17869 ((eq extended 'lax) t)
17871 (or (and (eq extended 'agenda)
17872 (or (org-at-planning-p)
17873 (org-at-property-p)
17874 (and (bound-and-true-p
17875 org-agenda-include-inactive-timestamps)
17876 (org-at-clock-log-p))))
17879 (when (= pos (cdr boundaries)) (forward-char -1))
17880 (org-element-type (org-element-context)))))))))))
17883 ((= pos (match-beginning 0)) 'bracket)
17884 ;; Distinguish location right before the closing bracket from
17886 ((= pos (1- (match-end 0))) 'bracket)
17887 ((= pos (match-end 0)) 'after)
17888 ((org-pos-in-match-range pos 2) 'year)
17889 ((org-pos-in-match-range pos 3) 'month)
17890 ((org-pos-in-match-range pos 7) 'hour)
17891 ((org-pos-in-match-range pos 8) 'minute)
17892 ((or (org-pos-in-match-range pos 4)
17893 (org-pos-in-match-range pos 5)) 'day)
17894 ((and (> pos (or (match-end 8) (match-end 5)))
17895 (< pos (match-end 0)))
17896 (- pos (or (match-end 8) (match-end 5))))
17899 (defun org-toggle-timestamp-type ()
17900 "Toggle the type (<active> or [inactive]) of a time stamp."
17902 (when (org-at-timestamp-p 'lax)
17903 (let ((beg (match-beginning 0)) (end (match-end 0))
17904 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17907 (while (re-search-forward "[][<>]" end t)
17908 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17910 (message "Timestamp is now %sactive"
17911 (if (equal (char-after beg) ?<) "" "in")))))
17913 (defun org-at-clock-log-p ()
17914 "Non-nil if point is on a clock log line."
17915 (and (org-match-line org-clock-line-re)
17916 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17918 (defvar org-clock-history) ; defined in org-clock.el
17919 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17920 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17921 "Change the date in the time stamp at point.
17922 The date will be changed by N times WHAT. WHAT can be `day', `month',
17923 `year', `minute', `second'. If WHAT is not given, the cursor position
17924 in the timestamp determines what will be changed.
17925 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17926 (let ((origin (point))
17927 (timestamp? (org-at-timestamp-p 'lax))
17930 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17932 ts time time0 fixnext clrgx)
17933 (unless timestamp? (user-error "Not at a timestamp"))
17934 (if (and (not what) (eq timestamp? 'bracket))
17935 (org-toggle-timestamp-type)
17936 ;; Point isn't on brackets. Remember the part of the time-stamp
17937 ;; the point was in. Indeed, size of time-stamps may change,
17938 ;; but point must be kept in the same category nonetheless.
17939 (setq origin-cat timestamp?)
17940 (when (and (not what) (not (eq timestamp? 'day))
17941 org-display-custom-times
17942 (get-text-property (point) 'display)
17943 (not (get-text-property (1- (point)) 'display)))
17944 (setq timestamp? 'day))
17945 (setq timestamp? (or what timestamp?)
17946 inactive (= (char-after (match-beginning 0)) ?\[)
17947 ts (match-string 0))
17949 (when (string-match
17950 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17952 (setq extra (match-string 1 ts))
17953 (when suppress-tmp-delay
17954 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17955 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17957 (setq time0 (org-parse-time-string ts))
17959 (eq timestamp? 'minute)
17960 (not current-prefix-arg))
17961 ;; This looks like s-up and s-down. Change by one rounding step.
17962 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17963 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17964 (setcar (cdr time0) (+ (nth 1 time0)
17965 (if (> n 0) (- rem) (- dm rem))))))
17967 (apply #'encode-time
17969 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17970 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17971 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17972 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17973 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17975 (when (and (memq timestamp? '(hour minute))
17977 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17978 (setq extra (org-modify-ts-extra
17980 (if (eq timestamp? 'hour) 2 5)
17982 (when (integerp timestamp?)
17983 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17984 (when (eq what 'calendar)
17985 (let ((cal-date (org-get-date-from-calendar)))
17986 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17987 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17988 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17989 (setcar time0 (or (car time0) 0))
17990 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17991 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17992 (setq time (apply 'encode-time time0))))
17993 ;; Insert the new time-stamp, and ensure point stays in the same
17994 ;; category as before (i.e. not after the last position in that
17996 (let ((pos (point)))
17997 ;; Stay before inserted string. `save-excursion' is of no use.
17998 (setq org-last-changed-timestamp
17999 (org-insert-time-stamp time with-hm inactive nil nil extra))
18002 (looking-at org-ts-regexp3)
18005 ;; `day' category ends before `hour' if any, or at the end
18006 ;; of the day name.
18007 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18008 (`hour (min (match-end 7) origin))
18009 (`minute (min (1- (match-end 8)) origin))
18010 ((pred integerp) (min (1- (match-end 0)) origin))
18011 ;; Point was right after the time-stamp. However, the
18012 ;; time-stamp length might have changed, so refer to
18013 ;; (match-end 0) instead.
18014 (`after (match-end 0))
18015 ;; `year' and `month' have both fixed size: point couldn't
18016 ;; have moved into another part.
18018 ;; Update clock if on a CLOCK line.
18019 (org-clock-update-time-maybe)
18020 ;; Maybe adjust the closest clock in `org-clock-history'
18021 (when org-clock-adjust-closest
18022 (if (not (and (org-at-clock-log-p)
18023 (< 1 (length (delq nil (mapcar 'marker-position
18024 org-clock-history))))))
18025 (message "No clock to adjust")
18026 (cond ((save-excursion ; fix previous clock?
18027 (re-search-backward org-ts-regexp0 nil t)
18028 (looking-back (concat org-clock-string " \\[")
18029 (line-beginning-position)))
18030 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18031 ((save-excursion ; fix next clock?
18032 (re-search-backward org-ts-regexp0 nil t)
18033 (looking-at (concat org-ts-regexp0 "\\] =>")))
18034 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18035 (save-window-excursion
18036 ;; Find closest clock to point, adjust the previous/next one in history
18037 (let* ((p (save-excursion (org-back-to-heading t)))
18038 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18040 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18041 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18043 (message "No clock to adjust")
18045 (org-goto-marker-or-bmk clfixpos)
18047 (when (re-search-forward clrgx nil t)
18048 (goto-char (match-beginning 1))
18049 (let (org-clock-adjust-closest)
18050 (org-timestamp-change n timestamp? updown))
18051 (message "Clock adjusted in %s for heading: %s"
18052 (file-name-nondirectory (buffer-file-name))
18053 (org-get-heading t t)))))))))
18054 ;; Try to recenter the calendar window, if any.
18055 (when (and org-calendar-follow-timestamp-change
18056 (get-buffer-window "*Calendar*" t)
18057 (memq timestamp? '(day month year)))
18058 (org-recenter-calendar (time-to-days time))))))
18060 (defun org-modify-ts-extra (s pos n dm)
18061 "Change the different parts of the lead-time and repeat fields in timestamp."
18062 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18064 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18066 ((or (org-pos-in-match-range pos 2)
18067 (org-pos-in-match-range pos 3))
18068 (setq m (string-to-number (match-string 3 s))
18069 h (string-to-number (match-string 2 s)))
18070 (if (org-pos-in-match-range pos 2)
18072 (setq n (* dm (with-no-warnings (signum n))))
18073 (unless (= 0 (setq rem (% m dm)))
18074 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18076 (when (< m 0) (setq m (+ m 60) h (1- h)))
18077 (when (> m 59) (setq m (- m 60) h (1+ h)))
18078 (setq h (mod h 24))
18079 (setq ng 1 new (format "-%02d:%02d" h m)))
18080 ((org-pos-in-match-range pos 6)
18081 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18082 ((org-pos-in-match-range pos 5)
18083 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18085 ((org-pos-in-match-range pos 9)
18086 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18087 ((org-pos-in-match-range pos 8)
18088 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18092 (substring s 0 (match-beginning ng))
18094 (substring s (match-end ng))))))
18097 (defun org-recenter-calendar (d)
18098 "If the calendar is visible, recenter it to date D."
18099 (let ((cwin (get-buffer-window "*Calendar*" t)))
18101 (let ((calendar-move-hook nil))
18102 (with-selected-window cwin
18103 (calendar-goto-date
18104 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18106 (defun org-goto-calendar (&optional arg)
18107 "Go to the Emacs calendar at the current date.
18108 If there is a time stamp in the current line, go to that date.
18109 A prefix ARG can be used to force the current date."
18111 (let ((calendar-move-hook nil)
18112 (calendar-view-holidays-initially-flag nil)
18113 (calendar-view-diary-initially-flag nil)
18115 (when (or (org-at-timestamp-p 'lax)
18116 (org-match-line (concat ".*" org-ts-regexp)))
18117 (let ((d1 (time-to-days (current-time)))
18118 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18119 (setq diff (- d2 d1))))
18121 (calendar-goto-today)
18122 (when (and diff (not arg)) (calendar-forward-day diff))))
18124 (defun org-get-date-from-calendar ()
18125 "Return a list (month day year) of date at point in calendar."
18126 (with-current-buffer "*Calendar*"
18128 (calendar-cursor-to-date))))
18130 (defun org-date-from-calendar ()
18131 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18132 If there is already a time stamp at the cursor position, update it."
18134 (if (org-at-timestamp-p 'lax)
18135 (org-timestamp-change 0 'calendar)
18136 (let ((cal-date (org-get-date-from-calendar)))
18137 (org-insert-time-stamp
18138 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18140 (defcustom org-effort-durations
18144 ("w" . ,(* 60 8 5))
18145 ("m" . ,(* 60 8 5 4))
18146 ("y" . ,(* 60 8 5 40)))
18147 "Conversion factor to minutes for an effort modifier.
18149 Each entry has the form (MODIFIER . MINUTES).
18151 In an effort string, a number followed by MODIFIER is multiplied
18152 by the specified number of MINUTES to obtain an effort in
18155 For example, if the value of this variable is ((\"hours\" . 60)), then an
18156 effort string \"2hours\" is equivalent to 120 minutes."
18159 :package-version '(Org . "8.3")
18160 :type '(alist :key-type (string :tag "Modifier")
18161 :value-type (number :tag "Minutes")))
18163 (defcustom org-image-actual-width t
18164 "Should we use the actual width of images when inlining them?
18166 When set to t, always use the image width.
18168 When set to a number, use imagemagick (when available) to set
18169 the image's width to this value.
18171 When set to a number in a list, try to get the width from any
18172 #+ATTR.* keyword if it matches a width specification like
18174 #+ATTR_HTML: :width 300px
18176 and fall back on that number if none is found.
18178 When set to nil, try to get the width from an #+ATTR.* keyword
18179 and fall back on the original width if none is found.
18181 This requires Emacs >= 24.1, build with imagemagick support."
18182 :group 'org-appearance
18184 :package-version '(Org . "8.0")
18186 (const :tag "Use the image width" t)
18187 (integer :tag "Use a number of pixels")
18188 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18189 (const :tag "Use #+ATTR* or don't resize" nil)))
18191 (defcustom org-agenda-inhibit-startup nil
18192 "Inhibit startup when preparing agenda buffers.
18193 When this variable is t, the initialization of the Org agenda
18194 buffers is inhibited: e.g. the visibility state is not set, the
18195 tables are not re-aligned, etc."
18198 :group 'org-agenda)
18200 (defcustom org-agenda-ignore-properties nil
18201 "Avoid updating text properties when building the agenda.
18202 Properties are used to prepare buffers for effort estimates,
18203 appointments, statistics and subtree-local categories.
18204 If you don't use these in the agenda, you can add them to this
18205 list and agenda building will be a bit faster.
18206 The value is a list, with zero or more of the symbols `effort', `appt',
18207 `stats' or `category'."
18208 :type '(set :greedy t
18214 :package-version '(Org . "8.3")
18215 :group 'org-agenda)
18219 (defun org-save-all-org-buffers ()
18220 "Save all Org buffers without user confirmation."
18222 (message "Saving all Org buffers...")
18223 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18224 (when (featurep 'org-id) (org-id-locations-save))
18225 (message "Saving all Org buffers... done"))
18227 (defun org-revert-all-org-buffers ()
18228 "Revert all Org buffers.
18229 Prompt for confirmation when there are unsaved changes.
18230 Be sure you know what you are doing before letting this function
18231 overwrite your changes.
18233 This function is useful in a setup where one tracks org files
18234 with a version control system, to revert on one machine after pulling
18235 changes from another. I believe the procedure must be like this:
18237 1. M-x org-save-all-org-buffers
18238 2. Pull changes from the other machine, resolve conflicts
18239 3. M-x org-revert-all-org-buffers"
18241 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18242 (user-error "Abort"))
18244 (save-window-excursion
18245 (dolist (b (buffer-list))
18246 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18247 (with-current-buffer b buffer-file-name))
18248 (pop-to-buffer-same-window b)
18249 (revert-buffer t 'no-confirm)))
18250 (when (and (featurep 'org-id) org-id-track-globally)
18251 (org-id-locations-load)))))
18256 (defun org-switchb (&optional arg)
18257 "Switch between Org buffers.
18259 With `\\[universal-argument]' prefix, restrict available buffers to files.
18261 With `\\[universal-argument] \\[universal-argument]' \
18262 prefix, restrict available buffers to agenda files."
18264 (let ((blist (org-buffer-list
18265 (cond ((equal arg '(4)) 'files)
18266 ((equal arg '(16)) 'agenda)))))
18267 (pop-to-buffer-same-window
18268 (completing-read "Org buffer: "
18269 (mapcar #'list (mapcar #'buffer-name blist))
18272 (defun org-buffer-list (&optional predicate exclude-tmp)
18273 "Return a list of Org buffers.
18274 PREDICATE can be `export', `files' or `agenda'.
18276 export restrict the list to Export buffers.
18277 files restrict the list to buffers visiting Org files.
18278 agenda restrict the list to buffers visiting agenda files.
18280 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18282 (agenda-files (and (eq predicate 'agenda)
18283 (mapcar 'file-truename (org-agenda-files t))))
18286 ((eq predicate 'files)
18287 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18288 ((eq predicate 'export)
18289 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18290 ((eq predicate 'agenda)
18292 (with-current-buffer b
18293 (and (derived-mode-p 'org-mode)
18294 (setq bfn (buffer-file-name b))
18295 (member (file-truename bfn) agenda-files)))))
18296 (t (lambda (b) (with-current-buffer b
18297 (or (derived-mode-p 'org-mode)
18298 (string-match "\\*Org .*Export"
18299 (buffer-name b)))))))))
18303 (if (and (funcall filter b)
18304 (or (not exclude-tmp)
18305 (not (string-match "tmp" (buffer-name b)))))
18310 (defun org-agenda-files (&optional unrestricted archives)
18311 "Get the list of agenda files.
18312 Optional UNRESTRICTED means return the full list even if a restriction
18313 is currently in place.
18314 When ARCHIVES is t, include all archive files that are really being
18315 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18316 `org-agenda-archives-mode' is t."
18319 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18320 ((stringp org-agenda-files) (org-read-agenda-file-list))
18321 ((listp org-agenda-files) org-agenda-files)
18322 (t (error "Invalid value of `org-agenda-files'")))))
18323 (setq files (apply 'append
18324 (mapcar (lambda (f)
18325 (if (file-directory-p f)
18327 f t org-agenda-file-regexp)
18330 (when org-agenda-skip-unavailable-files
18331 (setq files (delq nil
18334 (and (file-readable-p file) file)))
18336 (when (or (eq archives t)
18337 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18338 (setq files (org-add-archive-files files)))
18341 (defun org-agenda-file-p (&optional file)
18342 "Return non-nil, if FILE is an agenda file.
18343 If FILE is omitted, use the file associated with the current
18345 (let ((fname (or file (buffer-file-name))))
18347 (member (file-truename fname)
18348 (mapcar #'file-truename (org-agenda-files t))))))
18350 (defun org-edit-agenda-file-list ()
18351 "Edit the list of agenda files.
18352 Depending on setup, this either uses customize to edit the variable
18353 `org-agenda-files', or it visits the file that is holding the list. In the
18354 latter case, the buffer is set up in a way that saving it automatically kills
18355 the buffer and restores the previous window configuration."
18357 (if (stringp org-agenda-files)
18358 (let ((cw (current-window-configuration)))
18359 (find-file org-agenda-files)
18360 (setq-local org-window-configuration cw)
18361 (add-hook 'after-save-hook
18363 (set-window-configuration
18364 (prog1 org-window-configuration
18365 (kill-buffer (current-buffer))))
18366 (org-install-agenda-files-menu)
18367 (message "New agenda file list installed"))
18369 (message "%s" (substitute-command-keys
18370 "Edit list and finish with \\[save-buffer]")))
18371 (customize-variable 'org-agenda-files)))
18373 (defun org-store-new-agenda-file-list (list)
18374 "Set new value for the agenda file list and save it correctly."
18375 (if (stringp org-agenda-files)
18376 (let ((fe (org-read-agenda-file-list t)) b u)
18377 (while (setq b (find-buffer-visiting org-agenda-files))
18379 (with-temp-file org-agenda-files
18382 (lambda (f) ;; Keep un-expanded entries.
18383 (if (setq u (assoc f fe))
18388 (let ((org-mode-hook nil) (org-inhibit-startup t)
18389 (org-insert-mode-line-in-empty-file nil))
18390 (setq org-agenda-files list)
18391 (customize-save-variable 'org-agenda-files org-agenda-files))))
18393 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18394 "Read the list of agenda files from a file.
18395 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18396 filenames, used by `org-store-new-agenda-file-list' to write back
18397 un-expanded file names."
18398 (when (file-directory-p org-agenda-files)
18399 (error "`org-agenda-files' cannot be a single directory"))
18400 (when (stringp org-agenda-files)
18402 (insert-file-contents org-agenda-files)
18405 (let ((e (expand-file-name (substitute-in-file-name f)
18407 (if pair-with-expansion
18410 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18413 (defun org-cycle-agenda-files ()
18414 "Cycle through the files in `org-agenda-files'.
18415 If the current buffer visits an agenda file, find the next one in the list.
18416 If the current buffer does not, find the first agenda file."
18418 (let* ((fs (or (org-agenda-files t)
18419 (user-error "No agenda files")))
18420 (files (copy-sequence fs))
18421 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18424 (while (and (setq file (pop files))
18425 (not (equal (file-truename file) tcf)))))
18426 (find-file (car (or files fs)))
18427 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18429 (defun org-agenda-file-to-front (&optional to-end)
18430 "Move/add the current file to the top of the agenda file list.
18431 If the file is not present in the list, it is added to the front. If it is
18432 present, it is moved there. With optional argument TO-END, add/move to the
18435 (let ((org-agenda-skip-unavailable-files nil)
18436 (file-alist (mapcar (lambda (x)
18437 (cons (file-truename x) x))
18438 (org-agenda-files t)))
18439 (ctf (file-truename
18440 (or buffer-file-name
18441 (user-error "Please save the current buffer to a file"))))
18443 (setq x (assoc ctf file-alist) had x)
18445 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18447 (setq file-alist (append (delq x file-alist) (list x)))
18448 (setq file-alist (cons x (delq x file-alist))))
18449 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18450 (org-install-agenda-files-menu)
18451 (message "File %s to %s of agenda file list"
18452 (if had "moved" "added") (if to-end "end" "front"))))
18454 (defun org-remove-file (&optional file)
18455 "Remove current file from the list of files in variable `org-agenda-files'.
18456 These are the files which are being checked for agenda entries.
18457 Optional argument FILE means use this file instead of the current."
18459 (let* ((org-agenda-skip-unavailable-files nil)
18460 (file (or file buffer-file-name
18461 (user-error "Current buffer does not visit a file")))
18462 (true-file (file-truename file))
18463 (afile (abbreviate-file-name file))
18464 (files (delq nil (mapcar
18466 (unless (equal true-file
18469 (org-agenda-files t)))))
18470 (if (not (= (length files) (length (org-agenda-files t))))
18472 (org-store-new-agenda-file-list files)
18473 (org-install-agenda-files-menu)
18474 (message "Removed from Org Agenda list: %s" afile))
18475 (message "File was not in list: %s (not removed)" afile))))
18477 (defun org-file-menu-entry (file)
18478 (vector file (list 'find-file file) t))
18480 (defun org-check-agenda-file (file)
18481 "Make sure FILE exists. If not, ask user what to do."
18482 (unless (file-exists-p file)
18483 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18484 (abbreviate-file-name file))
18485 (let ((r (downcase (read-char-exclusive))))
18488 (org-remove-file file)
18489 (throw 'nextfile t))
18490 (t (user-error "Abort"))))))
18492 (defun org-get-agenda-file-buffer (file)
18493 "Get an agenda buffer visiting FILE.
18494 If the buffer needs to be created, add it to the list of buffers
18495 which might be released later."
18496 (let ((buf (org-find-base-buffer-visiting file)))
18498 buf ; just return it
18499 ;; Make a new buffer and remember it
18500 (setq buf (find-file-noselect file))
18501 (when buf (push buf org-agenda-new-buffers))
18504 (defun org-release-buffers (blist)
18505 "Release all buffers in list, asking the user for confirmation when needed.
18506 When a buffer is unmodified, it is just killed. When modified, it is saved
18507 \(if the user agrees) and then killed."
18509 (dolist (buf blist)
18510 (setq file (buffer-file-name buf))
18511 (when (and (buffer-modified-p buf)
18513 (y-or-n-p (format "Save file %s? " file)))
18514 (with-current-buffer buf (save-buffer)))
18515 (kill-buffer buf))))
18517 (defun org-agenda-prepare-buffers (files)
18518 "Create buffers for all agenda files, protect archived trees and comments."
18520 (let ((pa '(:org-archived t))
18521 (pc '(:org-comment t))
18522 (pall '(:org-archived t :org-comment t))
18523 (inhibit-read-only t)
18524 (org-inhibit-startup org-agenda-inhibit-startup)
18525 (rea (concat ":" org-archive-tag ":"))
18527 (setq org-tag-alist-for-agenda nil
18528 org-tag-groups-alist-for-agenda nil)
18531 (dolist (file files)
18535 (org-check-agenda-file file)
18536 (set-buffer (org-get-agenda-file-buffer file)))
18538 (org-set-regexps-and-options 'tags-only)
18540 (or (memq 'category org-agenda-ignore-properties)
18541 (org-refresh-category-properties))
18542 (or (memq 'stats org-agenda-ignore-properties)
18543 (org-refresh-stats-properties))
18544 (or (memq 'effort org-agenda-ignore-properties)
18545 (org-refresh-effort-properties))
18546 (or (memq 'appt org-agenda-ignore-properties)
18547 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18548 (setq org-todo-keywords-for-agenda
18549 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18550 (setq org-done-keywords-for-agenda
18551 (append org-done-keywords-for-agenda org-done-keywords))
18552 (setq org-todo-keyword-alist-for-agenda
18553 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18554 (setq org-tag-alist-for-agenda
18556 (append org-tag-alist-for-agenda
18557 org-current-tag-alist)))
18558 ;; Merge current file's tag groups into global
18559 ;; `org-tag-groups-alist-for-agenda'.
18560 (when org-group-tags
18561 (dolist (alist org-tag-groups-alist)
18562 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18564 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18565 (push alist org-tag-groups-alist-for-agenda)))))
18566 (org-with-silent-modifications
18568 (remove-text-properties (point-min) (point-max) pall)
18569 (when org-agenda-skip-archived-trees
18570 (goto-char (point-min))
18571 (while (re-search-forward rea nil t)
18572 (when (org-at-heading-p t)
18573 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18574 (goto-char (point-min))
18575 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18576 (while (re-search-forward re nil t)
18577 (when (save-match-data (org-in-commented-heading-p t))
18578 (add-text-properties
18579 (match-beginning 0) (org-end-of-subtree t) pc)))))
18580 (goto-char pos)))))
18581 (setq org-todo-keywords-for-agenda
18582 (org-uniquify org-todo-keywords-for-agenda))
18583 (setq org-todo-keyword-alist-for-agenda
18584 (org-uniquify org-todo-keyword-alist-for-agenda))))
18587 ;;;; CDLaTeX minor mode
18589 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18590 "Keymap for the minor `org-cdlatex-mode'.")
18592 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18593 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18594 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18595 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18596 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18598 (defvar org-cdlatex-texmathp-advice-is-done nil
18599 "Flag remembering if we have applied the advice to texmathp already.")
18601 (define-minor-mode org-cdlatex-mode
18602 "Toggle the minor `org-cdlatex-mode'.
18603 This mode supports entering LaTeX environment and math in LaTeX fragments
18605 \\{org-cdlatex-mode-map}"
18607 (when org-cdlatex-mode
18609 (run-hooks 'cdlatex-mode-hook)
18610 (cdlatex-compute-tables))
18611 (unless org-cdlatex-texmathp-advice-is-done
18612 (setq org-cdlatex-texmathp-advice-is-done t)
18613 (defadvice texmathp (around org-math-always-on activate)
18614 "Always return t in Org buffers.
18615 This is because we want to insert math symbols without dollars even outside
18616 the LaTeX math segments. If Org mode thinks that point is actually inside
18617 an embedded LaTeX fragment, let `texmathp' do its job.
18618 `\\[org-cdlatex-mode-map]'"
18622 ((not (derived-mode-p 'org-mode)) ad-do-it)
18623 ((eq this-command 'cdlatex-math-symbol)
18624 (setq ad-return-value t
18625 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18627 (let ((p (org-inside-LaTeX-fragment-p)))
18628 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18629 (setq ad-return-value t
18630 texmathp-why '("Org mode embedded math" . 0))
18631 (when p ad-do-it)))))))))
18633 (defun turn-on-org-cdlatex ()
18634 "Unconditionally turn on `org-cdlatex-mode'."
18635 (org-cdlatex-mode 1))
18637 (defun org-try-cdlatex-tab ()
18638 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18639 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18640 - inside a LaTeX fragment, or
18641 - after the first word in a line, where an abbreviation expansion could
18642 insert a LaTeX environment."
18643 (when org-cdlatex-mode
18645 ;; Before any word on the line: No expansion possible.
18646 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18647 ;; Just after first word on the line: Expand it. Make sure it
18648 ;; cannot happen on headlines, though.
18650 (skip-chars-backward "a-zA-Z0-9*")
18651 (skip-chars-backward " \t")
18652 (and (bolp) (not (org-at-heading-p))))
18654 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18656 (defun org-cdlatex-underscore-caret (&optional _arg)
18657 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18658 Revert to the normal definition outside of these fragments."
18660 (if (org-inside-LaTeX-fragment-p)
18661 (call-interactively 'cdlatex-sub-superscript)
18662 (let (org-cdlatex-mode)
18663 (call-interactively (key-binding (vector last-input-event))))))
18665 (defun org-cdlatex-math-modify (&optional _arg)
18666 "Execute `cdlatex-math-modify' in LaTeX fragments.
18667 Revert to the normal definition outside of these fragments."
18669 (if (org-inside-LaTeX-fragment-p)
18670 (call-interactively 'cdlatex-math-modify)
18671 (let (org-cdlatex-mode)
18672 (call-interactively (key-binding (vector last-input-event))))))
18674 (defun org-cdlatex-environment-indent (&optional environment item)
18675 "Execute `cdlatex-environment' and indent the inserted environment.
18677 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18679 The inserted environment is indented to current indentation
18680 unless point is at the beginning of the line, in which the
18681 environment remains unintended."
18683 ;; cdlatex-environment always return nil. Therefore, capture output
18684 ;; first and determine if an environment was selected.
18685 (let* ((beg (point-marker))
18686 (end (copy-marker (point) t))
18688 (ignore-errors (cdlatex-environment environment item))
18690 ;; Figure out how many lines to move forward after the
18691 ;; environment has been inserted.
18692 (lines (when inserted
18694 (- (cl-loop while (< beg (point))
18696 do (forward-line -1)
18699 (if (progn (goto-char beg)
18700 (and (progn (skip-chars-forward " \t") (eolp))
18701 (progn (skip-chars-backward " \t") (bolp))))
18703 (env (org-trim (delete-and-extract-region beg end))))
18705 ;; Get indentation of next line unless at column 0.
18706 (let ((ind (if (bolp) 0
18708 (org-return-indent)
18709 (prog1 (org-get-indentation)
18710 (when (progn (skip-chars-forward " \t") (eolp))
18711 (delete-region beg (point)))))))
18712 (bol (progn (skip-chars-backward " \t") (bolp))))
18713 ;; Insert a newline before environment unless at column zero
18714 ;; to "escape" the current line. Insert a newline if
18715 ;; something is one the same line as \end{ENVIRONMENT}.
18717 (concat (unless bol "\n") env
18718 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18719 (unless (zerop ind)
18722 (while (< (point) end)
18723 (unless (eolp) (indent-line-to ind))
18726 (forward-line lines)
18727 (indent-line-to ind)))
18728 (set-marker beg nil)
18729 (set-marker end nil)))
18732 ;;;; LaTeX fragments
18734 (defun org-inside-LaTeX-fragment-p ()
18735 "Test if point is inside a LaTeX fragment.
18736 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18737 sequence appearing also before point.
18738 Even though the matchers for math are configurable, this function assumes
18739 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18740 delimiters are skipped when they have been removed by customization.
18741 The return value is nil, or a cons cell with the delimiter and the
18742 position of this delimiter.
18744 This function does a reasonably good job, but can locally be fooled by
18745 for example currency specifications. For example it will assume being in
18746 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18747 fragments that are properly closed, but during editing, we have to live
18748 with the uncertainty caused by missing closing delimiters. This function
18749 looks only before point, not after."
18751 (let ((pos (point))
18752 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18753 (lim (save-excursion (org-backward-paragraph) (point)))
18754 dd-on str (start 0) m re)
18757 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18758 re (nth 1 (assoc "$" org-latex-regexps)))
18759 (while (string-match re str start)
18761 ((= (match-end 0) (length str))
18762 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18763 ((= (match-end 0) (- (length str) 5))
18765 (t (setq start (match-end 0))))))
18766 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18768 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18769 (and (match-beginning 2) (throw 'exit nil))
18771 (while (re-search-backward "\\$\\$" lim t)
18772 (setq dd-on (not dd-on)))
18774 (when dd-on (cons "$$" m))))))
18776 (defun org-inside-latex-macro-p ()
18777 "Is point inside a LaTeX macro or its arguments?"
18780 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18782 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18783 "Build an overlay between BEG and END using IMAGE file.
18784 Argument IMAGETYPE is the extension of the displayed image,
18785 as a string. It defaults to \"png\"."
18786 (let ((ov (make-overlay beg end))
18787 (imagetype (or (intern imagetype) 'png)))
18788 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18789 (overlay-put ov 'evaporate t)
18791 'modification-hooks
18792 (list (lambda (o _flag _beg _end &optional _l)
18793 (delete-overlay o))))
18796 (list 'image :type imagetype :file image :ascent 'center))))
18798 (defun org--list-latex-overlays (&optional beg end)
18799 "List all Org LaTeX overlays in current buffer.
18800 Limit to overlays between BEG and END when those are provided."
18802 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18803 (overlays-in (or beg (point-min)) (or end (point-max)))))
18805 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18806 "Remove all overlays with LaTeX fragment images in current buffer.
18807 When optional arguments BEG and END are non-nil, remove all
18808 overlays between them instead. Return a non-nil value when some
18809 overlays were removed, nil otherwise."
18810 (let ((overlays (org--list-latex-overlays beg end)))
18811 (mapc #'delete-overlay overlays)
18814 (defun org-toggle-latex-fragment (&optional arg)
18815 "Preview the LaTeX fragment at point, or all locally or globally.
18817 If the cursor is on a LaTeX fragment, create the image and overlay
18818 it over the source code, if there is none. Remove it otherwise.
18819 If there is no fragment at point, display all fragments in the
18822 With prefix ARG, preview or clear image for all fragments in the
18823 current subtree or in the whole buffer when used before the first
18824 headline. With a prefix ARG `\\[universal-argument] \
18825 \\[universal-argument]' preview or clear images
18826 for all fragments in the buffer."
18828 (when (display-graphic-p)
18833 ((or (equal arg '(16))
18834 (and (equal arg '(4))
18835 (org-with-limited-levels (org-before-first-heading-p))))
18836 (if (org-remove-latex-fragment-image-overlays)
18837 (progn (message "LaTeX fragments images removed from buffer")
18839 (setq msg "Creating images for buffer...")))
18841 (org-with-limited-levels (org-back-to-heading t))
18843 (setq end (progn (org-end-of-subtree t) (point)))
18844 (if (org-remove-latex-fragment-image-overlays beg end)
18846 (message "LaTeX fragment images removed from subtree")
18848 (setq msg "Creating images for subtree...")))
18849 ((let ((datum (org-element-context)))
18850 (when (memq (org-element-type datum)
18851 '(latex-environment latex-fragment))
18852 (setq beg (org-element-property :begin datum))
18853 (setq end (org-element-property :end datum))
18854 (if (org-remove-latex-fragment-image-overlays beg end)
18855 (progn (message "LaTeX fragment image removed")
18857 (setq msg "Creating image...")))))
18859 (org-with-limited-levels
18860 (setq beg (if (org-at-heading-p) (line-beginning-position)
18861 (outline-previous-heading)
18863 (setq end (progn (outline-next-heading) (point)))
18864 (if (org-remove-latex-fragment-image-overlays beg end)
18866 (message "LaTeX fragment images removed from section")
18868 (setq msg "Creating images for section...")))))
18869 (let ((file (buffer-file-name (buffer-base-buffer))))
18871 (concat org-preview-latex-image-directory "org-ltximg")
18873 ;; Emacs cannot overlay images from remote hosts. Create
18874 ;; it in `temporary-file-directory' instead.
18875 (if (or (not file) (file-remote-p file))
18876 temporary-file-directory
18878 'overlays msg 'forbuffer org-preview-latex-default-process))
18879 (message (concat msg "done")))))))
18881 (defun org-format-latex
18882 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18883 "Replace LaTeX fragments with links to an image.
18885 The function takes care of creating the replacement image.
18887 Only consider fragments between BEG and END when those are
18890 When optional argument OVERLAYS is non-nil, display the image on
18891 top of the fragment instead of replacing it.
18893 PROCESSING-TYPE is the conversion method to use, as a symbol.
18895 Some of the options can be changed using the variable
18896 `org-format-latex-options', which see."
18897 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18898 (unless (eq processing-type 'verbatim)
18899 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18902 (goto-char (or beg (point-min)))
18903 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18904 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18905 (overlay-recenter (or end (point-max))))
18906 (while (re-search-forward math-regexp end t)
18907 (unless (and overlays
18908 (eq (get-char-property (point) 'org-overlay-type)
18909 'org-latex-overlay))
18910 (let* ((context (org-element-context))
18911 (type (org-element-type context)))
18912 (when (memq type '(latex-environment latex-fragment))
18913 (let ((block-type (eq type 'latex-environment))
18914 (value (org-element-property :value context))
18915 (beg (org-element-property :begin context))
18916 (end (save-excursion
18917 (goto-char (org-element-property :end context))
18918 (skip-chars-backward " \r\t\n")
18921 ((eq processing-type 'mathjax)
18922 ;; Prepare for MathJax processing.
18923 (if (not (string-match "\\`\\$\\$?" value))
18925 (delete-region beg end)
18926 (if (string= (match-string 0 value) "$$")
18927 (insert "\\[" (substring value 2 -2) "\\]")
18928 (insert "\\(" (substring value 1 -1) "\\)"))))
18929 ((assq processing-type org-preview-latex-process-alist)
18930 ;; Process to an image.
18933 (let* ((processing-info
18934 (cdr (assq processing-type org-preview-latex-process-alist)))
18935 (face (face-at-point))
18936 ;; Get the colors from the face at point.
18938 (let ((color (plist-get org-format-latex-options
18940 (if (and forbuffer (eq color 'auto))
18941 (face-attribute face :foreground nil 'default)
18944 (let ((color (plist-get org-format-latex-options
18946 (if (and forbuffer (eq color 'auto))
18947 (face-attribute face :background nil 'default)
18949 (hash (sha1 (prin1-to-string
18950 (list org-format-latex-header
18951 org-latex-default-packages-alist
18952 org-latex-packages-alist
18953 org-format-latex-options
18954 forbuffer value fg bg))))
18955 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18956 (absprefix (expand-file-name prefix dir))
18957 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18958 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18959 (sep (and block-type "\n\n"))
18960 (link (concat sep "[[file:" linkfile "]]" sep))
18962 (org-combine-plists
18963 org-format-latex-options
18964 `(:foreground ,fg :background ,bg))))
18965 (when msg (message msg cnt))
18966 (unless checkdir-flag ; Ensure the directory exists.
18967 (setq checkdir-flag t)
18968 (let ((todir (file-name-directory absprefix)))
18969 (unless (file-directory-p todir)
18970 (make-directory todir t))))
18971 (unless (file-exists-p movefile)
18972 (org-create-formula-image
18973 value movefile options forbuffer processing-type))
18976 (dolist (o (overlays-in beg end))
18977 (when (eq (overlay-get o 'org-overlay-type)
18978 'org-latex-overlay)
18979 (delete-overlay o)))
18980 (org--format-latex-make-overlay beg end movefile imagetype)
18982 (delete-region beg end)
18984 (org-add-props link
18985 (list 'org-latex-src
18986 (replace-regexp-in-string "\"" "" value)
18987 'org-latex-src-embed-type
18988 (if block-type 'paragraph 'character)))))))
18989 ((eq processing-type 'mathml)
18990 ;; Process to MathML.
18991 (unless (org-format-latex-mathml-available-p)
18992 (user-error "LaTeX to MathML converter not configured"))
18994 (when msg (message msg cnt))
18996 (delete-region beg end)
18997 (insert (org-format-latex-as-mathml
18998 value block-type prefix dir)))
19000 (error "Unknown conversion process %s for LaTeX fragments"
19001 processing-type)))))))))))
19003 (defun org-create-math-formula (latex-frag &optional mathml-file)
19004 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19005 Use `org-latex-to-mathml-convert-command'. If the conversion is
19006 sucessful, return the portion between \"<math...> </math>\"
19007 elements otherwise return nil. When MATHML-FILE is specified,
19008 write the results in to that file. When invoked as an
19009 interactive command, prompt for LATEX-FRAG, with initial value
19010 set to the current active region and echo the results for user
19012 (interactive (list (let ((frag (when (org-region-active-p)
19013 (buffer-substring-no-properties
19014 (region-beginning) (region-end)))))
19015 (read-string "LaTeX Fragment: " frag nil frag))))
19016 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19017 (let* ((tmp-in-file
19018 (let ((file (file-relative-name
19019 (make-temp-name (expand-file-name "ltxmathml-in")))))
19020 (write-region latex-frag nil file)
19022 (tmp-out-file (file-relative-name
19023 (make-temp-name (expand-file-name "ltxmathml-out"))))
19025 org-latex-to-mathml-convert-command
19026 `((?j . ,(and org-latex-to-mathml-jar-file
19027 (shell-quote-argument
19029 org-latex-to-mathml-jar-file))))
19030 (?I . ,(shell-quote-argument tmp-in-file))
19032 (?o . ,(shell-quote-argument tmp-out-file)))))
19033 mathml shell-command-output)
19034 (when (called-interactively-p 'any)
19035 (unless (org-format-latex-mathml-available-p)
19036 (user-error "LaTeX to MathML converter not configured")))
19037 (message "Running %s" cmd)
19038 (setq shell-command-output (shell-command-to-string cmd))
19040 (when (file-readable-p tmp-out-file)
19041 (with-current-buffer (find-file-noselect tmp-out-file t)
19042 (goto-char (point-min))
19043 (when (re-search-forward
19044 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19046 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19048 (prog1 (match-string 0) (kill-buffer))))))
19052 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19054 (write-region mathml nil mathml-file))
19055 (when (called-interactively-p 'any)
19057 ((message "LaTeX to MathML conversion failed")
19058 (message shell-command-output)))
19059 (delete-file tmp-in-file)
19060 (when (file-exists-p tmp-out-file)
19061 (delete-file tmp-out-file))
19064 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19065 prefix &optional dir)
19066 "Use `org-create-math-formula' but check local cache first."
19067 (let* ((absprefix (expand-file-name prefix dir))
19068 (print-length nil) (print-level nil)
19069 (formula-id (concat
19074 org-latex-to-mathml-convert-command)))))
19075 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19076 (formula-cache-dir (file-name-directory formula-cache)))
19078 (unless (file-directory-p formula-cache-dir)
19079 (make-directory formula-cache-dir t))
19081 (unless (file-exists-p formula-cache)
19082 (org-create-math-formula latex-frag formula-cache))
19084 (if (file-exists-p formula-cache)
19085 ;; Successful conversion. Return the link to MathML file.
19087 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19088 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19089 'org-latex-src-embed-type (if latex-frag-type
19090 'paragraph 'character)))
19091 ;; Failed conversion. Return the LaTeX fragment verbatim
19094 (defun org--get-display-dpi ()
19095 "Get the DPI of the display.
19096 The function assumes that the display has the same pixel width in
19097 the horizontal and vertical directions."
19098 (if (display-graphic-p)
19099 (round (/ (display-pixel-height)
19100 (/ (display-mm-height) 25.4)))
19101 (error "Attempt to calculate the dpi of a non-graphic display")))
19103 (defun org-create-formula-image
19104 (string tofile options buffer &optional processing-type)
19105 "Create an image from LaTeX source using external processes.
19107 The LaTeX STRING is saved to a temporary LaTeX file, then
19108 converted to an image file by process PROCESSING-TYPE defined in
19109 `org-preview-latex-process-alist'. A nil value defaults to
19110 `org-preview-latex-default-process'.
19112 The generated image file is eventually moved to TOFILE.
19114 The OPTIONS argument controls the size, foreground color and
19115 background color of the generated image.
19117 When BUFFER non-nil, this function is used for LaTeX previewing.
19118 Otherwise, it is used to deal with LaTeX snippets showed in
19120 (let* ((processing-type (or processing-type
19121 org-preview-latex-default-process))
19123 (cdr (assq processing-type org-preview-latex-process-alist)))
19124 (programs (plist-get processing-info :programs))
19125 (error-message (or (plist-get processing-info :message) ""))
19126 (use-xcolor (plist-get processing-info :use-xcolor))
19127 (image-input-type (plist-get processing-info :image-input-type))
19128 (image-output-type (plist-get processing-info :image-output-type))
19129 (post-clean (or (plist-get processing-info :post-clean)
19130 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19131 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19133 (or (plist-get processing-info :latex-header)
19134 (org-latex-make-preamble
19135 (org-export-get-environment (org-export-get-backend 'latex))
19136 org-format-latex-header
19138 (latex-compiler (plist-get processing-info :latex-compiler))
19139 (image-converter (plist-get processing-info :image-converter))
19140 (tmpdir temporary-file-directory)
19141 (texfilebase (make-temp-name
19142 (expand-file-name "orgtex" tmpdir)))
19143 (texfile (concat texfilebase ".tex"))
19144 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19146 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19147 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19148 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19149 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19151 (bg (or (plist-get options (if buffer :background :html-background))
19153 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19154 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19155 (dolist (program programs)
19156 (org-check-external-command program error-message))
19158 (progn (if (eq fg 'default)
19159 (setq fg (org-latex-color :foreground))
19160 (setq fg (org-latex-color-format fg)))
19161 (if (eq bg 'default)
19162 (setq bg (org-latex-color :background))
19163 (setq bg (org-latex-color-format
19164 (if (string= bg "Transparent") "white" bg))))
19165 (with-temp-file texfile
19166 (insert latex-header)
19167 (insert "\n\\begin{document}\n"
19168 "\\definecolor{fg}{rgb}{" fg "}\n"
19169 "\\definecolor{bg}{rgb}{" bg "}\n"
19170 "\n\\pagecolor{bg}\n"
19174 "\n\\end{document}\n")))
19175 (if (eq fg 'default)
19176 (setq fg (org-dvipng-color :foreground))
19177 (unless (string= fg "Transparent")
19178 (setq fg (org-dvipng-color-format fg))))
19179 (if (eq bg 'default)
19180 (setq bg (org-dvipng-color :background))
19181 (unless (string= bg "Transparent")
19182 (setq bg (org-dvipng-color-format bg))))
19183 (with-temp-file texfile
19184 (insert latex-header)
19185 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19187 (let* ((err-msg (format "Please adjust `%s' part of \
19188 `org-preview-latex-process-alist'."
19192 texfile latex-compiler image-input-type err-msg log-buf))
19195 image-input-file image-converter image-output-type err-msg log-buf
19196 `((?F . ,(shell-quote-argument fg))
19197 (?B . ,(shell-quote-argument bg))
19198 (?D . ,(shell-quote-argument (format "%s" dpi)))
19199 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19200 (copy-file image-output-file tofile 'replace)
19201 (dolist (e post-clean)
19202 (when (file-exists-p (concat texfilebase e))
19203 (delete-file (concat texfilebase e))))
19204 image-output-file)))
19206 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19207 "Fill a LaTeX header template TPL.
19208 In the template, the following place holders will be recognized:
19210 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19211 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19212 [PACKAGES] \\usepackage statements for PKG
19213 [NO-PACKAGES] do not include PKG
19214 [EXTRA] the string EXTRA
19215 [NO-EXTRA] do not include EXTRA
19217 For backward compatibility, if both the positive and the negative place
19218 holder is missing, the positive one (without the \"NO-\") will be
19219 assumed to be present at the end of the template.
19220 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19222 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19223 (let (rpl (end ""))
19224 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19225 (setq rpl (if (or (match-end 1) (not def-pkg))
19226 "" (org-latex-packages-to-string def-pkg snippets-p t))
19227 tpl (replace-match rpl t t tpl))
19228 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19230 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19231 (setq rpl (if (or (match-end 1) (not pkg))
19232 "" (org-latex-packages-to-string pkg snippets-p t))
19233 tpl (replace-match rpl t t tpl))
19234 (when pkg (setq end
19236 (org-latex-packages-to-string pkg snippets-p)))))
19238 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19239 (setq rpl (if (or (match-end 1) (not extra))
19240 "" (concat extra "\n"))
19241 tpl (replace-match rpl t t tpl))
19242 (when (and extra (string-match "\\S-" extra))
19243 (setq end (concat end "\n" extra))))
19245 (if (string-match "\\S-" end)
19246 (concat tpl "\n" end)
19249 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19250 "Turn an alist of packages into a string with the \\usepackage macros."
19251 (setq pkg (mapconcat (lambda(p)
19254 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19255 (format "%% Package %s omitted" (cadr p)))
19256 ((equal "" (car p))
19257 (format "\\usepackage{%s}" (cadr p)))
19259 (format "\\usepackage[%s]{%s}"
19260 (car p) (cadr p)))))
19263 (if newline (concat pkg "\n") pkg))
19265 (defun org-dvipng-color (attr)
19266 "Return a RGB color specification for dvipng."
19267 (org-dvipng-color-format (face-attribute 'default attr nil)))
19269 (defun org-dvipng-color-format (color-name)
19270 "Convert COLOR-NAME to a RGB color value for dvipng."
19271 (apply #'format "rgb %s %s %s"
19272 (mapcar 'org-normalize-color
19273 (color-values color-name))))
19275 (defun org-latex-color (attr)
19276 "Return a RGB color for the LaTeX color package."
19277 (org-latex-color-format (face-attribute 'default attr nil)))
19279 (defun org-latex-color-format (color-name)
19280 "Convert COLOR-NAME to a RGB color value."
19281 (apply #'format "%s,%s,%s"
19282 (mapcar 'org-normalize-color
19283 (color-values color-name))))
19285 (defun org-normalize-color (value)
19286 "Return string to be used as color value for an RGB component."
19287 (format "%g" (/ value 65535.0)))
19293 (defvar-local org-inline-image-overlays nil)
19295 (defun org-toggle-inline-images (&optional include-linked)
19296 "Toggle the display of inline images.
19297 INCLUDE-LINKED is passed to `org-display-inline-images'."
19299 (if org-inline-image-overlays
19301 (org-remove-inline-images)
19302 (when (called-interactively-p 'interactive)
19303 (message "Inline image display turned off")))
19304 (org-display-inline-images include-linked)
19305 (when (called-interactively-p 'interactive)
19306 (message (if org-inline-image-overlays
19307 (format "%d images displayed inline"
19308 (length org-inline-image-overlays))
19309 "No images to display inline")))))
19311 (defun org-redisplay-inline-images ()
19312 "Refresh the display of inline images."
19314 (if (not org-inline-image-overlays)
19315 (org-toggle-inline-images)
19316 (org-toggle-inline-images)
19317 (org-toggle-inline-images)))
19319 (defun org-display-inline-images (&optional include-linked refresh beg end)
19320 "Display inline images.
19322 An inline image is a link which follows either of these
19325 1. Its path is a file with an extension matching return value
19326 from `image-file-name-regexp' and it has no contents.
19328 2. Its description consists in a single link of the previous
19331 When optional argument INCLUDE-LINKED is non-nil, also links with
19332 a text description part will be inlined. This can be nice for
19333 a quick look at those images, but it does not reflect what
19334 exported files will look like.
19336 When optional argument REFRESH is non-nil, refresh existing
19337 images between BEG and END. This will create new image displays
19338 only if necessary. BEG and END default to the buffer
19341 (when (display-graphic-p)
19343 (org-remove-inline-images)
19344 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19345 (org-with-wide-buffer
19346 (goto-char (or beg (point-min)))
19347 (let* ((case-fold-search t)
19348 (file-extension-re (image-file-name-regexp))
19349 (link-abbrevs (mapcar #'car
19350 (append org-link-abbrev-alist-local
19351 org-link-abbrev-alist)))
19352 ;; Check absolute, relative file names and explicit
19353 ;; "file:" links. Also check link abbreviations since
19354 ;; some might expand to "file" links.
19355 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19356 (if (not link-abbrevs) ""
19357 (format "\\|\\(?:%s:\\)"
19358 (regexp-opt link-abbrevs))))))
19359 (while (re-search-forward file-types-re end t)
19360 (let ((link (save-match-data (org-element-context))))
19361 ;; Check if we're at an inline image, i.e., an image file
19362 ;; link without a description (unless INCLUDE-LINKED is
19364 (when (and (equal "file" (org-element-property :type link))
19366 (null (org-element-contents link)))
19367 (string-match-p file-extension-re
19368 (org-element-property :path link)))
19369 (let ((file (expand-file-name
19371 (org-element-property :path link)))))
19372 (when (file-exists-p file)
19374 ;; Apply `org-image-actual-width' specifications.
19376 ((not (image-type-available-p 'imagemagick)) nil)
19377 ((eq org-image-actual-width t) nil)
19378 ((listp org-image-actual-width)
19380 ;; First try to find a width among
19381 ;; attributes associated to the paragraph
19382 ;; containing link.
19385 (while (and (setq e (org-element-property
19387 (not (eq (org-element-type e)
19392 (goto-char (org-element-property :begin paragraph))
19395 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19396 (org-element-property
19397 :post-affiliated paragraph)
19399 (string-to-number (match-string 1))))))
19400 ;; Otherwise, fall-back to provided number.
19401 (car org-image-actual-width)))
19402 ((numberp org-image-actual-width)
19403 org-image-actual-width)))
19404 (old (get-char-property-and-overlay
19405 (org-element-property :begin link)
19406 'org-image-overlay)))
19407 (if (and (car-safe old) refresh)
19408 (image-refresh (overlay-get (cdr old) 'display))
19409 (let ((image (create-image file
19410 (and width 'imagemagick)
19414 (let ((ov (make-overlay
19415 (org-element-property :begin link)
19418 (org-element-property :end link))
19419 (skip-chars-backward " \t")
19421 (overlay-put ov 'display image)
19422 (overlay-put ov 'face 'default)
19423 (overlay-put ov 'org-image-overlay t)
19425 ov 'modification-hooks
19426 (list 'org-display-inline-remove-overlay))
19427 (push ov org-inline-image-overlays)))))))))))))))
19429 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19430 "Remove inline-display overlay if a corresponding region is modified."
19431 (let ((inhibit-modification-hooks t))
19432 (when (and ov after)
19433 (delete ov org-inline-image-overlays)
19434 (delete-overlay ov))))
19436 (defun org-remove-inline-images ()
19437 "Remove inline display of images."
19439 (mapc #'delete-overlay org-inline-image-overlays)
19440 (setq org-inline-image-overlays nil))
19444 (defun org-remap (map &rest commands)
19445 "In MAP, remap the functions given in COMMANDS.
19446 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19449 (setq old (pop commands) new (pop commands))
19450 (org-defkey map (vector 'remap old) new))))
19452 ;; Outline functions from `outline-mode-prefix-map'
19453 ;; that can be remapped in Org:
19454 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19455 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19456 (define-key org-mode-map [remap outline-forward-same-level]
19457 'org-forward-heading-same-level)
19458 (define-key org-mode-map [remap outline-backward-same-level]
19459 'org-backward-heading-same-level)
19460 (define-key org-mode-map [remap outline-show-branches]
19461 'org-kill-note-or-show-branches)
19462 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19463 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19464 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19465 (define-key org-mode-map [remap outline-next-visible-heading]
19466 'org-next-visible-heading)
19467 (define-key org-mode-map [remap outline-previous-visible-heading]
19468 'org-previous-visible-heading)
19469 (define-key org-mode-map [remap show-children] 'org-show-children)
19471 ;; Outline functions from `outline-mode-prefix-map' that can not
19472 ;; be remapped in Org:
19474 ;; - the column "key binding" shows whether the Outline function is still
19475 ;; available in Org mode on the same key that it has been bound to in
19477 ;; - "overridden": key used for a different functionality in Org mode
19478 ;; - else: key still bound to the same Outline function in Org mode
19480 ;; | Outline function | key binding | Org replacement |
19481 ;; |------------------------------------+-------------+--------------------------|
19482 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19483 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19484 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19485 ;; | `show-entry' | overridden | no replacement |
19486 ;; | `show-branches' | `C-c C-k' | still same function |
19487 ;; | `show-subtree' | overridden | visibility cycling |
19488 ;; | `show-all' | overridden | no replacement |
19489 ;; | `hide-subtree' | overridden | visibility cycling |
19490 ;; | `hide-body' | overridden | no replacement |
19491 ;; | `hide-entry' | overridden | visibility cycling |
19492 ;; | `hide-leaves' | overridden | no replacement |
19493 ;; | `hide-sublevels' | overridden | no replacement |
19494 ;; | `hide-other' | overridden | no replacement |
19496 ;; Make `C-c C-x' a prefix key
19497 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19499 ;; TAB key with modifiers
19500 (org-defkey org-mode-map "\C-i" 'org-cycle)
19501 (org-defkey org-mode-map [(tab)] 'org-cycle)
19502 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19503 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19505 ;; The following line is necessary under Suse GNU/Linux
19506 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19507 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19508 (define-key org-mode-map [backtab] 'org-shifttab)
19510 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19511 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19512 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19514 ;; Cursor keys with modifiers
19515 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19516 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19517 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19518 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19520 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19521 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19522 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19523 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19524 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19525 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19527 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19528 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19529 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19530 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19532 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19533 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19534 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19535 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19538 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19539 (dolist (pair org-babel-key-bindings)
19540 (define-key org-babel-map (car pair) (cdr pair)))
19542 ;;; Extra keys for tty access.
19543 ;; We only set them when really needed because otherwise the
19544 ;; menus don't show the simple keys
19546 (when (or org-use-extra-keys (not window-system))
19547 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19548 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19549 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19550 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19551 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19552 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19553 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19554 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19555 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19556 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19557 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19558 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19559 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19560 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19561 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19562 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19563 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19564 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19565 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19566 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19567 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19568 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19569 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19570 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19571 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19572 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19573 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19574 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19576 ;; All the other keys
19577 (org-remap org-mode-map
19578 'self-insert-command 'org-self-insert-command
19579 'delete-char 'org-delete-char
19580 'delete-backward-char 'org-delete-backward-char)
19581 (org-defkey org-mode-map "|" 'org-force-self-insert)
19583 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19584 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19585 (if (boundp 'narrow-map)
19586 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19587 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19588 (if (boundp 'narrow-map)
19589 (org-defkey narrow-map "b" 'org-narrow-to-block)
19590 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19591 (if (boundp 'narrow-map)
19592 (org-defkey narrow-map "e" 'org-narrow-to-element)
19593 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19594 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19595 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19596 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19597 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19598 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19599 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19600 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19601 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19602 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19603 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19604 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19605 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19606 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19607 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19608 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19609 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19610 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19611 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19612 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19613 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19614 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19615 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19616 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19617 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19618 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19619 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19620 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19621 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19622 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19623 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19624 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19625 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19626 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19627 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19628 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19629 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19630 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19631 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19632 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19633 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19634 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19635 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19636 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19637 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19638 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19639 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19640 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19641 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19642 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19643 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19644 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19645 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19646 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19647 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19648 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19649 (org-defkey org-mode-map "\C-c^" 'org-sort)
19650 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19651 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19652 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19653 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19654 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19655 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19656 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19657 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19658 (org-defkey org-mode-map "\C-m" 'org-return)
19659 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19660 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19661 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19662 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19663 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19664 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19665 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19666 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19667 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19668 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19669 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19670 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19671 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19672 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19673 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19674 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19675 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19676 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19677 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19678 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19679 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19680 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19681 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19682 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19683 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19685 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19686 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19687 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19689 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19690 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19691 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19692 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19693 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19694 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19695 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19696 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19697 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19698 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19699 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19700 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19701 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19702 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19703 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19704 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19705 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19706 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19707 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19708 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19709 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19710 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19712 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19713 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19714 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19715 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19716 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19718 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19720 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19722 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19723 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19725 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19728 (defconst org-speed-commands-default
19730 ("Outline Navigation")
19731 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19732 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19733 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19734 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19735 ("F" . org-next-block)
19736 ("B" . org-previous-block)
19737 ("u" . (org-speed-move-safe 'outline-up-heading))
19739 ("g" . (org-refile t))
19740 ("Outline Visibility")
19742 ("C" . org-shifttab)
19743 (" " . org-display-outline-path)
19744 ("s" . org-narrow-to-subtree)
19745 ("=" . org-columns)
19746 ("Outline Structure Editing")
19748 ("D" . org-metadown)
19749 ("r" . org-metaright)
19750 ("l" . org-metaleft)
19751 ("R" . org-shiftmetaright)
19752 ("L" . org-shiftmetaleft)
19753 ("i" . (progn (forward-char 1) (call-interactively
19754 'org-insert-heading-respect-content)))
19757 ("a" . org-archive-subtree-default-with-confirmation)
19758 ("@" . org-mark-subtree)
19759 ("#" . org-toggle-comment)
19761 ("I" . org-clock-in)
19762 ("O" . org-clock-out)
19763 ("Meta Data Editing")
19765 ("," . (org-priority))
19766 ("0" . (org-priority ?\ ))
19767 ("1" . (org-priority ?A))
19768 ("2" . (org-priority ?B))
19769 ("3" . (org-priority ?C))
19770 (":" . org-set-tags-command)
19771 ("e" . org-set-effort)
19772 ("E" . org-inc-effort)
19773 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19774 (org-entry-put (point) "APPT_WARNTIME" m)))
19775 ("Agenda Views etc")
19777 ("/" . org-sparse-tree)
19779 ("o" . org-open-at-point)
19780 ("?" . org-speed-command-help)
19781 ("<" . (org-agenda-set-restriction-lock 'subtree))
19782 (">" . (org-agenda-remove-restriction-lock))
19784 "The default speed commands.")
19786 (defun org-print-speed-command (e)
19787 (if (> (length (car e)) 1)
19792 (princ (make-string (length (car e)) ?-))
19796 (if (symbolp (cdr e))
19797 (princ (symbol-name (cdr e)))
19801 (defun org-speed-command-help ()
19802 "Show the available speed commands."
19804 (if (not org-use-speed-commands)
19805 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19806 (with-output-to-temp-buffer "*Help*"
19807 (princ "User-defined Speed commands\n===========================\n")
19808 (mapc #'org-print-speed-command org-speed-commands-user)
19810 (princ "Built-in Speed commands\n=======================\n")
19811 (mapc #'org-print-speed-command org-speed-commands-default))
19812 (with-current-buffer "*Help*"
19813 (setq truncate-lines t))))
19815 (defun org-speed-move-safe (cmd)
19816 "Execute CMD, but make sure that the cursor always ends up in a headline.
19817 If not, return to the original position and throw an error."
19819 (let ((pos (point)))
19820 (call-interactively cmd)
19821 (unless (and (bolp) (org-at-heading-p))
19823 (error "Boundary reached while executing %s" cmd))))
19825 (defvar org-self-insert-command-undo-counter 0)
19827 (defvar org-table-auto-blank-field) ; defined in org-table.el
19828 (defvar org-speed-command nil)
19830 (defun org-speed-command-activate (keys)
19831 "Hook for activating single-letter speed commands.
19832 `org-speed-commands-default' specifies a minimal command set.
19833 Use `org-speed-commands-user' for further customization."
19834 (when (or (and (bolp) (looking-at org-outline-regexp))
19835 (and (functionp org-use-speed-commands)
19836 (funcall org-use-speed-commands)))
19837 (cdr (assoc keys (append org-speed-commands-user
19838 org-speed-commands-default)))))
19840 (defun org-babel-speed-command-activate (keys)
19841 "Hook for activating single-letter code block commands."
19842 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19843 (cdr (assoc keys org-babel-key-bindings))))
19845 (defcustom org-speed-command-hook
19846 '(org-speed-command-activate org-babel-speed-command-activate)
19847 "Hook for activating speed commands at strategic locations.
19848 Hook functions are called in sequence until a valid handler is
19851 Each hook takes a single argument, a user-pressed command key
19852 which is also a `self-insert-command' from the global map.
19854 Within the hook, examine the cursor position and the command key
19855 and return nil or a valid handler as appropriate. Handler could
19856 be one of an interactive command, a function, or a form.
19858 Set `org-use-speed-commands' to non-nil value to enable this
19859 hook. The default setting is `org-speed-command-activate'."
19860 :group 'org-structure
19864 (defun org-self-insert-command (N)
19865 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19866 If the cursor is in a table looking at whitespace, the whitespace is
19867 overwritten, and the table is not marked as requiring realignment."
19869 (org-check-before-invisible-edit 'insert)
19871 ((and org-use-speed-commands
19872 (let ((kv (this-command-keys-vector)))
19873 (setq org-speed-command
19874 (run-hook-with-args-until-success
19875 'org-speed-command-hook
19876 (make-string 1 (aref kv (1- (length kv))))))))
19878 ((commandp org-speed-command)
19879 (setq this-command org-speed-command)
19880 (call-interactively org-speed-command))
19881 ((functionp org-speed-command)
19882 (funcall org-speed-command))
19883 ((and org-speed-command (listp org-speed-command))
19884 (eval org-speed-command))
19885 (t (let (org-use-speed-commands)
19886 (call-interactively 'org-self-insert-command)))))
19890 (not (org-region-active-p))
19892 ;; Check if we blank the field, and if that triggers align.
19893 (and (featurep 'org-table) org-table-auto-blank-field
19895 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19896 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19897 ;; Got extra space, this field does not determine
19899 (let (org-table-may-need-update) (org-table-blank-field))
19900 ;; No extra space, this field may determine column
19902 (org-table-blank-field)))
19904 (looking-at "[^|\n]* \\( \\)|"))
19905 ;; There is room for insertion without re-aligning the table.
19906 (delete-region (match-beginning 1) (match-end 1))
19907 (self-insert-command N))
19909 (setq org-table-may-need-update t)
19910 (self-insert-command N)
19911 (org-fix-tags-on-the-fly)
19912 (when org-self-insert-cluster-for-undo
19913 (if (not (eq last-command 'org-self-insert-command))
19914 (setq org-self-insert-command-undo-counter 1)
19915 (if (>= org-self-insert-command-undo-counter 20)
19916 (setq org-self-insert-command-undo-counter 1)
19917 (and (> org-self-insert-command-undo-counter 0)
19918 buffer-undo-list (listp buffer-undo-list)
19919 (not (cadr buffer-undo-list)) ; remove nil entry
19920 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19921 (setq org-self-insert-command-undo-counter
19922 (1+ org-self-insert-command-undo-counter))))))))
19924 (defun org-check-before-invisible-edit (kind)
19925 "Check is editing if kind KIND would be dangerous with invisible text around.
19926 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19927 ;; First, try to get out of here as quickly as possible, to reduce overhead
19928 (when (and org-catch-invisible-edits
19929 (or (not (boundp 'visible-mode)) (not visible-mode))
19930 (or (get-char-property (point) 'invisible)
19931 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19932 ;; OK, we need to take a closer look. Do not consider
19933 ;; invisibility obtained through text properties (e.g., link
19934 ;; fontification), as it cannot be toggled.
19935 (let* ((invisible-at-point
19936 (pcase (get-char-property-and-overlay (point) 'invisible)
19937 (`(,_ . ,(and (pred overlayp) o)) o)))
19938 ;; Assume that point cannot land in the middle of an
19939 ;; overlay, or between two overlays.
19940 (invisible-before-point
19941 (and (not invisible-at-point)
19943 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19944 (`(,_ . ,(and (pred overlayp) o)) o))))
19945 (border-and-ok-direction
19947 ;; Check if we are acting predictably before invisible
19949 (and invisible-at-point
19950 (memq kind '(insert delete-backward)))
19951 ;; Check if we are acting predictably after invisible text
19952 ;; This works not well, and I have turned it off. It seems
19953 ;; better to always show and stop after invisible text.
19954 ;; (and (not invisible-at-point) invisible-before-point
19955 ;; (memq kind '(insert delete)))
19957 (when (or invisible-at-point invisible-before-point)
19958 (when (eq org-catch-invisible-edits 'error)
19959 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19960 (if (and org-custom-properties-overlays
19961 (y-or-n-p "Display invisible properties in this buffer? "))
19962 (org-toggle-custom-properties-visibility)
19963 ;; Make the area visible
19965 (when invisible-before-point
19967 (previous-single-char-property-change (point) 'invisible)))
19968 ;; Remove whatever overlay is currently making yet-to-be
19969 ;; edited text invisible. Also remove nested invisibility
19970 ;; related overlays.
19971 (delete-overlay (or invisible-at-point invisible-before-point))
19972 (let ((origin (if invisible-at-point (point) (1- (point)))))
19973 (while (pcase (get-char-property-and-overlay origin 'invisible)
19974 (`(,_ . ,(and (pred overlayp) o))
19978 ((eq org-catch-invisible-edits 'show)
19979 ;; That's it, we do the edit after showing
19981 "Unfolding invisible region around point before editing")
19983 ((and (eq org-catch-invisible-edits 'smart)
19984 border-and-ok-direction)
19985 (message "Unfolding invisible region around point before editing"))
19987 ;; Don't do the edit, make the user repeat it in full visibility
19988 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19990 (defun org-fix-tags-on-the-fly ()
19991 "Align tags in headline at point.
19992 Unlike to `org-set-tags', it ignores region and sorting."
19993 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19994 (org-at-heading-p))
19995 (let ((org-ignore-region t)
19996 (org-tags-sort-function nil))
19997 (org-set-tags nil t))))
19999 (defun org-delete-backward-char (N)
20000 "Like `delete-backward-char', insert whitespace at field end in tables.
20001 When deleting backwards, in tables this function will insert whitespace in
20002 front of the next \"|\" separator, to keep the table aligned. The table will
20003 still be marked for re-alignment if the field did fill the entire column,
20004 because, in this case the deletion might narrow the column."
20007 (org-check-before-invisible-edit 'delete-backward)
20008 (if (and (org-at-table-p)
20010 (not (org-region-active-p))
20011 (string-match "|" (buffer-substring (point-at-bol) (point)))
20012 (looking-at ".*?|"))
20013 (let ((pos (point))
20014 (noalign (looking-at "[^|\n\r]* |"))
20015 (c org-table-may-need-update))
20016 (backward-delete-char N)
20017 (unless overwrite-mode
20018 (skip-chars-forward "^|")
20020 (goto-char (1- pos)))
20021 ;; noalign: if there were two spaces at the end, this field
20022 ;; does not determine the width of the column.
20023 (when noalign (setq org-table-may-need-update c)))
20024 (backward-delete-char N)
20025 (org-fix-tags-on-the-fly))))
20027 (defun org-delete-char (N)
20028 "Like `delete-char', but insert whitespace at field end in tables.
20029 When deleting characters, in tables this function will insert whitespace in
20030 front of the next \"|\" separator, to keep the table aligned. The table will
20031 still be marked for re-alignment if the field did fill the entire column,
20032 because, in this case the deletion might narrow the column."
20035 (org-check-before-invisible-edit 'delete)
20036 (if (and (org-at-table-p)
20038 (not (= (char-after) ?|))
20040 (if (looking-at ".*?|")
20041 (let ((pos (point))
20042 (noalign (looking-at "[^|\n\r]* |"))
20043 (c org-table-may-need-update))
20045 (concat (substring (match-string 0) 1 -1) " |") nil t)
20047 ;; noalign: if there were two spaces at the end, this field
20048 ;; does not determine the width of the column.
20049 (when noalign (setq org-table-may-need-update c)))
20052 (org-fix-tags-on-the-fly))))
20054 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20055 (put 'org-self-insert-command 'delete-selection
20057 (not (run-hook-with-args-until-success
20058 'self-insert-uses-region-functions))))
20059 (put 'orgtbl-self-insert-command 'delete-selection
20061 (not (run-hook-with-args-until-success
20062 'self-insert-uses-region-functions))))
20063 (put 'org-delete-char 'delete-selection 'supersede)
20064 (put 'org-delete-backward-char 'delete-selection 'supersede)
20065 (put 'org-yank 'delete-selection 'yank)
20067 ;; Make `flyspell-mode' delay after some commands
20068 (put 'org-self-insert-command 'flyspell-delayed t)
20069 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20070 (put 'org-delete-char 'flyspell-delayed t)
20071 (put 'org-delete-backward-char 'flyspell-delayed t)
20073 ;; Make pabbrev-mode expand after Org mode commands
20074 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20075 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20077 (defun org-transpose-words ()
20078 "Transpose words for Org.
20079 This uses the `org-mode-transpose-word-syntax-table' syntax
20080 table, which interprets characters in `org-emphasis-alist' as
20081 word constituents."
20083 (with-syntax-table org-mode-transpose-word-syntax-table
20084 (call-interactively 'transpose-words)))
20085 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20087 (defvar org-ctrl-c-ctrl-c-hook nil
20088 "Hook for functions attaching themselves to `C-c C-c'.
20090 This can be used to add additional functionality to the C-c C-c
20091 key which executes context-dependent commands. This hook is run
20092 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20093 run after the last test.
20095 Each function will be called with no arguments. The function
20096 must check if the context is appropriate for it to act. If yes,
20097 it should do its thing and then return a non-nil value. If the
20098 context is wrong, just do nothing and return nil.")
20100 (defvar org-ctrl-c-ctrl-c-final-hook nil
20101 "Hook for functions attaching themselves to `C-c C-c'.
20103 This can be used to add additional functionality to the C-c C-c
20104 key which executes context-dependent commands. This hook is run
20105 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20106 before the first test.
20108 Each function will be called with no arguments. The function
20109 must check if the context is appropriate for it to act. If yes,
20110 it should do its thing and then return a non-nil value. If the
20111 context is wrong, just do nothing and return nil.")
20113 (defvar org-tab-first-hook nil
20114 "Hook for functions to attach themselves to TAB.
20115 See `org-ctrl-c-ctrl-c-hook' for more information.
20116 This hook runs as the first action when TAB is pressed, even before
20117 `org-cycle' messes around with the `outline-regexp' to cater for
20118 inline tasks and plain list item folding.
20119 If any function in this hook returns t, any other actions that
20120 would have been caused by TAB (such as table field motion or visibility
20121 cycling) will not occur.")
20123 (defvar org-tab-after-check-for-table-hook nil
20124 "Hook for functions to attach themselves to TAB.
20125 See `org-ctrl-c-ctrl-c-hook' for more information.
20126 This hook runs after it has been established that the cursor is not in a
20127 table, but before checking if the cursor is in a headline or if global cycling
20129 If any function in this hook returns t, not other actions like visibility
20130 cycling will be done.")
20132 (defvar org-tab-after-check-for-cycling-hook nil
20133 "Hook for functions to attach themselves to TAB.
20134 See `org-ctrl-c-ctrl-c-hook' for more information.
20135 This hook runs after it has been established that not table field motion and
20136 not visibility should be done because of current context. This is probably
20137 the place where a package like yasnippets can hook in.")
20139 (defvar org-tab-before-tab-emulation-hook nil
20140 "Hook for functions to attach themselves to TAB.
20141 See `org-ctrl-c-ctrl-c-hook' for more information.
20142 This hook runs after every other options for TAB have been exhausted, but
20143 before indentation and \t insertion takes place.")
20145 (defvar org-metaleft-hook nil
20146 "Hook for functions attaching themselves to `M-left'.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.")
20148 (defvar org-metaright-hook nil
20149 "Hook for functions attaching themselves to `M-right'.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-metaup-hook nil
20152 "Hook for functions attaching themselves to `M-up'.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-metadown-hook nil
20155 "Hook for functions attaching themselves to `M-down'.
20156 See `org-ctrl-c-ctrl-c-hook' for more information.")
20157 (defvar org-shiftmetaleft-hook nil
20158 "Hook for functions attaching themselves to `M-S-left'.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-shiftmetaright-hook nil
20161 "Hook for functions attaching themselves to `M-S-right'.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-shiftmetaup-hook nil
20164 "Hook for functions attaching themselves to `M-S-up'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-shiftmetadown-hook nil
20167 "Hook for functions attaching themselves to `M-S-down'.
20168 See `org-ctrl-c-ctrl-c-hook' for more information.")
20169 (defvar org-metareturn-hook nil
20170 "Hook for functions attaching themselves to `M-RET'.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-shiftup-hook nil
20173 "Hook for functions attaching themselves to `S-up'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftup-final-hook nil
20176 "Hook for functions attaching themselves to `S-up'.
20177 This one runs after all other options except shift-select have been excluded.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defvar org-shiftdown-hook nil
20180 "Hook for functions attaching themselves to `S-down'.
20181 See `org-ctrl-c-ctrl-c-hook' for more information.")
20182 (defvar org-shiftdown-final-hook nil
20183 "Hook for functions attaching themselves to `S-down'.
20184 This one runs after all other options except shift-select have been excluded.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftleft-hook nil
20187 "Hook for functions attaching themselves to `S-left'.
20188 See `org-ctrl-c-ctrl-c-hook' for more information.")
20189 (defvar org-shiftleft-final-hook nil
20190 "Hook for functions attaching themselves to `S-left'.
20191 This one runs after all other options except shift-select have been excluded.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftright-hook nil
20194 "Hook for functions attaching themselves to `S-right'.
20195 See `org-ctrl-c-ctrl-c-hook' for more information.")
20196 (defvar org-shiftright-final-hook nil
20197 "Hook for functions attaching themselves to `S-right'.
20198 This one runs after all other options except shift-select have been excluded.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20201 (defun org-modifier-cursor-error ()
20202 "Throw an error, a modified cursor command was applied in wrong context."
20203 (user-error "This command is active in special context like tables, headlines or items"))
20205 (defun org-shiftselect-error ()
20206 "Throw an error because Shift-Cursor command was applied in wrong context."
20207 (if (and (boundp 'shift-select-mode) shift-select-mode)
20208 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20209 (user-error "This command works only in special context like headlines or timestamps")))
20211 (defun org-call-for-shift-select (cmd)
20212 (let ((this-command-keys-shift-translated t))
20213 (call-interactively cmd)))
20215 (defun org-shifttab (&optional arg)
20216 "Global visibility cycling or move to previous table field.
20217 Call `org-table-previous-field' within a table.
20218 When ARG is nil, cycle globally through visibility states.
20219 When ARG is a numeric prefix, show contents of this level."
20222 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20224 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20225 (message "Content view to level: %d" arg)
20226 (org-content (prefix-numeric-value arg2))
20227 (org-cycle-show-empty-lines t)
20228 (setq org-cycle-global-status 'overview)))
20229 (t (call-interactively 'org-global-cycle))))
20231 (defun org-shiftmetaleft ()
20232 "Promote subtree or delete table column.
20233 Calls `org-promote-subtree', `org-outdent-item-tree', or
20234 `org-table-delete-column', depending on context. See the
20235 individual commands for more information."
20238 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20239 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20240 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20241 ((if (not (org-region-active-p)) (org-at-item-p)
20242 (save-excursion (goto-char (region-beginning))
20244 (call-interactively 'org-outdent-item-tree))
20245 (t (org-modifier-cursor-error))))
20247 (defun org-shiftmetaright ()
20248 "Demote subtree or insert table column.
20249 Calls `org-demote-subtree', `org-indent-item-tree', or
20250 `org-table-insert-column', depending on context. See the
20251 individual commands for more information."
20254 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20255 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20256 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20257 ((if (not (org-region-active-p)) (org-at-item-p)
20258 (save-excursion (goto-char (region-beginning))
20260 (call-interactively 'org-indent-item-tree))
20261 (t (org-modifier-cursor-error))))
20263 (defun org-shiftmetaup (&optional _arg)
20264 "Drag the line at point up.
20265 In a table, kill the current row.
20266 On a clock timestamp, update the value of the timestamp like `S-<up>'
20267 but also adjust the previous clocked item in the clock history.
20268 Everywhere else, drag the line at point up."
20271 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20272 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20273 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20274 (call-interactively 'org-timestamp-up)))
20275 (t (call-interactively 'org-drag-line-backward))))
20277 (defun org-shiftmetadown (&optional _arg)
20278 "Drag the line at point down.
20279 In a table, insert an empty row at the current line.
20280 On a clock timestamp, update the value of the timestamp like `S-<down>'
20281 but also adjust the previous clocked item in the clock history.
20282 Everywhere else, drag the line at point down."
20285 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20286 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20287 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20288 (call-interactively 'org-timestamp-down)))
20289 (t (call-interactively 'org-drag-line-forward))))
20291 (defsubst org-hidden-tree-error ()
20293 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20295 (defun org-metaleft (&optional _arg)
20296 "Promote heading, list item at point or move table column left.
20298 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20299 depending on context. With no specific context, calls the Emacs
20300 default `backward-word'. See the individual commands for more
20303 This function runs the hook `org-metaleft-hook' as a first step,
20304 and returns at first non-nil value."
20307 ((run-hook-with-args-until-success 'org-metaleft-hook))
20308 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20309 ((org-with-limited-levels
20310 (or (org-at-heading-p)
20311 (and (org-region-active-p)
20313 (goto-char (region-beginning))
20314 (org-at-heading-p)))))
20315 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20316 (call-interactively 'org-do-promote))
20317 ;; At an inline task.
20318 ((org-at-heading-p)
20319 (call-interactively 'org-inlinetask-promote))
20320 ((or (org-at-item-p)
20321 (and (org-region-active-p)
20323 (goto-char (region-beginning))
20325 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20326 (call-interactively 'org-outdent-item))
20327 (t (call-interactively 'backward-word))))
20329 (defun org-metaright (&optional _arg)
20330 "Demote heading, list item at point or move table column right.
20332 In front of a drawer or a block keyword, indent it correctly.
20334 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20335 `org-indent-drawer' or `org-indent-block' depending on context.
20336 With no specific context, calls the Emacs default `forward-word'.
20337 See the individual commands for more information.
20339 This function runs the hook `org-metaright-hook' as a first step,
20340 and returns at first non-nil value."
20343 ((run-hook-with-args-until-success 'org-metaright-hook))
20344 ((org-at-table-p) (call-interactively 'org-table-move-column))
20345 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20346 ((org-at-block-p) (call-interactively 'org-indent-block))
20347 ((org-with-limited-levels
20348 (or (org-at-heading-p)
20349 (and (org-region-active-p)
20351 (goto-char (region-beginning))
20352 (org-at-heading-p)))))
20353 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20354 (call-interactively 'org-do-demote))
20355 ;; At an inline task.
20356 ((org-at-heading-p)
20357 (call-interactively 'org-inlinetask-demote))
20358 ((or (org-at-item-p)
20359 (and (org-region-active-p)
20361 (goto-char (region-beginning))
20363 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20364 (call-interactively 'org-indent-item))
20365 (t (call-interactively 'forward-word))))
20367 (defun org-check-for-hidden (what)
20368 "Check if there are hidden headlines/items in the current visual line.
20369 WHAT can be either `headlines' or `items'. If the current line is
20370 an outline or item heading and it has a folded subtree below it,
20371 this function returns t, nil otherwise."
20373 ((eq what 'headlines) org-outline-regexp-bol)
20374 ((eq what 'items) (org-item-beginning-re))
20375 (t (error "This should not happen"))))
20379 (unless (org-region-active-p)
20380 (setq beg (point-at-bol))
20381 (beginning-of-line 2)
20382 (while (and (not (eobp)) ;; this is like `next-line'
20383 (get-char-property (1- (point)) 'invisible))
20384 (beginning-of-line 2))
20387 (goto-char (point-at-eol))
20388 (setq end (max end (point)))
20389 (while (re-search-forward re end t)
20390 (when (get-char-property (match-beginning 0) 'invisible)
20394 (defun org-metaup (&optional _arg)
20395 "Move subtree up or move table row up.
20396 Calls `org-move-subtree-up' or `org-table-move-row' or
20397 `org-move-item-up', depending on context. See the individual commands
20398 for more information."
20401 ((run-hook-with-args-until-success 'org-metaup-hook))
20402 ((org-region-active-p)
20403 (let* ((a (min (region-beginning) (region-end)))
20404 (b (1- (max (region-beginning) (region-end))))
20405 (c (save-excursion (goto-char a)
20406 (move-beginning-of-line 0)))
20407 (d (save-excursion (goto-char a)
20408 (move-end-of-line 0) (point))))
20409 (transpose-regions a b c d)
20411 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20412 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20413 ((org-at-item-p) (call-interactively 'org-move-item-up))
20414 (t (org-drag-element-backward))))
20416 (defun org-metadown (&optional _arg)
20417 "Move subtree down or move table row down.
20418 Calls `org-move-subtree-down' or `org-table-move-row' or
20419 `org-move-item-down', depending on context. See the individual
20420 commands for more information."
20423 ((run-hook-with-args-until-success 'org-metadown-hook))
20424 ((org-region-active-p)
20425 (let* ((a (min (region-beginning) (region-end)))
20426 (b (max (region-beginning) (region-end)))
20427 (c (save-excursion (goto-char b)
20428 (move-beginning-of-line 1)))
20429 (d (save-excursion (goto-char b)
20430 (move-end-of-line 1) (1+ (point)))))
20431 (transpose-regions a b c d)
20433 ((org-at-table-p) (call-interactively 'org-table-move-row))
20434 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20435 ((org-at-item-p) (call-interactively 'org-move-item-down))
20436 (t (org-drag-element-forward))))
20438 (defun org-shiftup (&optional arg)
20439 "Increase item in timestamp or increase priority of current headline.
20440 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20441 depending on context. See the individual commands for more information."
20444 ((run-hook-with-args-until-success 'org-shiftup-hook))
20445 ((and org-support-shift-select (org-region-active-p))
20446 (org-call-for-shift-select 'previous-line))
20447 ((org-at-timestamp-p 'lax)
20448 (call-interactively (if org-edit-timestamp-down-means-later
20449 'org-timestamp-down 'org-timestamp-up)))
20450 ((and (not (eq org-support-shift-select 'always))
20451 org-enable-priority-commands
20452 (org-at-heading-p))
20453 (call-interactively 'org-priority-up))
20454 ((and (not org-support-shift-select) (org-at-item-p))
20455 (call-interactively 'org-previous-item))
20456 ((org-clocktable-try-shift 'up arg))
20457 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20458 (org-support-shift-select
20459 (org-call-for-shift-select 'previous-line))
20460 (t (org-shiftselect-error))))
20462 (defun org-shiftdown (&optional arg)
20463 "Decrease item in timestamp or decrease priority of current headline.
20464 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20465 depending on context. See the individual commands for more information."
20468 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20469 ((and org-support-shift-select (org-region-active-p))
20470 (org-call-for-shift-select 'next-line))
20471 ((org-at-timestamp-p 'lax)
20472 (call-interactively (if org-edit-timestamp-down-means-later
20473 'org-timestamp-up 'org-timestamp-down)))
20474 ((and (not (eq org-support-shift-select 'always))
20475 org-enable-priority-commands
20476 (org-at-heading-p))
20477 (call-interactively 'org-priority-down))
20478 ((and (not org-support-shift-select) (org-at-item-p))
20479 (call-interactively 'org-next-item))
20480 ((org-clocktable-try-shift 'down arg))
20481 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20482 (org-support-shift-select
20483 (org-call-for-shift-select 'next-line))
20484 (t (org-shiftselect-error))))
20486 (defun org-shiftright (&optional arg)
20487 "Cycle the thing at point or in the current line, depending on context.
20488 Depending on context, this does one of the following:
20490 - switch a timestamp at point one day into the future
20491 - on a headline, switch to the next TODO keyword.
20492 - on an item, switch entire list to the next bullet type
20493 - on a property line, switch to the next allowed value
20494 - on a clocktable definition line, move time block into the future"
20497 ((run-hook-with-args-until-success 'org-shiftright-hook))
20498 ((and org-support-shift-select (org-region-active-p))
20499 (org-call-for-shift-select 'forward-char))
20500 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20501 ((and (not (eq org-support-shift-select 'always))
20502 (org-at-heading-p))
20503 (let ((org-inhibit-logging
20504 (not org-treat-S-cursor-todo-selection-as-state-change))
20505 (org-inhibit-blocking
20506 (not org-treat-S-cursor-todo-selection-as-state-change)))
20507 (org-call-with-arg 'org-todo 'right)))
20508 ((or (and org-support-shift-select
20509 (not (eq org-support-shift-select 'always))
20510 (org-at-item-bullet-p))
20511 (and (not org-support-shift-select) (org-at-item-p)))
20512 (org-call-with-arg 'org-cycle-list-bullet nil))
20513 ((and (not (eq org-support-shift-select 'always))
20514 (org-at-property-p))
20515 (call-interactively 'org-property-next-allowed-value))
20516 ((org-clocktable-try-shift 'right arg))
20517 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20518 (org-support-shift-select
20519 (org-call-for-shift-select 'forward-char))
20520 (t (org-shiftselect-error))))
20522 (defun org-shiftleft (&optional arg)
20523 "Cycle the thing at point or in the current line, depending on context.
20524 Depending on context, this does one of the following:
20526 - switch a timestamp at point one day into the past
20527 - on a headline, switch to the previous TODO keyword.
20528 - on an item, switch entire list to the previous bullet type
20529 - on a property line, switch to the previous allowed value
20530 - on a clocktable definition line, move time block into the past"
20533 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20534 ((and org-support-shift-select (org-region-active-p))
20535 (org-call-for-shift-select 'backward-char))
20536 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20537 ((and (not (eq org-support-shift-select 'always))
20538 (org-at-heading-p))
20539 (let ((org-inhibit-logging
20540 (not org-treat-S-cursor-todo-selection-as-state-change))
20541 (org-inhibit-blocking
20542 (not org-treat-S-cursor-todo-selection-as-state-change)))
20543 (org-call-with-arg 'org-todo 'left)))
20544 ((or (and org-support-shift-select
20545 (not (eq org-support-shift-select 'always))
20546 (org-at-item-bullet-p))
20547 (and (not org-support-shift-select) (org-at-item-p)))
20548 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20549 ((and (not (eq org-support-shift-select 'always))
20550 (org-at-property-p))
20551 (call-interactively 'org-property-previous-allowed-value))
20552 ((org-clocktable-try-shift 'left arg))
20553 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20554 (org-support-shift-select
20555 (org-call-for-shift-select 'backward-char))
20556 (t (org-shiftselect-error))))
20558 (defun org-shiftcontrolright ()
20559 "Switch to next TODO set."
20562 ((and org-support-shift-select (org-region-active-p))
20563 (org-call-for-shift-select 'forward-word))
20564 ((and (not (eq org-support-shift-select 'always))
20565 (org-at-heading-p))
20566 (org-call-with-arg 'org-todo 'nextset))
20567 (org-support-shift-select
20568 (org-call-for-shift-select 'forward-word))
20569 (t (org-shiftselect-error))))
20571 (defun org-shiftcontrolleft ()
20572 "Switch to previous TODO set."
20575 ((and org-support-shift-select (org-region-active-p))
20576 (org-call-for-shift-select 'backward-word))
20577 ((and (not (eq org-support-shift-select 'always))
20578 (org-at-heading-p))
20579 (org-call-with-arg 'org-todo 'previousset))
20580 (org-support-shift-select
20581 (org-call-for-shift-select 'backward-word))
20582 (t (org-shiftselect-error))))
20584 (defun org-shiftcontrolup (&optional n)
20585 "Change timestamps synchronously up in CLOCK log lines.
20586 Optional argument N tells to change by that many units."
20588 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20589 (let (org-support-shift-select)
20590 (org-clock-timestamps-up n))
20591 (user-error "Not at a clock log")))
20593 (defun org-shiftcontroldown (&optional n)
20594 "Change timestamps synchronously down in CLOCK log lines.
20595 Optional argument N tells to change by that many units."
20597 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20598 (let (org-support-shift-select)
20599 (org-clock-timestamps-down n))
20600 (user-error "Not at a clock log")))
20602 (defun org-increase-number-at-point (&optional inc)
20603 "Increment the number at point.
20604 With an optional prefix numeric argument INC, increment using
20605 this numeric value."
20607 (if (not (number-at-point))
20608 (user-error "Not on a number")
20609 (unless inc (setq inc 1))
20610 (let ((pos (point))
20611 (beg (skip-chars-backward "-+^/*0-9eE."))
20612 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20613 (setq nap (buffer-substring-no-properties
20614 (+ pos beg) (+ pos beg end)))
20615 (delete-region (+ pos beg) (+ pos beg end))
20616 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20617 (when (org-at-table-p)
20619 (org-table-end-of-field 1))))
20621 (defun org-decrease-number-at-point (&optional inc)
20622 "Decrement the number at point.
20623 With an optional prefix numeric argument INC, decrement using
20624 this numeric value."
20626 (org-increase-number-at-point (- (or inc 1))))
20628 (defun org-ctrl-c-ret ()
20629 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20632 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20633 (t (call-interactively 'org-insert-heading))))
20635 (defun org-find-visible ()
20637 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20638 (get-char-property s 'invisible)))
20640 (defun org-find-invisible ()
20642 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20643 (not (get-char-property s 'invisible))))
20646 (defun org-copy-visible (beg end)
20647 "Copy the visible parts of the region."
20650 (while (/= beg end)
20651 (when (get-char-property beg 'invisible)
20652 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20653 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20654 (setq result (concat result (buffer-substring beg next)))
20656 (kill-new result)))
20658 (defun org-copy-special ()
20659 "Copy region in table or copy current subtree.
20660 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20661 context. See the individual commands for more information."
20663 (call-interactively
20664 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20666 (defun org-cut-special ()
20667 "Cut region in table or cut current subtree.
20668 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20669 context. See the individual commands for more information."
20671 (call-interactively
20672 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20674 (defun org-paste-special (arg)
20675 "Paste rectangular region into table, or past subtree relative to level.
20676 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20677 See the individual commands for more information."
20679 (if (org-at-table-p)
20680 (org-table-paste-rectangle)
20681 (org-paste-subtree arg)))
20683 (defun org-edit-special (&optional arg)
20684 "Call a special editor for the element at point.
20685 When at a table, call the formula editor with `org-table-edit-formulas'.
20686 When in a source code block, call `org-edit-src-code'.
20687 When in a fixed-width region, call `org-edit-fixed-width-region'.
20688 When in an export block, call `org-edit-export-block'.
20689 When in a LaTeX environment, call `org-edit-latex-environment'.
20690 When at an #+INCLUDE keyword, visit the included file.
20691 When at a footnote reference, call `org-edit-footnote-reference'
20692 On a link, call `ffap' to visit the link at point.
20693 Otherwise, return a user error."
20695 (let ((element (org-element-at-point)))
20696 (barf-if-buffer-read-only)
20697 (pcase (org-element-type element)
20699 (if (not arg) (org-edit-src-code)
20700 (let* ((info (org-babel-get-src-block-info))
20701 (lang (nth 0 info))
20702 (params (nth 2 info))
20703 (session (cdr (assq :session params))))
20704 (if (not session) (org-edit-src-code)
20705 ;; At a src-block with a session and function called with
20706 ;; an ARG: switch to the buffer related to the inferior
20709 (funcall (intern (concat "org-babel-prep-session:" lang))
20710 session params))))))
20712 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20713 (org-open-link-from-string
20716 (let ((value (org-element-property :value element)))
20717 (cond ((org-file-url-p value)
20718 (user-error "The file is specified as a URL, cannot be edited"))
20719 ((not (org-string-nw-p value))
20720 (user-error "No file to edit"))
20721 ((string-match "\\`\"\\(.*?\\)\"" value)
20722 (match-string 1 value))
20723 ((string-match "\\`[^ \t\"]\\S-*" value)
20724 (match-string 0 value))
20725 (t (user-error "No valid file specified")))))))
20726 (user-error "No special environment to edit here")))
20728 (if (eq (org-element-property :type element) 'table.el)
20729 (org-edit-table.el)
20730 (call-interactively 'org-table-edit-formulas)))
20731 ;; Only Org tables contain `table-row' type elements.
20732 (`table-row (call-interactively 'org-table-edit-formulas))
20733 (`example-block (org-edit-src-code))
20734 (`export-block (org-edit-export-block))
20735 (`fixed-width (org-edit-fixed-width-region))
20736 (`latex-environment (org-edit-latex-environment))
20738 ;; No notable element at point. Though, we may be at a link or
20739 ;; a footnote reference, which are objects. Thus, scan deeper.
20740 (let ((context (org-element-context element)))
20741 (pcase (org-element-type context)
20742 (`footnote-reference (org-edit-footnote-reference))
20743 (`inline-src-block (org-edit-inline-src-code))
20744 (`link (call-interactively #'ffap))
20745 (_ (user-error "No special environment to edit here"))))))))
20747 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20748 (defun org-ctrl-c-ctrl-c (&optional arg)
20749 "Set tags in headline, or update according to changed information at point.
20751 This command does many different things, depending on context:
20753 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20754 this is what we do.
20756 - If the cursor is on a statistics cookie, update it.
20758 - If the cursor is in a headline, prompt for tags and insert them
20759 into the current line, aligned to `org-tags-column'. When called
20760 with prefix arg, realign all tags in the current buffer.
20762 - If the cursor is in one of the special #+KEYWORD lines, this
20763 triggers scanning the buffer for these lines and updating the
20766 - If the cursor is inside a table, realign the table. This command
20767 works even if the automatic table editor has been turned off.
20769 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20772 - If the cursor is at a footnote reference or definition, jump to
20773 the corresponding definition or references, respectively.
20775 - If the cursor is a the beginning of a dynamic block, update it.
20777 - If the current buffer is a capture buffer, close note and file it.
20779 - If the cursor is on a <<<target>>>, update radio targets and
20780 corresponding links in this buffer.
20782 - If the cursor is on a numbered item in a plain list, renumber the
20785 - If the cursor is on a checkbox, toggle it.
20787 - If the cursor is on a code block, evaluate it. The variable
20788 `org-confirm-babel-evaluate' can be used to control prompting
20789 before code block evaluation, by default every code block
20790 evaluation requires confirmation. Code block evaluation can be
20791 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20794 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20795 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20796 (org-remove-occur-highlights)
20797 (message "Temporary highlights/overlays removed from current buffer"))
20798 ((and (local-variable-p 'org-finish-function)
20799 (fboundp org-finish-function))
20800 (funcall org-finish-function))
20801 ((org-babel-hash-at-point))
20802 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20805 (org-element-lineage
20806 (org-element-context)
20807 ;; Limit to supported contexts.
20808 '(babel-call clock dynamic-block footnote-definition
20809 footnote-reference inline-babel-call inline-src-block
20810 inlinetask item keyword node-property paragraph
20811 plain-list planning property-drawer radio-target
20812 src-block statistics-cookie table table-cell table-row
20815 (type (org-element-type context)))
20816 ;; For convenience: at the first line of a paragraph on the same
20817 ;; line as an item, apply function on that item instead.
20818 (when (eq type 'paragraph)
20819 (let ((parent (org-element-property :parent context)))
20820 (when (and (eq (org-element-type parent) 'item)
20821 (= (line-beginning-position)
20822 (org-element-property :begin parent)))
20823 (setq context parent)
20824 (setq type 'item))))
20825 ;; Act according to type of element or object at point.
20827 ;; Do nothing on a blank line, except if it is contained in
20828 ;; a src block. Hence, we first check if point is in such
20829 ;; a block and then if it is at a blank line.
20831 ((or `inline-src-block `src-block)
20832 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20833 (org-babel-eval-wipe-error-buffer)
20834 (org-babel-execute-src-block
20835 current-prefix-arg (org-babel-get-src-block-info nil context))))
20836 ((guard (org-match-line "[ \t]*$"))
20837 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20839 (substitute-command-keys
20840 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20841 ((or `babel-call `inline-babel-call)
20842 (let ((info (org-babel-lob-get-info context)))
20843 (when info (org-babel-execute-src-block nil info))))
20844 (`clock (org-clock-update-time-maybe))
20847 (goto-char (org-element-property :post-affiliated context))
20848 (org-update-dblock)))
20849 (`footnote-definition
20850 (goto-char (org-element-property :post-affiliated context))
20851 (call-interactively 'org-footnote-action))
20852 (`footnote-reference (call-interactively #'org-footnote-action))
20853 ((or `headline `inlinetask)
20854 (save-excursion (goto-char (org-element-property :begin context))
20855 (call-interactively #'org-set-tags)))
20857 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20858 ;; unconditionally, whereas `C-u' will toggle its presence.
20859 ;; Without a universal argument, if the item has a checkbox,
20860 ;; toggle it. Otherwise repair the list.
20861 (let* ((box (org-element-property :checkbox context))
20862 (struct (org-element-property :structure context))
20863 (old-struct (copy-tree struct))
20864 (parents (org-list-parents-alist struct))
20865 (prevs (org-list-prevs-alist struct))
20866 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20867 (org-list-set-checkbox
20868 (org-element-property :begin context) struct
20869 (cond ((equal arg '(16)) "[-]")
20870 ((and (not box) (equal arg '(4))) "[ ]")
20871 ((or (not box) (equal arg '(4))) nil)
20872 ((eq box 'on) "[ ]")
20874 ;; Mimic `org-list-write-struct' but with grabbing a return
20875 ;; value from `org-list-struct-fix-box'.
20876 (org-list-struct-fix-ind struct parents 2)
20877 (org-list-struct-fix-item-end struct)
20878 (org-list-struct-fix-bul struct prevs)
20879 (org-list-struct-fix-ind struct parents)
20881 (org-list-struct-fix-box struct parents prevs orderedp)))
20882 (if (and box (equal struct old-struct))
20883 (if (equal arg '(16))
20884 (message "Checkboxes already reset")
20885 (user-error "Cannot toggle this checkbox: %s"
20887 "all subitems checked"
20888 "unchecked subitems")))
20889 (org-list-struct-apply-struct struct old-struct)
20890 (org-update-checkbox-count-maybe))
20892 (message "Checkboxes were removed due to empty box at line %d"
20893 (org-current-line block-item))))))
20895 (let ((org-inhibit-startup-visibility-stuff t)
20896 (org-startup-align-all-tables nil))
20897 (when (boundp 'org-table-coordinate-overlays)
20898 (mapc #'delete-overlay org-table-coordinate-overlays)
20899 (setq org-table-coordinate-overlays nil))
20900 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20901 (message "Local setup has been refreshed"))
20903 ;; At a plain list, with a double C-u argument, set
20904 ;; checkboxes of each item to "[-]", whereas a single one
20905 ;; will toggle their presence according to the state of the
20906 ;; first item in the list. Without an argument, repair the
20908 (let* ((begin (org-element-property :contents-begin context))
20909 (beginm (move-marker (make-marker) begin))
20910 (struct (org-element-property :structure context))
20911 (old-struct (copy-tree struct))
20912 (first-box (save-excursion
20914 (looking-at org-list-full-item-re)
20915 (match-string-no-properties 3)))
20916 (new-box (cond ((equal arg '(16)) "[-]")
20917 ((equal arg '(4)) (unless first-box "[ ]"))
20918 ((equal first-box "[X]") "[ ]")
20923 (org-list-get-all-items
20924 begin struct (org-list-prevs-alist struct)))
20925 (org-list-set-checkbox pos struct new-box)))
20926 ((and first-box (eq (point) begin))
20927 ;; For convenience, when point is at bol on the first
20928 ;; item of the list and no argument is provided, simply
20929 ;; toggle checkbox of that item, if any.
20930 (org-list-set-checkbox begin struct new-box)))
20931 (org-list-write-struct
20932 struct (org-list-parents-alist struct) old-struct)
20933 (org-update-checkbox-count-maybe)
20934 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20935 ((or `property-drawer `node-property)
20936 (call-interactively #'org-property-action))
20938 (call-interactively #'org-update-radio-target-regexp))
20939 (`statistics-cookie
20940 (call-interactively #'org-update-statistics-cookies))
20941 ((or `table `table-cell `table-row)
20942 ;; At a table, recalculate every field and align it. Also
20943 ;; send the table if necessary. If the table has
20944 ;; a `table.el' type, just give up. At a table row or cell,
20945 ;; maybe recalculate line but always align table.
20946 (if (eq (org-element-property :type context) 'table.el)
20947 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20948 Use `\\[org-edit-special]' to edit table.el tables"))
20949 (if (or (eq type 'table)
20950 ;; Check if point is at a TBLFM line.
20951 (and (eq type 'table-row)
20952 (= (point) (org-element-property :end context))))
20954 (if (org-at-TBLFM-p)
20955 (progn (require 'org-table)
20956 (org-table-calc-current-TBLFM))
20957 (goto-char (org-element-property :contents-begin context))
20958 (org-call-with-arg 'org-table-recalculate (or arg t))
20959 (orgtbl-send-table 'maybe)))
20960 (org-table-maybe-eval-formula)
20961 (cond (arg (call-interactively #'org-table-recalculate))
20962 ((org-table-maybe-recalculate-line))
20963 (t (org-table-align))))))
20964 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20965 (org-timestamp-change 0 'day))
20966 ((and `nil (guard (org-at-heading-p)))
20967 ;; When point is on an unsupported object type, we can miss
20968 ;; the fact that it also is at a heading. Handle it here.
20969 (call-interactively #'org-set-tags))
20971 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20974 (substitute-command-keys
20975 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20977 (defun org-mode-restart ()
20979 (let ((indent-status (bound-and-true-p org-indent-mode)))
20980 (funcall major-mode)
20981 (hack-local-variables)
20982 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20983 (org-indent-mode -1))
20984 (org-reset-file-cache))
20985 (message "%s restarted" major-mode))
20987 (defun org-kill-note-or-show-branches ()
20988 "Abort storing current note, or call `outline-show-branches'."
20990 (if (not org-finish-function)
20992 (outline-hide-subtree)
20993 (call-interactively 'outline-show-branches))
20994 (let ((org-note-abort t))
20995 (funcall org-finish-function))))
20997 (defun org-delete-indentation (&optional arg)
20998 "Join current line to previous and fix whitespace at join.
21000 If previous line is a headline add to headline title. Otherwise
21001 the function calls `delete-indentation'.
21003 With a non-nil optional argument, join it to the following one."
21005 (if (save-excursion
21006 (beginning-of-line (if arg 1 0))
21007 (let ((case-fold-search nil))
21008 (looking-at org-complex-heading-regexp)))
21010 (let ((tags-column (when (match-beginning 5)
21011 (save-excursion (goto-char (match-beginning 5))
21012 (current-column))))
21013 (string (concat " " (progn (when arg (forward-line 1))
21014 (org-trim (delete-and-extract-region
21015 (line-beginning-position)
21016 (line-end-position)))))))
21017 (unless (bobp) (delete-region (point) (1- (point))))
21018 (goto-char (or (match-end 4)
21019 (match-beginning 5)
21021 (skip-chars-backward " \t")
21022 (save-excursion (insert string))
21023 ;; Adjust alignment of tags.
21025 ((not tags-column)) ;no tags
21026 (org-auto-align-tags (org-set-tags nil t))
21027 (t (org--align-tags-here tags-column)))) ;preserve tags column
21028 (delete-indentation arg)))
21030 (defun org-open-line (n)
21031 "Insert a new row in tables, call `open-line' elsewhere.
21032 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21033 As a special case, when a document starts with a table, allow to
21034 call `open-line' on the very first character."
21036 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21037 (org-table-insert-row)
21040 (defun org-return (&optional indent)
21041 "Goto next table row or insert a newline.
21043 Calls `org-table-next-row' or `newline', depending on context.
21045 When optional INDENT argument is non-nil, call
21046 `newline-and-indent' instead of `newline'.
21048 When `org-return-follows-link' is non-nil and point is on
21049 a timestamp or a link, call `org-open-at-point'. However, it
21050 will not happen if point is in a table or on a \"dead\"
21051 object (e.g., within a comment). In these case, you need to use
21052 `org-open-at-point' directly."
21054 (let ((context (if org-return-follows-link (org-element-context)
21055 (org-element-at-point))))
21057 ;; In a table, call `org-table-next-row'. However, before first
21058 ;; column or after last one, split the table.
21059 ((or (and (eq (org-element-type context) 'table)
21060 (>= (point) (org-element-property :contents-begin context))
21061 (< (point) (org-element-property :contents-end context)))
21062 (org-element-lineage context '(table-row table-cell) t))
21063 (if (or (looking-at-p "[ \t]*$")
21064 (save-excursion (skip-chars-backward " \t") (bolp)))
21066 (org-table-justify-field-maybe)
21067 (call-interactively #'org-table-next-row)))
21068 ;; On a link or a timestamp, call `org-open-at-point' if
21069 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21070 ;; locations, e.g., in a comment, as `org-open-at-point'.
21071 ((and org-return-follows-link
21072 (or (org-in-regexp org-ts-regexp-both nil t)
21073 (org-in-regexp org-tsr-regexp-both nil t)
21074 (org-in-regexp org-any-link-re nil t)))
21075 (call-interactively #'org-open-at-point))
21076 ;; Insert newline in heading, but preserve tags.
21078 (save-excursion (beginning-of-line)
21079 (let ((case-fold-search nil))
21080 (looking-at org-complex-heading-regexp))))
21081 ;; At headline. Split line. However, if point is on keyword,
21082 ;; priority cookie or tags, do not break any of them: add
21083 ;; a newline after the headline instead.
21084 (let ((tags-column (and (match-beginning 5)
21085 (save-excursion (goto-char (match-beginning 5))
21086 (current-column))))
21088 (when (and (match-end 4) (org-point-in-group (point) 4))
21089 (delete-and-extract-region (point) (match-end 4)))))
21090 ;; Adjust tag alignment.
21092 ((not (and tags-column string)))
21093 (org-auto-align-tags (org-set-tags nil t))
21094 (t (org--align-tags-here tags-column))) ;preserve tags column
21097 (if indent (newline-and-indent) (newline))
21098 (when string (save-excursion (insert (org-trim string))))))
21099 ;; In a list, make sure indenting keeps trailing text within.
21102 (org-element-lineage context '(item)))
21103 (let ((trailing-data
21104 (delete-and-extract-region (point) (line-end-position))))
21105 (newline-and-indent)
21106 (save-excursion (insert trailing-data))))
21107 (t (if indent (newline-and-indent) (newline))))))
21109 (defun org-return-indent ()
21110 "Goto next table row or insert a newline and indent.
21111 Calls `org-table-next-row' or `newline-and-indent', depending on
21112 context. See the individual commands for more information."
21116 (defun org-ctrl-c-star ()
21117 "Compute table, or change heading status of lines.
21118 Calls `org-table-recalculate' or `org-toggle-heading',
21119 depending on context."
21123 (call-interactively 'org-table-recalculate))
21125 ;; Convert all lines in region to list items
21126 (call-interactively 'org-toggle-heading))))
21128 (defun org-ctrl-c-minus ()
21129 "Insert separator line in table or modify bullet status of line.
21130 Also turns a plain line or a region of lines into list items.
21131 Calls `org-table-insert-hline', `org-toggle-item', or
21132 `org-cycle-list-bullet', depending on context."
21136 (call-interactively 'org-table-insert-hline))
21137 ((org-region-active-p)
21138 (call-interactively 'org-toggle-item))
21140 (call-interactively 'org-cycle-list-bullet))
21142 (call-interactively 'org-toggle-item))))
21144 (defun org-toggle-heading (&optional nstars)
21145 "Convert headings to normal text, or items or text to headings.
21146 If there is no active region, only convert the current line.
21148 With a `\\[universal-argument]' prefix, convert the whole list at
21149 point into heading.
21153 - If the first non blank line is a headline, remove the stars
21154 from all headlines in the region.
21156 - If it is a normal line, turn each and every normal line (i.e.,
21157 not an heading or an item) in the region into headings. If you
21158 want to convert only the first line of this region, use one
21159 universal prefix argument.
21161 - If it is a plain list item, turn all plain list items into headings.
21163 When converting a line into a heading, the number of stars is chosen
21164 such that the lines become children of the current entry. However,
21165 when a numeric prefix argument is given, its value determines the
21166 number of stars to add."
21170 ;; Return beginning of first non-blank line, starting from
21175 (while (org-at-comment-p) (forward-line))
21176 (skip-chars-forward " \r\t\n")
21179 ;; Determine boundaries of changes. If a universal prefix has
21180 ;; been given, put the list in a region. If region ends at a bol,
21181 ;; do not consider the last line to be in the region.
21183 (when (and current-prefix-arg (org-at-item-p))
21184 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21185 (org-mark-element))
21187 (if (org-region-active-p)
21188 (setq beg (funcall skip-blanks (region-beginning))
21189 end (copy-marker (save-excursion
21190 (goto-char (region-end))
21191 (if (bolp) (point) (point-at-eol)))))
21192 (setq beg (funcall skip-blanks (point-at-bol))
21193 end (copy-marker (point-at-eol))))
21194 ;; Ensure inline tasks don't count as headings.
21195 (org-with-limited-levels
21199 ;; Case 1. Started at an heading: de-star headings.
21200 ((org-at-heading-p)
21201 (while (< (point) end)
21202 (when (org-at-heading-p t)
21203 (looking-at org-outline-regexp) (replace-match "")
21206 ;; Case 2. Started at an item: change items into headlines.
21207 ;; One star will be added by `org-list-to-subtree'.
21209 (while (< (point) end)
21210 (when (org-at-item-p)
21211 ;; Pay attention to cases when region ends before list.
21212 (let* ((struct (org-list-struct))
21214 (min (org-list-get-bottom-point struct) (1+ end))))
21216 (narrow-to-region (point) list-end)
21217 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21220 ;; Case 3. Started at normal text: make every line an heading,
21221 ;; skipping headlines and items.
21224 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21226 (cond (nstars "") ; stars from prefix only
21227 ((equal stars "") "*") ; before first heading
21228 (org-odd-levels-only "**") ; inside heading, odd
21229 (t "*"))) ; inside heading, oddeven
21230 (rpl (concat stars add-stars " "))
21231 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21232 (while (< (point) (if (equal nstars '(4)) lend end))
21233 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21234 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21235 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21236 (forward-line)))))))
21237 (unless toggled (message "Cannot toggle heading from here"))))
21239 (defun org-meta-return (&optional arg)
21240 "Insert a new heading or wrap a region in a table.
21241 Calls `org-insert-heading', `org-insert-item' or
21242 `org-table-wrap-region', depending on context. When called with
21243 an argument, unconditionally call `org-insert-heading'."
21245 (org-check-before-invisible-edit 'insert)
21246 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21247 (call-interactively (cond (arg #'org-insert-heading)
21248 ((org-at-table-p) #'org-table-wrap-region)
21249 ((org-in-item-p) #'org-insert-item)
21250 (t #'org-insert-heading)))))
21254 (defsubst org-in-subtree-not-table-p ()
21255 "Are we in a subtree and not in a table?"
21256 (and (not (org-before-first-heading-p))
21257 (not (org-at-table-p))))
21259 ;; Define the Org mode menus
21260 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21262 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21263 ["Next Field" org-cycle (org-at-table-p)]
21264 ["Previous Field" org-shifttab (org-at-table-p)]
21265 ["Next Row" org-return (org-at-table-p)]
21267 ["Blank Field" org-table-blank-field (org-at-table-p)]
21268 ["Edit Field" org-table-edit-field (org-at-table-p)]
21269 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21272 ["Move Column Left" org-metaleft (org-at-table-p)]
21273 ["Move Column Right" org-metaright (org-at-table-p)]
21274 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21275 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21277 ["Move Row Up" org-metaup (org-at-table-p)]
21278 ["Move Row Down" org-metadown (org-at-table-p)]
21279 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21280 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21281 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21283 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21285 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21286 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21287 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21288 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21291 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21292 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21293 ["Edit Formulas" org-edit-special (org-at-table-p)]
21295 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21296 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21297 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21299 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21301 ["Sum Column/Rectangle" org-table-sum
21302 (or (org-at-table-p) (org-region-active-p))]
21303 ["Which Column?" org-table-current-column (org-at-table-p)])
21305 org-table-toggle-formula-debugger
21306 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21307 ["Show Col/Row Numbers"
21308 org-table-toggle-coordinate-overlays
21310 :selected (bound-and-true-p org-table-overlay-coordinates)]
21312 ["Create" org-table-create (not (org-at-table-p))]
21313 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21314 ["Import from File" org-table-import (not (org-at-table-p))]
21315 ["Export to File" org-table-export (org-at-table-p)]
21317 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21320 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21321 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21323 (easy-menu-define org-org-menu org-mode-map "Org menu"
21326 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21327 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21328 ["Sparse Tree..." org-sparse-tree t]
21329 ["Reveal Context" org-reveal t]
21330 ["Show All" outline-show-all t]
21332 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21334 ["New Heading" org-insert-heading t]
21335 ("Navigate Headings"
21336 ["Up" outline-up-heading t]
21337 ["Next" outline-next-visible-heading t]
21338 ["Previous" outline-previous-visible-heading t]
21339 ["Next Same Level" outline-forward-same-level t]
21340 ["Previous Same Level" outline-backward-same-level t]
21342 ["Jump" org-goto t])
21344 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21346 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21347 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21349 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21350 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21351 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21353 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21355 ["Copy visible text" org-copy-visible t]
21357 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21358 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21359 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21360 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21362 ["Sort Region/Children" org-sort t]
21364 ["Convert to odd levels" org-convert-to-odd-levels t]
21365 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21367 ["Emphasis..." org-emphasize t]
21368 ["Edit Source Example" org-edit-special t]
21370 ["Footnote new/jump" org-footnote-action t]
21371 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21373 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21375 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21376 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21377 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21381 ["Store Link (Global)" org-store-link t]
21382 ["Find existing link to here" org-occur-link-in-agenda-files t]
21383 ["Insert Link" org-insert-link t]
21384 ["Follow Link" org-open-at-point t]
21386 ["Next link" org-next-link t]
21387 ["Previous link" org-previous-link t]
21389 ["Descriptive Links"
21390 org-toggle-link-display
21392 :selected org-descriptive-links
21395 org-toggle-link-display
21397 :selected (not org-descriptive-links)])
21400 ["TODO/DONE/-" org-todo t]
21402 ["Next keyword" org-shiftright (org-at-heading-p)]
21403 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21404 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21405 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21406 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21407 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21408 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21410 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21411 :selected org-enforce-todo-dependencies :style toggle :active t]
21412 "Settings for tree at point"
21413 ["Do Children sequentially" org-toggle-ordered-property :style radio
21414 :selected (org-entry-get nil "ORDERED")
21415 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21416 ["Do Children parallel" org-toggle-ordered-property :style radio
21417 :selected (not (org-entry-get nil "ORDERED"))
21418 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21420 ["Set Priority" org-priority t]
21421 ["Priority Up" org-shiftup t]
21422 ["Priority Down" org-shiftdown t]
21424 ["Get news from all feeds" org-feed-update-all t]
21425 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21426 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21427 ("TAGS and Properties"
21428 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21429 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21431 ["Set property" org-set-property (not (org-before-first-heading-p))]
21432 ["Column view of properties" org-columns t]
21433 ["Insert Column View DBlock" org-columns-insert-dblock t])
21434 ("Dates and Scheduling"
21435 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21436 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21438 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21439 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21440 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21441 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21442 ["Compute Time Range" org-evaluate-time-range t]
21443 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21444 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21446 ["Custom time format" org-toggle-time-stamp-overlays
21447 :style radio :selected org-display-custom-times]
21449 ["Goto Calendar" org-goto-calendar t]
21450 ["Date from Calendar" org-date-from-calendar t]
21452 ["Start/Restart Timer" org-timer-start t]
21453 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21454 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21455 ["Insert Timer String" org-timer t]
21456 ["Insert Timer Item" org-timer-item t])
21458 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21459 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21460 ["Clock out" org-clock-out t]
21461 ["Clock cancel" org-clock-cancel t]
21463 ["Mark as default task" org-clock-mark-default-task t]
21464 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21465 ["Goto running clock" org-clock-goto t]
21467 ["Display times" org-clock-display t]
21468 ["Create clock table" org-clock-report t]
21470 ["Record DONE time"
21471 (progn (setq org-log-done (not org-log-done))
21472 (message "Switching to %s will %s record a timestamp"
21473 (car org-done-keywords)
21474 (if org-log-done "automatically" "not")))
21475 :style toggle :selected org-log-done])
21477 ["Agenda Command..." org-agenda t]
21478 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21479 ("File List for Agenda")
21480 ("Special views current file"
21481 ["TODO Tree" org-show-todo-tree t]
21482 ["Check Deadlines" org-check-deadlines t]
21483 ["Tags/Property tree" org-match-sparse-tree t])
21485 ["Export/Publish..." org-export-dispatch t]
21487 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21488 :style toggle :selected org-cdlatex-mode]
21489 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21490 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21491 ["Modify math symbol" org-cdlatex-math-modify
21492 (org-inside-LaTeX-fragment-p)]
21493 ["Insert citation" org-reftex-citation t])
21496 ["Push Files and Views" org-mobile-push t]
21497 ["Get Captured and Flagged" org-mobile-pull t]
21498 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21500 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21503 ["Show Version" org-version t]
21504 ["Info Documentation" org-info t])
21506 ["Browse Org Group" org-customize t]
21508 ["Expand This Menu" org-create-customize-menu
21509 (fboundp 'customize-menu-create)])
21510 ["Send bug report" org-submit-bug-report t]
21513 ["Refresh setup current buffer" org-mode-restart t]
21514 ["Reload Org (after update)" org-reload t]
21515 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21518 (defun org-info (&optional node)
21519 "Read documentation for Org in the info system.
21520 With optional NODE, go directly to that node."
21522 (info (format "(org)%s" (or node ""))))
21525 (defun org-submit-bug-report ()
21526 "Submit a bug report on Org via mail.
21528 Don't hesitate to report any problems or inaccurate documentation.
21530 If you don't have setup sending mail from (X)Emacs, please copy the
21531 output buffer into your mail program, as it gives us important
21532 information about your Org version and configuration."
21534 (require 'reporter)
21535 (defvar reporter-prompt-for-summary-p)
21536 (org-load-modules-maybe)
21537 (org-require-autoloaded-modules)
21538 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21539 (reporter-submit-bug-report
21540 "emacs-orgmode@gnu.org"
21541 (org-version nil 'full)
21543 (save-window-excursion
21544 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21545 (delete-other-windows)
21547 (insert "You are about to submit a bug report to the Org mailing list.
21549 We would like to add your full Org and Outline configuration to the
21550 bug report. This greatly simplifies the work of the maintainer and
21551 other experts on the mailing list.
21553 HOWEVER, some variables you have customized may contain private
21554 information. The names of customers, colleagues, or friends, might
21555 appear in the form of file names, tags, todo states, or search strings.
21556 If you answer yes to the prompt, you might want to check and remove
21557 such private information before sending the email.")
21558 (add-text-properties (point-min) (point-max) '(face org-warning))
21559 (when (yes-or-no-p "Include your Org configuration ")
21563 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21564 (or (and (symbol-value v)
21565 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21567 (get v 'custom-type) (get v 'standard-value)
21568 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21570 (kill-buffer (get-buffer "*Warn about privacy*"))
21573 "Remember to cover the basics, that is, what you expected to happen and
21574 what in fact did happen. You don't know how to make a good report? See
21576 http://orgmode.org/manual/Feedback.html#Feedback
21578 Your bug report will be posted to the Org mailing list.
21579 ------------------------------------------------------------------------")
21581 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21582 (replace-match "\\1Bug: \\3 [\\2]")))))
21585 (defun org-install-agenda-files-menu ()
21586 (let ((bl (buffer-list)))
21589 (set-buffer (pop bl))
21590 (when (derived-mode-p 'org-mode) (setq bl nil)))
21591 (when (derived-mode-p 'org-mode)
21593 '("Org") "File List for Agenda"
21596 ["Edit File List" (org-edit-agenda-file-list) t]
21597 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21598 ["Remove Current File from List" org-remove-file t]
21599 ["Cycle through agenda files" org-cycle-agenda-files t]
21600 ["Occur in all agenda files" org-occur-in-agenda-files t]
21602 (mapcar 'org-file-menu-entry
21603 ;; Prevent initialization from failing.
21604 (ignore-errors (org-agenda-files t)))))))))
21608 (defun org-require-autoloaded-modules ()
21611 '(org-agenda org-archive org-attach org-clock org-colview org-id
21612 org-table org-timer)))
21615 (defun org-reload (&optional uncompiled)
21616 "Reload all org lisp files.
21617 With prefix arg UNCOMPILED, load the uncompiled versions."
21619 (require 'loadhist)
21620 (let* ((org-dir (org-find-library-dir "org"))
21621 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21622 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21623 (remove-re (format "\\`%s\\'"
21624 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21625 (feats (delete-dups
21626 (mapcar 'file-name-sans-extension
21627 (mapcar 'file-name-nondirectory
21629 (mapcar 'feature-file
21636 (if (and (string-match feature-re f)
21637 (not (string-match remove-re f)))
21641 (list "org-version" "org")))
21642 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21643 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21644 load-uncore load-misses)
21647 (mapcar (lambda (f)
21648 (or (org-load-noerror-mustsuffix (concat org-dir f))
21649 (and (string= org-dir contrib-dir)
21650 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21651 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21652 (add-to-list 'load-uncore f 'append)
21657 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21658 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21660 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21661 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21662 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21665 (defun org-customize ()
21666 "Call the customize function with org as argument."
21668 (org-load-modules-maybe)
21669 (org-require-autoloaded-modules)
21670 (customize-browse 'org))
21672 (defun org-create-customize-menu ()
21673 "Create a full customization menu for Org mode, insert it into the menu."
21675 (org-load-modules-maybe)
21676 (org-require-autoloaded-modules)
21677 (if (fboundp 'customize-menu-create)
21680 '("Org") "Customize"
21681 `(["Browse Org group" org-customize t]
21683 ,(customize-menu-create 'org)
21684 ["Set" Custom-set t]
21685 ["Save" Custom-save t]
21686 ["Reset to Current" Custom-reset-current t]
21687 ["Reset to Saved" Custom-reset-saved t]
21688 ["Reset to Standard Settings" Custom-reset-standard t]))
21689 (message "\"Org\"-menu now contains full customization menu"))
21690 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21692 ;;;; Miscellaneous stuff
21694 ;;; Generally useful functions
21696 (defun org-get-at-eol (property n)
21697 "Get text property PROPERTY at the end of line less N characters."
21698 (get-text-property (- (point-at-eol) n) property))
21700 (defun org-find-text-property-in-string (prop s)
21701 "Return the first non-nil value of property PROP in string S."
21702 (or (get-text-property 0 prop s)
21703 (get-text-property (or (next-single-property-change 0 prop s) 0)
21706 (defun org-display-warning (message)
21707 "Display the given MESSAGE as a warning."
21708 (display-warning 'org message :warning))
21710 (defun org-eval (form)
21711 "Eval FORM and return result."
21712 (condition-case error
21714 (error (format "%%![Error: %s]" error))))
21716 (defun org-in-clocktable-p ()
21717 "Check if the cursor is in a clocktable."
21718 (let ((pos (point)) start)
21721 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21722 (setq start (match-beginning 0))
21723 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21724 (>= (match-end 0) pos)
21727 (defun org-in-verbatim-emphasis ()
21729 (and (org-in-regexp org-verbatim-re 2)
21730 (>= (point) (match-beginning 3))
21731 (<= (point) (match-end 4)))))
21733 (defun org-overlay-display (ovl text &optional face evap)
21734 "Make overlay OVL display TEXT with face FACE."
21735 (overlay-put ovl 'display text)
21736 (if face (overlay-put ovl 'face face))
21737 (if evap (overlay-put ovl 'evaporate t)))
21739 (defun org-overlay-before-string (ovl text &optional face evap)
21740 "Make overlay OVL display TEXT with face FACE."
21741 (if face (org-add-props text nil 'face face))
21742 (overlay-put ovl 'before-string text)
21743 (if evap (overlay-put ovl 'evaporate t)))
21745 (defun org-find-overlays (prop &optional pos delete)
21746 "Find all overlays specifying PROP at POS or point.
21747 If DELETE is non-nil, delete all those overlays."
21749 (dolist (ov (overlays-at (or pos (point))) found)
21750 (cond ((not (overlay-get ov prop)))
21751 (delete (delete-overlay ov))
21752 (t (push ov found))))))
21754 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21755 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21756 (if (and marker (marker-buffer marker)
21757 (buffer-live-p (marker-buffer marker)))
21759 (pop-to-buffer-same-window (marker-buffer marker))
21760 (when (or (> marker (point-max)) (< marker (point-min)))
21763 (org-show-context 'org-goto))
21765 (bookmark-jump bookmark)
21766 (error "Cannot find location"))))
21768 (defun org-quote-csv-field (s)
21769 "Quote field for inclusion in CSV material."
21770 (if (string-match "[\",]" s)
21771 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21774 (defun org-force-self-insert (N)
21775 "Needed to enforce self-insert under remapping."
21777 (self-insert-command N))
21779 (defun org-shorten-string (s maxlength)
21780 "Shorten string S so that it is no longer than MAXLENGTH characters.
21781 If the string is shorter or has length MAXLENGTH, just return the
21782 original string. If it is longer, the functions finds a space in the
21783 string, breaks this string off at that locations and adds three dots
21784 as ellipsis. Including the ellipsis, the string will not be longer
21785 than MAXLENGTH. If finding a good breaking point in the string does
21786 not work, the string is just chopped off in the middle of a word
21788 (if (<= (length s) maxlength)
21790 (let* ((n (max (- maxlength 4) 1))
21791 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21792 (if (string-match re s)
21793 (concat (match-string 1 s) "...")
21794 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21796 (defun org-get-indentation (&optional line)
21797 "Get the indentation of the current line, interpreting tabs.
21798 When LINE is given, assume it represents a line and compute its indentation."
21800 (when (string-match "^ *" (org-remove-tabs line))
21803 (beginning-of-line 1)
21804 (skip-chars-forward " \t")
21805 (current-column))))
21807 (defun org-get-string-indentation (s)
21808 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21809 (let ((n -1) (i 0) (w tab-width) c)
21811 (while (< (setq n (1+ n)) (length s))
21812 (setq c (aref s n))
21813 (cond ((= c ?\ ) (setq i (1+ i)))
21814 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21815 (t (throw 'exit t)))))
21818 (defun org-remove-tabs (s &optional width)
21819 "Replace tabulators in S with spaces.
21820 Assumes that s is a single line, starting in column 0."
21821 (setq width (or width tab-width))
21822 (while (string-match "\t" s)
21823 (setq s (replace-match
21825 (- (* width (/ (+ (match-beginning 0) width) width))
21826 (match-beginning 0)) ?\ )
21830 (defun org-fix-indentation (line ind)
21831 "Fix indentation in LINE.
21832 IND is a cons cell with target and minimum indentation.
21833 If the current indentation in LINE is smaller than the minimum,
21834 leave it alone. If it is larger than ind, set it to the target."
21835 (let* ((l (org-remove-tabs line))
21836 (i (org-get-indentation l))
21837 (i1 (car ind)) (i2 (cdr ind)))
21838 (when (>= i i2) (setq l (substring line i2)))
21840 (concat (make-string i1 ?\ ) l)
21843 (defun org-remove-indentation (code &optional n)
21844 "Remove maximum common indentation in string CODE and return it.
21845 N may optionally be the number of columns to remove. Return CODE
21846 as-is if removal failed."
21849 (if (org-do-remove-indentation n) (buffer-string) code)))
21851 (defun org-do-remove-indentation (&optional n)
21852 "Remove the maximum common indentation from the buffer.
21853 When optional argument N is a positive integer, remove exactly
21854 that much characters from indentation, if possible. Return nil
21857 (goto-char (point-min))
21858 ;; Find maximum common indentation, if not specified.
21860 (let ((min-ind (point-max)))
21862 (while (re-search-forward "^[ \t]*\\S-" nil t)
21863 (let ((ind (1- (current-column))))
21864 (if (zerop ind) (throw :exit nil)
21865 (setq min-ind (min min-ind ind))))))
21867 (if (zerop n) (throw :exit nil)
21868 ;; Remove exactly N indentation, but give up if not possible.
21869 (while (not (eobp))
21870 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21871 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21872 ((< ind n) (throw :exit nil))
21873 (t (indent-line-to (- ind n))))
21878 (defun org-fill-template (template alist)
21879 "Find each %key of ALIST in TEMPLATE and replace it."
21880 (let ((case-fold-search nil))
21881 (dolist (entry (sort (copy-sequence alist)
21882 (lambda (a b) (< (length (car a)) (length (car b))))))
21884 (replace-regexp-in-string
21885 (concat "%" (regexp-quote (car entry)))
21886 (or (cdr entry) "") template t t)))
21889 (defun org-base-buffer (buffer)
21890 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21893 (or (buffer-base-buffer buffer)
21896 (defun org-wrap (string &optional width lines)
21897 "Wrap string to either a number of lines, or a width in characters.
21898 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21899 that costs. If there is a word longer than WIDTH, the text is actually
21900 wrapped to the length of that word.
21901 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21902 many lines, whatever width that takes.
21903 The return value is a list of lines, without newlines at the end."
21904 (let* ((words (split-string string))
21905 (maxword (apply 'max (mapcar 'org-string-width words)))
21908 (org-do-wrap words (max maxword width)))
21911 (setq ll (org-do-wrap words maxword))
21912 (if (<= (length ll) lines)
21915 (while (> (length ll) lines)
21917 (setq ll (org-do-wrap words w)))
21919 (t (error "Cannot wrap this")))))
21921 (defun org-do-wrap (words width)
21922 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21925 (setq line (pop words))
21926 (while (and words (< (+ (length line) (length (car words))) width))
21927 (setq line (concat line " " (pop words))))
21928 (setq lines (push line lines)))
21931 (defun org-quote-vert (s)
21932 "Replace \"|\" with \"\\vert\"."
21933 (while (string-match "|" s)
21934 (setq s (replace-match "\\vert" t t s)))
21937 (defun org-uuidgen-p (s)
21938 "Is S an ID created by UUIDGEN?"
21939 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21941 (defun org-in-src-block-p (&optional inside)
21942 "Whether point is in a code source block.
21943 When INSIDE is non-nil, don't consider we are within a src block
21944 when point is at #+BEGIN_SRC or #+END_SRC."
21945 (let ((case-fold-search t))
21946 (or (and (eq (get-char-property (point) 'src-block) t))
21950 (beginning-of-line)
21951 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21953 (defun org-context ()
21954 "Return a list of contexts of the current cursor position.
21955 If several contexts apply, all are returned.
21956 Each context entry is a list with a symbol naming the context, and
21957 two positions indicating start and end of the context. Possible
21960 :headline anywhere in a headline
21961 :headline-stars on the leading stars in a headline
21962 :todo-keyword on a TODO keyword (including DONE) in a headline
21963 :tags on the TAGS in a headline
21964 :priority on the priority cookie in a headline
21965 :item on the first line of a plain list item
21966 :item-bullet on the bullet/number of a plain list item
21967 :checkbox on the checkbox in a plain list item
21968 :table in an Org table
21969 :table-special on a special filed in a table
21970 :table-table in a table.el table
21971 :clocktable in a clocktable
21972 :src-block in a source block
21973 :link on a hyperlink
21974 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21975 :target on a <<target>>
21976 :radio-target on a <<<radio-target>>>
21977 :latex-fragment on a LaTeX fragment
21978 :latex-preview on a LaTeX fragment with overlaid preview image
21980 This function expects the position to be visible because it uses font-lock
21981 faces as a help to recognize the following contexts: :table-special, :link,
21983 (let* ((f (get-text-property (point) 'face))
21984 (faces (if (listp f) f (list f)))
21985 (case-fold-search t)
21986 (p (point)) clist o)
21987 ;; First the large context
21989 ((org-at-heading-p t)
21990 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21992 (beginning-of-line 1)
21993 (looking-at org-todo-line-tags-regexp))
21994 (push (org-point-in-group p 1 :headline-stars) clist)
21995 (push (org-point-in-group p 2 :todo-keyword) clist)
21996 (push (org-point-in-group p 4 :tags) clist))
21998 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21999 (when (looking-at "\\[#[A-Z0-9]\\]")
22000 (push (org-point-in-group p 0 :priority) clist)))
22003 (push (org-point-in-group p 2 :item-bullet) clist)
22004 (push (list :item (point-at-bol)
22005 (save-excursion (org-end-of-item) (point)))
22007 (and (org-at-item-checkbox-p)
22008 (push (org-point-in-group p 0 :checkbox) clist)))
22011 (push (list :table (org-table-begin) (org-table-end)) clist)
22012 (when (memq 'org-formula faces)
22013 (push (list :table-special
22014 (previous-single-property-change p 'face)
22015 (next-single-property-change p 'face)) clist)))
22016 ((org-at-table-p 'any)
22017 (push (list :table-table) clist)))
22020 (let ((case-fold-search t))
22021 ;; New the "medium" contexts: clocktables, source blocks
22022 (cond ((org-in-clocktable-p)
22023 (push (list :clocktable
22024 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22025 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22026 (match-beginning 1))
22027 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22028 (match-end 0))) clist))
22029 ((org-in-src-block-p)
22030 (push (list :src-block
22031 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22032 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22033 (match-beginning 1))
22034 (and (search-forward "#+END_SRC" nil t)
22035 (match-beginning 0))) clist))))
22038 ;; Now the small context
22040 ((org-at-timestamp-p)
22041 (push (org-point-in-group p 0 :timestamp) clist))
22042 ((memq 'org-link faces)
22044 (previous-single-property-change p 'face)
22045 (next-single-property-change p 'face)) clist))
22046 ((memq 'org-special-keyword faces)
22047 (push (list :keyword
22048 (previous-single-property-change p 'face)
22049 (next-single-property-change p 'face)) clist))
22051 (push (org-point-in-group p 0 :target) clist)
22052 (goto-char (1- (match-beginning 0)))
22053 (when (looking-at org-radio-target-regexp)
22054 (push (org-point-in-group p 0 :radio-target) clist))
22058 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22060 (overlays-at (point))))
22061 (push (list :latex-fragment
22062 (overlay-start o) (overlay-end o)) clist)
22063 (push (list :latex-preview
22064 (overlay-start o) (overlay-end o)) clist))
22065 ((org-inside-LaTeX-fragment-p)
22066 ;; FIXME: positions wrong.
22067 (push (list :latex-fragment (point) (point)) clist)))
22069 (setq clist (nreverse (delq nil clist)))
22072 (defun org-in-regexp (regexp &optional nlines visually)
22073 "Check if point is inside a match of REGEXP.
22075 Normally only the current line is checked, but you can include
22076 NLINES extra lines around point into the search. If VISUALLY is
22077 set, require that the cursor is not after the match but really
22078 on, so that the block visually is on the match.
22080 Return nil or a cons cell (BEG . END) where BEG and END are,
22081 respectively, the positions at the beginning and the end of the
22084 (let ((pos (point))
22085 (eol (line-end-position (if nlines (1+ nlines) 1))))
22087 (beginning-of-line (- 1 (or nlines 0)))
22088 (while (and (re-search-forward regexp eol t)
22089 (<= (match-beginning 0) pos))
22090 (let ((end (match-end 0)))
22091 (when (or (> end pos) (and (= end pos) (not visually)))
22092 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22094 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22095 "Non-nil when point is between matches of START-RE and END-RE.
22097 Also return a non-nil value when point is on one of the matches.
22099 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22100 buffer positions. Default values are the positions of headlines
22101 surrounding the point.
22103 The functions returns a cons cell whose car (resp. cdr) is the
22104 position before START-RE (resp. after END-RE)."
22106 (let ((pos (point))
22107 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22108 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22111 ;; Point is on a block when on START-RE or if START-RE can be
22112 ;; found before it...
22113 (and (or (org-in-regexp start-re)
22114 (re-search-backward start-re limit-up t))
22115 (setq beg (match-beginning 0))
22116 ;; ... and END-RE after it...
22117 (goto-char (match-end 0))
22118 (re-search-forward end-re limit-down t)
22119 (> (setq end (match-end 0)) pos)
22120 ;; ... without another START-RE in-between.
22121 (goto-char (match-beginning 0))
22122 (not (re-search-backward start-re (1+ beg) t))
22124 (cons beg end))))))
22126 (defun org-in-block-p (names)
22127 "Non-nil when point belongs to a block whose name belongs to NAMES.
22129 NAMES is a list of strings containing names of blocks.
22131 Return first block name matched, or nil. Beware that in case of
22132 nested blocks, the returned name may not belong to the closest
22136 (let ((case-fold-search t)
22137 (lim-up (save-excursion (outline-previous-heading)))
22138 (lim-down (save-excursion (outline-next-heading))))
22139 (dolist (name names)
22140 (let ((n (regexp-quote name)))
22141 (when (org-between-regexps-p
22142 (concat "^[ \t]*#\\+begin_" n)
22143 (concat "^[ \t]*#\\+end_" n)
22145 (throw 'exit n)))))
22148 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22149 "Call `multi-occur' with buffers for all agenda files."
22150 (interactive "sOrg-files matching: ")
22151 (let* ((files (org-agenda-files))
22152 (tnames (mapcar #'file-truename files))
22153 (extra org-agenda-text-search-extra-files))
22154 (when (eq (car extra) 'agenda-archives)
22155 (setq extra (cdr extra))
22156 (setq files (org-add-archive-files files)))
22158 (unless (member (file-truename f) tnames)
22159 (unless (member f files) (setq files (append files (list f))))
22160 (setq tnames (append tnames (list (file-truename f))))))
22162 (mapcar (lambda (x)
22163 (with-current-buffer
22164 ;; FIXME: Why not just (find-file-noselect x)?
22165 ;; Is it to avoid the "revert buffer" prompt?
22166 (or (get-file-buffer x) (find-file-noselect x))
22172 (add-hook 'occur-mode-find-occurrence-hook
22173 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22175 (defun org-occur-link-in-agenda-files ()
22176 "Create a link and search for it in the agendas.
22177 The link is not stored in `org-stored-links', it is just created
22178 for the search purpose."
22180 (let ((link (condition-case nil
22181 (org-store-link nil)
22182 (error "Unable to create a link to here"))))
22183 (org-occur-in-agenda-files (regexp-quote link))))
22185 (defun org-reverse-string (string)
22186 "Return the reverse of STRING."
22187 (apply 'string (reverse (string-to-list string))))
22189 ;; defsubst org-uniquify must be defined before first use
22191 (defun org-uniquify-alist (alist)
22192 "Merge elements of ALIST with the same key.
22194 For example, in this alist:
22196 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22197 => \\='((a 1 3) (b 2))
22199 merge (a 1) and (a 3) into (a 1 3).
22201 The function returns the new ALIST."
22203 (dolist (e alist rtn)
22205 (if (not (assoc (car e) rtn))
22207 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22208 (setq rtn (assq-delete-all (car e) rtn))
22211 (defun org-delete-all (elts list)
22212 "Remove all elements in ELTS from LIST.
22213 Comparison is done with `equal'. It is a destructive operation
22214 that may remove elements by altering the list structure."
22216 (setq list (delete (pop elts) list)))
22219 (defun org-back-over-empty-lines ()
22220 "Move backwards over whitespace, to the beginning of the first empty line.
22221 Returns the number of empty lines passed."
22222 (let ((pos (point)))
22223 (if (cdr (assq 'heading org-blank-before-new-entry))
22224 (skip-chars-backward " \t\n\r")
22226 (forward-line -1)))
22227 (beginning-of-line 2)
22228 (goto-char (min (point) pos))
22229 (count-lines (point) pos)))
22231 (defun org-skip-whitespace ()
22232 (skip-chars-forward " \t\n\r"))
22234 (defun org-point-in-group (point group &optional context)
22235 "Check if POINT is in match-group GROUP.
22236 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22237 match. If the match group does not exist or point is not inside it,
22239 (and (match-beginning group)
22240 (>= point (match-beginning group))
22241 (<= point (match-end group))
22243 (list context (match-beginning group) (match-end group))
22246 (defun org-switch-to-buffer-other-window (&rest args)
22247 "Switch to buffer in a second window on the current frame.
22248 In particular, do not allow pop-up frames.
22249 Returns the newly created buffer."
22251 (apply 'switch-to-buffer-other-window args)))
22253 (defun org-combine-plists (&rest plists)
22254 "Create a single property list from all plists in PLISTS.
22255 The process starts by copying the first list, and then setting properties
22256 from the other lists. Settings in the last list are the most significant
22257 ones and overrule settings in the other lists."
22258 (let ((rtn (copy-sequence (pop plists)))
22261 (setq ls (pop plists))
22263 (setq p (pop ls) v (pop ls))
22264 (setq rtn (plist-put rtn p v))))
22267 (defun org-replace-escapes (string table)
22268 "Replace %-escapes in STRING with values in TABLE.
22269 TABLE is an association list with keys like \"%a\" and string values.
22270 The sequences in STRING may contain normal field width and padding information,
22271 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22272 so values can contain further %-escapes if they are define later in TABLE."
22273 (let ((tbl (copy-alist table))
22274 (case-fold-search nil)
22278 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22279 (when (and (cdr e) (string-match re (cdr e)))
22280 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22282 (add-text-properties 0 3 (list 'sref sref) safe)
22283 (setcdr e (replace-match safe t t (cdr e)))))
22284 (while (string-match re string)
22285 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22287 (setq string (replace-match rpl t t string))))
22288 (while (setq pchg (next-property-change pchg string))
22289 (let ((sref (get-text-property pchg 'sref string)))
22290 (when (and sref (string-match "SREF" string pchg))
22291 (setq string (replace-match sref t t string)))))
22294 (defun org-find-base-buffer-visiting (file)
22295 "Like `find-buffer-visiting' but always return the base buffer and
22296 not an indirect buffer."
22297 (let ((buf (or (get-file-buffer file)
22298 (find-buffer-visiting file))))
22300 (or (buffer-base-buffer buf) buf)
22303 ;;; TODO: Only called once, from ox-odt which should probably use
22304 ;;; org-export-inline-image-p or something.
22305 (defun org-file-image-p (file)
22306 "Return non-nil if FILE is an image."
22308 (string-match (image-file-name-regexp) file)))
22310 (defun org-get-cursor-date (&optional with-time)
22311 "Return the date at cursor in as a time.
22312 This works in the calendar and in the agenda, anywhere else it just
22313 returns the current time.
22314 If WITH-TIME is non-nil, returns the time of the event at point (in
22315 the agenda) or the current time of the day."
22316 (let (date day defd tp hod mod)
22318 (setq tp (get-text-property (point) 'time))
22319 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22320 (setq hod (string-to-number (match-string 1 tp))
22321 mod (string-to-number (match-string 2 tp))))
22322 (or tp (let ((now (decode-time)))
22323 (setq hod (nth 2 now)
22324 mod (nth 1 now)))))
22326 ((eq major-mode 'calendar-mode)
22327 (setq date (calendar-cursor-to-date)
22328 defd (encode-time 0 (or mod 0) (or hod 0)
22329 (nth 1 date) (nth 0 date) (nth 2 date))))
22330 ((eq major-mode 'org-agenda-mode)
22331 (setq day (get-text-property (point) 'day))
22333 (setq date (calendar-gregorian-from-absolute day)
22334 defd (encode-time 0 (or mod 0) (or hod 0)
22335 (nth 1 date) (nth 0 date) (nth 2 date))))))
22336 (or defd (current-time))))
22338 (defun org-mark-subtree (&optional up)
22339 "Mark the current subtree.
22340 This puts point at the start of the current subtree, and mark at
22341 the end. If a numeric prefix UP is given, move up into the
22342 hierarchy of headlines by UP levels before marking the subtree."
22344 (org-with-limited-levels
22345 (cond ((org-at-heading-p) (beginning-of-line))
22346 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22347 (t (outline-previous-visible-heading 1))))
22348 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22349 (if (called-interactively-p 'any)
22350 (call-interactively 'org-mark-element)
22351 (org-mark-element)))
22353 (defun org-file-newer-than-p (file time)
22354 "Non-nil if FILE is newer than TIME.
22355 FILE is a filename, as a string, TIME is a list of integers, as
22356 returned by, e.g., `current-time'."
22357 (and (file-exists-p file)
22358 ;; Only compare times up to whole seconds as some file-systems
22359 ;; (e.g. HFS+) do not retain any finer granularity. As
22360 ;; a consequence, make sure we return non-nil when the two
22361 ;; times are equal.
22362 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22363 (cl-subseq time 0 2)))))
22365 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22366 "Compile a SOURCE file using PROCESS.
22368 PROCESS is either a function or a list of shell commands, as
22369 strings. EXT is a file extension, without the leading dot, as
22370 a string. It is used to check if the process actually succeeded.
22372 PROCESS must create a file with the same base name and directory
22373 as SOURCE, but ending with EXT. The function then returns its
22374 filename. Otherwise, it raises an error. The error message can
22375 then be refined by providing string ERR-MSG, which is appended to
22376 the standard message.
22378 If PROCESS is a function, it is called with a single argument:
22381 If it is a list of commands, each of them is called using
22382 `shell-command'. By default, in each command, %b, %f, %F, %o and
22383 %O are replaced with, respectively, SOURCE base name, name, full
22384 name, directory and absolute output file name. It is possible,
22385 however, to use more place-holders by specifying them in optional
22386 argument SPEC, as an alist following the pattern
22388 (CHARACTER . REPLACEMENT-STRING).
22390 When PROCESS is a list of commands, optional argument LOG-BUF can
22391 be set to a buffer or a buffer name. `shell-command' then uses
22393 (let* ((base-name (file-name-base source))
22394 (full-name (file-truename source))
22395 (out-dir (or (file-name-directory source) "./"))
22396 (output (expand-file-name (concat base-name "." ext) out-dir))
22397 (time (current-time))
22398 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22399 (save-window-excursion
22401 ((pred functionp) (funcall process (shell-quote-argument source)))
22403 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22405 `((?b . ,(shell-quote-argument base-name))
22406 (?f . ,(shell-quote-argument source))
22407 (?F . ,(shell-quote-argument full-name))
22408 (?o . ,(shell-quote-argument out-dir))
22409 (?O . ,(shell-quote-argument output))))))
22410 (dolist (command process)
22411 (shell-command (format-spec command spec) log-buf))
22412 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22413 (_ (error "No valid command to process %S%s" source err-msg))))
22414 ;; Check for process failure. Output file is expected to be
22415 ;; located in the same directory as SOURCE.
22416 (unless (org-file-newer-than-p output time)
22417 (error (format "File %S wasn't produced%s" output err-msg)))
22422 (defvar org-element-greater-elements)
22423 (defun org--get-expected-indentation (element contentsp)
22424 "Expected indentation column for current line, according to ELEMENT.
22425 ELEMENT is an element containing point. CONTENTSP is non-nil
22426 when indentation is to be computed according to contents of
22428 (let ((type (org-element-type element))
22429 (start (org-element-property :begin element))
22430 (post-affiliated (org-element-property :post-affiliated element)))
22431 (org-with-wide-buffer
22435 ((diary-sexp footnote-definition) 0)
22436 ((headline inlinetask nil)
22437 (if (not org-adapt-indentation) 0
22438 (let ((level (org-current-level)))
22439 (if level (1+ level) 0))))
22440 ((item plain-list) (org-list-item-body-column post-affiliated))
22443 (org-get-indentation))))
22444 ((memq type '(headline inlinetask nil))
22445 (if (org-match-line "[ \t]*$")
22446 (org--get-expected-indentation element t)
22448 ((memq type '(diary-sexp footnote-definition)) 0)
22449 ;; First paragraph of a footnote definition or an item.
22450 ;; Indent like parent.
22451 ((< (line-beginning-position) start)
22452 (org--get-expected-indentation
22453 (org-element-property :parent element) t))
22454 ;; At first line: indent according to previous sibling, if any,
22455 ;; ignoring footnote definitions and inline tasks, or parent's
22457 ((= (line-beginning-position) start)
22460 (if (= (point-min) start) (throw 'exit 0)
22461 (goto-char (1- start))
22462 (let* ((previous (org-element-at-point))
22464 (while (and parent (<= (org-element-property :end parent) start))
22465 (setq previous parent
22466 parent (org-element-property :parent parent)))
22468 ((not previous) (throw 'exit 0))
22469 ((> (org-element-property :end previous) start)
22470 (throw 'exit (org--get-expected-indentation previous t)))
22471 ((memq (org-element-type previous)
22472 '(footnote-definition inlinetask))
22473 (setq start (org-element-property :begin previous)))
22474 (t (goto-char (org-element-property :begin previous))
22476 (if (bolp) (org-get-indentation)
22477 ;; At first paragraph in an item or
22478 ;; a footnote definition.
22479 (org--get-expected-indentation
22480 (org-element-property :parent previous) t))))))))))
22481 ;; Otherwise, move to the first non-blank line above.
22483 (beginning-of-line)
22484 (let ((pos (point)))
22485 (skip-chars-backward " \r\t\n")
22487 ;; Two blank lines end a footnote definition or a plain
22488 ;; list. When we indent an empty line after them, the
22489 ;; containing list or footnote definition is over, so it
22490 ;; qualifies as a previous sibling. Therefore, we indent
22491 ;; like its first line.
22492 ((and (memq type '(footnote-definition plain-list))
22493 (> (count-lines (point) pos) 2))
22495 (org-get-indentation))
22496 ;; Line above is the first one of a paragraph at the
22497 ;; beginning of an item or a footnote definition. Indent
22499 ((< (line-beginning-position) start)
22500 (org--get-expected-indentation
22501 (org-element-property :parent element) t))
22502 ;; Line above is the beginning of an element, i.e., point
22503 ;; was originally on the blank lines between element's start
22505 ((= (line-beginning-position) post-affiliated)
22506 (org--get-expected-indentation element t))
22507 ;; POS is after contents in a greater element. Indent like
22508 ;; the beginning of the element.
22509 ((and (memq type org-element-greater-elements)
22510 (let ((cend (org-element-property :contents-end element)))
22511 (and cend (<= cend pos))))
22512 ;; As a special case, if point is at the end of a footnote
22513 ;; definition or an item, indent like the very last element
22514 ;; within. If that last element is an item, indent like
22516 (if (memq type '(footnote-definition item plain-list))
22517 (let ((last (org-element-at-point)))
22519 (org--get-expected-indentation
22520 last (eq (org-element-type last) 'item)))
22522 (org-get-indentation)))
22523 ;; In any other case, indent like the current line.
22524 (t (org-get-indentation)))))))))
22526 (defun org--align-node-property ()
22527 "Align node property at point.
22528 Alignment is done according to `org-property-format', which see."
22529 (when (save-excursion
22530 (beginning-of-line)
22531 (looking-at org-property-re))
22533 (concat (match-string 4)
22535 (format org-property-format (match-string 1) (match-string 3))))
22538 (defun org-indent-line ()
22539 "Indent line depending on context.
22541 Indentation is done according to the following rules:
22543 - Footnote definitions, diary sexps, headlines and inline tasks
22544 have to start at column 0.
22546 - On the very first line of an element, consider, in order, the
22547 next rules until one matches:
22549 1. If there's a sibling element before, ignoring footnote
22550 definitions and inline tasks, indent like its first line.
22552 2. If element has a parent, indent like its contents. More
22553 precisely, if parent is an item, indent after the
22554 description part, if any, or the bullet (see
22555 `org-list-description-max-indent'). Else, indent like
22556 parent's first line.
22558 3. Otherwise, indent relatively to current level, if
22559 `org-adapt-indentation' is non-nil, or to left margin.
22561 - On a blank line at the end of an element, indent according to
22562 the type of the element. More precisely
22564 1. If element is a plain list, an item, or a footnote
22565 definition, indent like the very last element within.
22567 2. If element is a paragraph, indent like its last non blank
22570 3. Otherwise, indent like its very first line.
22572 - In the code part of a source block, use language major mode
22573 to indent current line if `org-src-tab-acts-natively' is
22574 non-nil. If it is nil, do nothing.
22576 - Otherwise, indent like the first non-blank line above.
22578 The function doesn't indent an item as it could break the whole
22579 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22580 `\\[org-shiftmetaright]'.
22582 Also align node properties according to `org-property-format'."
22586 (let ((indent-line-function
22587 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22588 (indent-according-to-mode)))
22589 ((org-at-heading-p) 'noindent)
22591 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22592 (type (org-element-type element)))
22593 (cond ((and (memq type '(plain-list item))
22594 (= (line-beginning-position)
22595 (org-element-property :post-affiliated element)))
22597 ((and (eq type 'latex-environment)
22598 (>= (point) (org-element-property :post-affiliated element))
22599 (< (point) (org-with-wide-buffer
22600 (goto-char (org-element-property :end element))
22601 (skip-chars-backward " \r\t\n")
22602 (line-beginning-position 2))))
22604 ((and (eq type 'src-block)
22605 org-src-tab-acts-natively
22606 (> (line-beginning-position)
22607 (org-element-property :post-affiliated element))
22608 (< (line-beginning-position)
22609 (org-with-wide-buffer
22610 (goto-char (org-element-property :end element))
22611 (skip-chars-backward " \r\t\n")
22612 (line-beginning-position))))
22613 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22615 (let ((column (org--get-expected-indentation element nil)))
22616 ;; Preserve current column.
22617 (if (<= (current-column) (current-indentation))
22618 (indent-line-to column)
22619 (save-excursion (indent-line-to column))))
22620 ;; Align node property. Also preserve current column.
22621 (when (eq type 'node-property)
22622 (let ((column (current-column)))
22623 (org--align-node-property)
22624 (org-move-to-column column)))))))))
22626 (defun org-indent-region (start end)
22627 "Indent each non-blank line in the region.
22628 Called from a program, START and END specify the region to
22629 indent. The function will not indent contents of example blocks,
22630 verse blocks and export blocks as leading white spaces are
22631 assumed to be significant there."
22635 (skip-chars-forward " \r\t\n")
22636 (unless (eobp) (beginning-of-line))
22639 ;; Set IND as indentation for all lines between point and
22640 ;; POS. Blank lines are ignored. Leave point after POS
22642 (let ((limit (copy-marker pos)))
22643 (while (< (point) limit)
22644 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22646 (set-marker limit nil))))
22647 (end (copy-marker end)))
22648 (while (< (point) end)
22649 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22650 (let* ((element (org-element-at-point))
22651 (type (org-element-type element))
22652 (element-end (copy-marker (org-element-property :end element)))
22653 (ind (org--get-expected-indentation element nil)))
22655 ;; Element indented as a single block. Example blocks
22656 ;; preserving indentation are a special case since the
22657 ;; "contents" must not be indented whereas the block
22659 ((or (memq type '(export-block latex-environment))
22660 (and (eq type 'example-block)
22662 (or org-src-preserve-indentation
22663 (org-element-property :preserve-indent element)))))
22664 (let ((offset (- ind (org-get-indentation))))
22665 (unless (zerop offset)
22666 (indent-rigidly (org-element-property :begin element)
22667 (org-element-property :end element)
22669 (goto-char element-end))
22670 ;; Elements indented line wise. Be sure to exclude
22671 ;; example blocks (preserving indentation) and source
22672 ;; blocks from this category as they are treated
22673 ;; specially later.
22674 ((or (memq type '(paragraph table table-row))
22675 (not (or (org-element-property :contents-begin element)
22676 (memq type '(example-block src-block)))))
22677 (when (eq type 'node-property)
22678 (org--align-node-property)
22679 (beginning-of-line))
22680 (funcall indent-to ind (min element-end end)))
22681 ;; Elements consisting of three parts: before the
22682 ;; contents, the contents, and after the contents. The
22683 ;; contents are treated specially, according to the
22684 ;; element type, or not indented at all. Other parts are
22685 ;; indented as a single block.
22687 (let* ((post (copy-marker
22688 (org-element-property :post-affiliated element)))
22692 ((not (org-element-property :contents-begin element))
22693 ;; Fake contents for source blocks.
22694 (org-with-wide-buffer
22696 (line-beginning-position 2)))
22697 ((memq type '(footnote-definition item plain-list))
22698 ;; Contents in these elements could start on
22699 ;; the same line as the beginning of the
22700 ;; element. Make sure we start indenting
22701 ;; from the second line.
22702 (org-with-wide-buffer
22705 (skip-chars-forward " \r\t\n")
22706 (if (eobp) (point) (line-beginning-position))))
22707 (t (org-element-property :contents-begin element)))))
22709 (or (org-element-property :contents-end element)
22710 ;; Fake contents for source blocks.
22711 (org-with-wide-buffer
22712 (goto-char element-end)
22713 (skip-chars-backward " \r\t\n")
22714 (line-beginning-position)))
22716 ;; Do not change items indentation individually as it
22717 ;; might break the list as a whole. On the other
22718 ;; hand, when at a plain list, indent it as a whole.
22719 (cond ((eq type 'plain-list)
22720 (let ((offset (- ind (org-get-indentation))))
22721 (unless (zerop offset)
22722 (indent-rigidly (org-element-property :begin element)
22723 (org-element-property :end element)
22726 ((eq type 'item) (goto-char cbeg))
22727 (t (funcall indent-to ind (min cbeg end))))
22728 (when (< (point) end)
22730 ((example-block verse-block))
22732 ;; In a source block, indent source code
22733 ;; according to language major mode, but only if
22734 ;; `org-src-tab-acts-natively' is non-nil.
22735 (when (and (< (point) end) org-src-tab-acts-natively)
22737 (org-babel-do-in-edit-buffer
22738 (indent-region (point-min) (point-max))))))
22739 (t (org-indent-region (point) (min cend end))))
22740 (goto-char (min cend end))
22741 (when (< (point) end)
22742 (funcall indent-to ind (min element-end end))))
22743 (set-marker post nil)
22744 (set-marker cbeg nil)
22745 (set-marker cend nil))))
22746 (set-marker element-end nil))))
22747 (set-marker end nil))))
22749 (defun org-indent-drawer ()
22750 "Indent the drawer at point."
22752 (unless (save-excursion
22753 (beginning-of-line)
22754 (looking-at-p org-drawer-regexp))
22755 (user-error "Not at a drawer"))
22756 (let ((element (org-element-at-point)))
22757 (unless (memq (org-element-type element) '(drawer property-drawer))
22758 (user-error "Not at a drawer"))
22759 (org-with-wide-buffer
22760 (org-indent-region (org-element-property :begin element)
22761 (org-element-property :end element))))
22762 (message "Drawer at point indented"))
22764 (defun org-indent-block ()
22765 "Indent the block at point."
22767 (unless (save-excursion
22768 (beginning-of-line)
22769 (let ((case-fold-search t))
22770 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22771 (user-error "Not at a block"))
22772 (let ((element (org-element-at-point)))
22773 (unless (memq (org-element-type element)
22774 '(comment-block center-block dynamic-block example-block
22775 export-block quote-block special-block
22776 src-block verse-block))
22777 (user-error "Not at a block"))
22778 (org-with-wide-buffer
22779 (org-indent-region (org-element-property :begin element)
22780 (org-element-property :end element))))
22781 (message "Block at point indented"))
22786 ;; We use our own fill-paragraph and auto-fill functions.
22788 ;; `org-fill-paragraph' relies on adaptive filling and context
22789 ;; checking. Appropriate `fill-prefix' is computed with
22790 ;; `org-adaptive-fill-function'.
22792 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22793 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22794 ;; `org-adaptive-fill-function' value. Internally,
22795 ;; `org-comment-line-break-function' breaks the line.
22797 ;; `org-setup-filling' installs filling and auto-filling related
22798 ;; variables during `org-mode' initialization.
22800 (defun org-setup-filling ()
22801 (require 'org-element)
22802 ;; Prevent auto-fill from inserting unwanted new items.
22803 (when (boundp 'fill-nobreak-predicate)
22805 fill-nobreak-predicate
22807 (append fill-nobreak-predicate
22808 '(org-fill-line-break-nobreak-p
22809 org-fill-n-macro-as-item-nobreak-p
22810 org-fill-paragraph-with-timestamp-nobreak-p)))))
22811 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22812 (setq-local paragraph-start paragraph-ending)
22813 (setq-local paragraph-separate paragraph-ending))
22814 (setq-local fill-paragraph-function 'org-fill-paragraph)
22815 (setq-local auto-fill-inhibit-regexp nil)
22816 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22817 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22818 (setq-local comment-line-break-function 'org-comment-line-break-function))
22820 (defun org-fill-line-break-nobreak-p ()
22821 "Non-nil when a new line at point would create an Org line break."
22823 (skip-chars-backward "[ \t]")
22824 (skip-chars-backward "\\\\")
22825 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22827 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22828 "Non-nil when a new line at point would split a timestamp."
22829 (and (org-at-timestamp-p 'lax)
22830 (not (looking-at org-ts-regexp-both))))
22832 (defun org-fill-n-macro-as-item-nobreak-p ()
22833 "Non-nil when a new line at point would create a new list."
22834 ;; During export, a "n" macro followed by a dot or a closing
22835 ;; parenthesis can end up being parsed as a new list item.
22836 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22838 (declare-function message-in-body-p "message" ())
22839 (defvar orgtbl-line-start-regexp) ; From org-table.el
22840 (defun org-adaptive-fill-function ()
22841 "Compute a fill prefix for the current line.
22842 Return fill prefix, as a string, or nil if current line isn't
22843 meant to be filled. For convenience, if `adaptive-fill-regexp'
22844 matches in paragraphs or comments, use it."
22846 (when (derived-mode-p 'message-mode)
22848 (beginning-of-line)
22849 (cond ((not (message-in-body-p)) (throw 'exit nil))
22850 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22851 ((looking-at message-cite-prefix-regexp)
22852 (throw 'exit (match-string-no-properties 0)))
22853 ((looking-at org-outline-regexp)
22854 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22855 (org-with-wide-buffer
22856 (unless (org-at-heading-p)
22857 (let* ((p (line-beginning-position))
22858 (element (save-excursion
22859 (beginning-of-line)
22860 (org-element-at-point)))
22861 (type (org-element-type element))
22862 (post-affiliated (org-element-property :post-affiliated element)))
22863 (unless (< p post-affiliated)
22867 (beginning-of-line)
22868 (looking-at "[ \t]*")
22869 (concat (match-string 0) "# ")))
22870 (footnote-definition "")
22872 (make-string (org-list-item-body-column post-affiliated) ?\s))
22874 ;; Fill prefix is usually the same as the current line,
22875 ;; unless the paragraph is at the beginning of an item.
22876 (let ((parent (org-element-property :parent element)))
22878 (beginning-of-line)
22879 (cond ((eq (org-element-type parent) 'item)
22880 (make-string (org-list-item-body-column
22881 (org-element-property :begin parent))
22883 ((and adaptive-fill-regexp
22885 ;; `adaptive-fill-function' to let
22886 ;; `fill-context-prefix' handle
22887 ;; `adaptive-fill-regexp' variable.
22888 (let (adaptive-fill-function)
22889 (fill-context-prefix
22891 (org-element-property :end element)))))
22892 ((looking-at "[ \t]+") (match-string 0))
22895 ;; Only fill contents if P is within block boundaries.
22896 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22899 (cend (save-excursion
22900 (goto-char (org-element-property :end element))
22901 (skip-chars-backward " \r\t\n")
22902 (line-beginning-position))))
22903 (when (and (>= p cbeg) (< p cend))
22904 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22908 (declare-function message-goto-body "message" ())
22909 (defvar message-cite-prefix-regexp) ; From message.el
22911 (defun org-fill-element (&optional justify)
22912 "Fill element at point, when applicable.
22914 This function only applies to comment blocks, comments, example
22915 blocks and paragraphs. Also, as a special case, re-align table
22916 when point is at one.
22918 If JUSTIFY is non-nil (interactively, with prefix argument),
22919 justify as well. If `sentence-end-double-space' is non-nil, then
22920 period followed by one space does not end a sentence, so don't
22921 break a line there. The variable `fill-column' controls the
22924 For convenience, when point is at a plain list, an item or
22925 a footnote definition, try to fill the first paragraph within."
22926 (with-syntax-table org-mode-transpose-word-syntax-table
22927 ;; Move to end of line in order to get the first paragraph within
22928 ;; a plain list or a footnote definition.
22929 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22930 ;; First check if point is in a blank line at the beginning of
22931 ;; the buffer. In that case, ignore filling.
22932 (cl-case (org-element-type element)
22933 ;; Use major mode filling function is src blocks.
22934 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22935 ;; Align Org tables, leave table.el tables as-is.
22936 (table-row (org-table-align) t)
22938 (when (eq (org-element-property :type element) 'org)
22940 (goto-char (org-element-property :post-affiliated element))
22941 (org-table-align)))
22944 ;; Paragraphs may contain `line-break' type objects.
22945 (let ((beg (max (point-min)
22946 (org-element-property :contents-begin element)))
22947 (end (min (point-max)
22948 (org-element-property :contents-end element))))
22949 ;; Do nothing if point is at an affiliated keyword.
22950 (if (< (line-end-position) beg) t
22951 (when (derived-mode-p 'message-mode)
22952 ;; In `message-mode', do not fill following citation
22953 ;; in current paragraph nor text before message body.
22954 (let ((body-start (save-excursion (message-goto-body))))
22955 (when body-start (setq beg (max body-start beg))))
22956 (when (save-excursion
22958 (concat "^" message-cite-prefix-regexp) end t))
22959 (setq end (match-beginning 0))))
22960 ;; Fill paragraph, taking line breaks into account.
22963 (let ((cuts (list beg)))
22964 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22965 (when (eq 'line-break
22967 (save-excursion (backward-char)
22968 (org-element-context))))
22969 (push (point) cuts)))
22970 (dolist (c (delq end cuts))
22971 (fill-region-as-paragraph c end justify)
22974 ;; Contents of `comment-block' type elements should be
22975 ;; filled as plain text, but only if point is within block
22978 (let* ((case-fold-search t)
22979 (beg (save-excursion
22980 (goto-char (org-element-property :begin element))
22981 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22984 (end (save-excursion
22985 (goto-char (org-element-property :end element))
22986 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22987 (line-beginning-position))))
22988 (if (or (< (point) beg) (> (point) end)) t
22989 (fill-region-as-paragraph
22990 (save-excursion (end-of-line)
22991 (re-search-backward "^[ \t]*$" beg 'move)
22992 (line-beginning-position))
22993 (save-excursion (beginning-of-line)
22994 (re-search-forward "^[ \t]*$" end 'move)
22995 (line-beginning-position))
22999 (let ((begin (org-element-property :post-affiliated element))
23000 (end (org-element-property :end element)))
23001 (when (and (>= (point) begin) (<= (point) end))
23002 (let ((begin (save-excursion
23004 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23005 (progn (forward-line) (point))
23007 (end (save-excursion
23009 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23010 (1- (line-beginning-position))
23011 (skip-chars-backward " \r\t\n")
23012 (line-end-position)))))
23013 ;; Do not fill comments when at a blank line.
23014 (when (> end begin)
23017 (beginning-of-line)
23018 (looking-at "[ \t]*#")
23019 (let ((comment-prefix (match-string 0)))
23020 (goto-char (match-end 0))
23021 (if (looking-at adaptive-fill-regexp)
23022 (concat comment-prefix (match-string 0))
23023 (concat comment-prefix " "))))))
23025 (fill-region-as-paragraph begin end justify))))))
23027 ;; Ignore every other element.
23030 (defun org-fill-paragraph (&optional justify region)
23031 "Fill element at point, when applicable.
23033 This function only applies to comment blocks, comments, example
23034 blocks and paragraphs. Also, as a special case, re-align table
23035 when point is at one.
23037 For convenience, when point is at a plain list, an item or
23038 a footnote definition, try to fill the first paragraph within.
23040 If JUSTIFY is non-nil (interactively, with prefix argument),
23041 justify as well. If `sentence-end-double-space' is non-nil, then
23042 period followed by one space does not end a sentence, so don't
23043 break a line there. The variable `fill-column' controls the
23046 The REGION argument is non-nil if called interactively; in that
23047 case, if Transient Mark mode is enabled and the mark is active,
23048 fill each of the elements in the active region, instead of just
23049 filling the current element."
23050 (interactive (progn
23051 (barf-if-buffer-read-only)
23052 (list (if current-prefix-arg 'full) t)))
23054 ((and (derived-mode-p 'message-mode)
23055 (or (not (message-in-body-p))
23056 (save-excursion (move-beginning-of-line 1)
23057 (looking-at message-cite-prefix-regexp))))
23058 ;; First ensure filling is correct in message-mode.
23059 (let ((fill-paragraph-function
23060 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23061 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23062 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23063 (paragraph-separate
23064 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23065 (fill-paragraph nil)))
23066 ((and region transient-mark-mode mark-active
23067 (not (eq (region-beginning) (region-end))))
23068 (let ((origin (point-marker))
23069 (start (region-beginning)))
23072 (goto-char (region-end))
23073 (while (> (point) start)
23074 (org-backward-paragraph)
23075 (org-fill-element justify)))
23077 (set-marker origin nil))))
23078 (t (org-fill-element justify))))
23079 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23081 (defun org-auto-fill-function ()
23082 "Auto-fill function."
23083 ;; Check if auto-filling is meaningful.
23084 (let ((fc (current-fill-column)))
23085 (when (and fc (> (current-column) fc))
23086 (let* ((fill-prefix (org-adaptive-fill-function))
23087 ;; Enforce empty fill prefix, if required. Otherwise, it
23088 ;; will be computed again.
23089 (adaptive-fill-mode (not (equal fill-prefix ""))))
23090 (when fill-prefix (do-auto-fill))))))
23092 (defun org-comment-line-break-function (&optional soft)
23093 "Break line at point and indent, continuing comment if within one.
23094 The inserted newline is marked hard if variable
23095 `use-hard-newlines' is true, unless optional argument SOFT is
23097 (if soft (insert-and-inherit ?\n) (newline 1))
23098 (save-excursion (forward-char -1) (delete-horizontal-space))
23099 (delete-horizontal-space)
23100 (indent-to-left-margin)
23101 (insert-before-markers-and-inherit fill-prefix))
23104 ;;; Fixed Width Areas
23106 (defun org-toggle-fixed-width ()
23107 "Toggle fixed-width markup.
23109 Add or remove fixed-width markup on current line, whenever it
23110 makes sense. Return an error otherwise.
23112 If a region is active and if it contains only fixed-width areas
23113 or blank lines, remove all fixed-width markup in it. If the
23114 region contains anything else, convert all non-fixed-width lines
23115 to fixed-width ones.
23117 Blank lines at the end of the region are ignored unless the
23118 region only contains such lines."
23120 (if (not (org-region-active-p))
23123 ;; Remove fixed width marker only in a fixed-with element.
23125 ;; Add fixed width maker in paragraphs, in blank lines after
23126 ;; elements or at the beginning of a headline or an inlinetask,
23127 ;; and before any one-line elements (e.g., a clock).
23129 (beginning-of-line)
23130 (let* ((element (org-element-at-point))
23131 (type (org-element-type element)))
23133 ((and (eq type 'fixed-width)
23134 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23136 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23137 ((and (memq type '(babel-call clock comment diary-sexp headline
23138 horizontal-rule keyword paragraph
23140 (<= (org-element-property :post-affiliated element) (point)))
23141 (skip-chars-forward " \t")
23143 ((and (looking-at-p "[ \t]*$")
23144 (or (eq type 'inlinetask)
23146 (skip-chars-forward " \r\t\n")
23147 (<= (org-element-property :end element) (point)))))
23148 (delete-region (point) (line-end-position))
23151 (t (user-error "Cannot insert a fixed-width line here")))))
23153 (let* ((begin (save-excursion
23154 (goto-char (region-beginning))
23155 (line-beginning-position)))
23158 (goto-char (region-end))
23159 (unless (eolp) (beginning-of-line))
23160 (if (save-excursion (re-search-backward "\\S-" begin t))
23161 (progn (skip-chars-backward " \r\t\n") (point))
23167 (skip-chars-forward " \r\t\n")
23168 (when (eobp) (throw 'not-all-p nil))
23169 (while (< (point) end)
23170 (let ((element (org-element-at-point)))
23171 (if (eq (org-element-type element) 'fixed-width)
23172 (goto-char (org-element-property :end element))
23173 (throw 'not-all-p nil))))
23175 (if all-fixed-width-p
23178 (while (< (point) end)
23179 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23182 (if (= (line-end-position) (match-end 0)) 0 1)))
23184 (let ((min-ind (point-max)))
23185 ;; Find minimum indentation across all lines.
23188 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23191 (while (< (point) end)
23192 (unless (looking-at-p "[ \t]*$")
23193 (let ((ind (org-get-indentation)))
23194 (setq min-ind (min min-ind ind))
23195 (when (zerop ind) (throw 'zerop t))))
23197 ;; Loop over all lines and add fixed-width markup everywhere
23198 ;; but in fixed-width lines.
23201 (while (< (point) end)
23203 ((org-at-heading-p)
23206 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23209 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23210 (let* ((element (org-element-at-point))
23211 (element-end (org-element-property :end element)))
23212 (if (eq (org-element-type element) 'fixed-width)
23213 (progn (goto-char element-end)
23214 (skip-chars-backward " \r\t\n")
23216 (let ((limit (min end element-end)))
23217 (while (< (point) limit)
23218 (org-move-to-column min-ind t)
23220 (forward-line))))))
23222 (org-move-to-column min-ind t)
23224 (forward-line)))))))
23225 (set-marker end nil))))
23230 ;; Org comments syntax is quite complex. It requires the entire line
23231 ;; to be just a comment. Also, even with the right syntax at the
23232 ;; beginning of line, some elements (e.g., verse-block or
23233 ;; example-block) don't accept comments. Usual Emacs comment commands
23234 ;; cannot cope with those requirements. Therefore, Org replaces them.
23236 ;; Org still relies on `comment-dwim', but cannot trust
23237 ;; `comment-only-p'. So, `comment-region-function' and
23238 ;; `uncomment-region-function' both point
23239 ;; to`org-comment-or-uncomment-region'. Eventually,
23240 ;; `org-insert-comment' takes care of insertion of comments at the
23241 ;; beginning of line.
23243 ;; `org-setup-comments-handling' install comments related variables
23244 ;; during `org-mode' initialization.
23246 (defun org-setup-comments-handling ()
23248 (setq-local comment-use-syntax nil)
23249 (setq-local comment-start "# ")
23250 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23251 (setq-local comment-insert-comment-function 'org-insert-comment)
23252 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23253 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23255 (defun org-insert-comment ()
23256 "Insert an empty comment above current line.
23257 If the line is empty, insert comment at its beginning. When
23258 point is within a source block, comment according to the related
23260 (if (let ((element (org-element-at-point)))
23261 (and (eq (org-element-type element) 'src-block)
23263 (goto-char (org-element-property :post-affiliated element))
23264 (line-end-position))
23267 (goto-char (org-element-property :end element))
23268 (skip-chars-backward " \r\t\n")
23269 (line-beginning-position))
23271 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23272 (beginning-of-line)
23273 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23278 (defvar comment-empty-lines) ; From newcomment.el.
23279 (defun org-comment-or-uncomment-region (beg end &rest _)
23280 "Comment or uncomment each non-blank line in the region.
23281 Uncomment each non-blank line between BEG and END if it only
23282 contains commented lines. Otherwise, comment them. If region is
23283 strictly within a source block, use appropriate comment syntax."
23284 (if (let ((element (org-element-at-point)))
23285 (and (eq (org-element-type element) 'src-block)
23287 (goto-char (org-element-property :post-affiliated element))
23288 (line-end-position))
23290 (>= (save-excursion
23291 (goto-char (org-element-property :end element))
23292 (skip-chars-backward " \r\t\n")
23293 (line-beginning-position))
23295 ;; Translate region boundaries for the Org buffer to the source
23297 (let ((offset (- end beg)))
23300 (org-babel-do-in-edit-buffer
23301 (comment-or-uncomment-region (point) (+ offset (point))))))
23304 (narrow-to-region (save-excursion (goto-char beg)
23305 (skip-chars-forward " \r\t\n" end)
23306 (line-beginning-position))
23307 (save-excursion (goto-char end)
23308 (skip-chars-backward " \r\t\n" beg)
23309 (line-end-position)))
23311 ;; UNCOMMENTP is non-nil when every non blank line between
23312 ;; BEG and END is a comment.
23314 (goto-char (point-min))
23315 (while (and (not (eobp))
23316 (let ((element (org-element-at-point)))
23317 (and (eq (org-element-type element) 'comment)
23318 (goto-char (min (point-max)
23319 (org-element-property
23320 :end element)))))))
23323 ;; Only blank lines and comments in region: uncomment it.
23325 (goto-char (point-min))
23326 (while (not (eobp))
23327 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23328 (replace-match "" nil nil nil 1))
23330 ;; Comment each line in region.
23331 (let ((min-indent (point-max)))
23332 ;; First find the minimum indentation across all lines.
23334 (goto-char (point-min))
23335 (while (and (not (eobp)) (not (zerop min-indent)))
23336 (unless (looking-at "[ \t]*$")
23337 (setq min-indent (min min-indent (current-indentation))))
23339 ;; Then loop over all lines.
23341 (goto-char (point-min))
23342 (while (not (eobp))
23343 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23344 ;; Don't get fooled by invisible text (e.g. link path)
23345 ;; when moving to column MIN-INDENT.
23346 (let ((buffer-invisibility-spec nil))
23347 (org-move-to-column min-indent t))
23348 (insert comment-start))
23349 (forward-line)))))))))
23351 (defun org-comment-dwim (_arg)
23352 "Call `comment-dwim' within a source edit buffer if needed."
23354 (if (org-in-src-block-p)
23355 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23356 (call-interactively 'comment-dwim)))
23361 ;; This section contains tools to operate on timestamp objects, as
23362 ;; returned by, e.g. `org-element-context'.
23364 (defun org-timestamp--to-internal-time (timestamp &optional end)
23365 "Encode TIMESTAMP object into Emacs internal time.
23366 Use end of date range or time range when END is non-nil."
23367 (apply #'encode-time
23370 (lambda (prop) (or (org-element-property prop timestamp) 0))
23371 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23372 '(:minute-start :hour-start :day-start :month-start
23375 (defun org-timestamp-has-time-p (timestamp)
23376 "Non-nil when TIMESTAMP has a time specified."
23377 (org-element-property :hour-start timestamp))
23379 (defun org-timestamp-format (timestamp format &optional end utc)
23380 "Format a TIMESTAMP object into a string.
23382 FORMAT is a format specifier to be passed to
23383 `format-time-string'.
23385 When optional argument END is non-nil, use end of date-range or
23386 time-range, if possible.
23388 When optional argument UTC is non-nil, time will be expressed as
23390 (format-time-string
23391 format (org-timestamp--to-internal-time timestamp end)
23394 (defun org-timestamp-split-range (timestamp &optional end)
23395 "Extract a TIMESTAMP object from a date or time range.
23397 END, when non-nil, means extract the end of the range.
23398 Otherwise, extract its start.
23400 Return a new timestamp object."
23401 (let ((type (org-element-property :type timestamp)))
23402 (if (memq type '(active inactive diary)) timestamp
23403 (let ((split-ts (org-element-copy timestamp)))
23405 (org-element-put-property
23406 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23407 ;; Copy start properties over end properties if END is
23408 ;; non-nil. Otherwise, copy end properties over `start' ones.
23409 (let ((p-alist '((:minute-start . :minute-end)
23410 (:hour-start . :hour-end)
23411 (:day-start . :day-end)
23412 (:month-start . :month-end)
23413 (:year-start . :year-end))))
23414 (dolist (p-cell p-alist)
23415 (org-element-put-property
23417 (funcall (if end #'car #'cdr) p-cell)
23418 (org-element-property
23419 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23420 ;; Eventually refresh `:raw-value'.
23421 (org-element-put-property split-ts :raw-value nil)
23422 (org-element-put-property
23423 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23425 (defun org-timestamp-translate (timestamp &optional boundary)
23426 "Translate TIMESTAMP object to custom format.
23428 Format string is defined in `org-time-stamp-custom-formats',
23431 When optional argument BOUNDARY is non-nil, it is either the
23432 symbol `start' or `end'. In this case, only translate the
23433 starting or ending part of TIMESTAMP if it is a date or time
23434 range. Otherwise, translate both parts.
23436 Return timestamp as-is if `org-display-custom-times' is nil or if
23437 it has a `diary' type."
23438 (let ((type (org-element-property :type timestamp)))
23439 (if (or (not org-display-custom-times) (eq type 'diary))
23440 (org-element-interpret-data timestamp)
23441 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23442 org-time-stamp-custom-formats)))
23443 (if (and (not boundary) (memq type '(active-range inactive-range)))
23444 (concat (org-timestamp-format timestamp fmt)
23446 (org-timestamp-format timestamp fmt t))
23447 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23453 (defvar reftex-docstruct-symbol)
23456 (defun org-reftex-citation ()
23457 "Use reftex-citation to insert a citation into the buffer.
23458 This looks for a line like
23460 #+BIBLIOGRAPHY: foo plain option:-d
23462 and derives from it that foo.bib is the bibliography file relevant
23463 for this document. It then installs the necessary environment for RefTeX
23464 to work in this buffer and calls `reftex-citation' to insert a citation
23467 Export of such citations to both LaTeX and HTML is handled by the contributed
23468 package ox-bibtex by Taru Karttunen."
23470 (let ((reftex-docstruct-symbol 'org--rds)
23472 (org-with-wide-buffer
23473 (let ((case-fold-search t)
23474 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23475 (if (not (save-excursion
23476 (or (re-search-forward re nil t)
23477 (re-search-backward re nil t))))
23478 (user-error "No bibliography defined in file")
23479 (setq bib (concat (match-string 1) ".bib")
23480 org--rds (list (list 'bib bib))))))
23481 (call-interactively 'reftex-citation)))
23483 ;;;; Functions extending outline functionality
23485 (defun org-beginning-of-line (&optional n)
23486 "Go to the beginning of the current visible line.
23488 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23489 tags on the first attempt, and only move to after the tags when
23490 the cursor is already beyond the end of the headline.
23492 With argument N not nil or 1, move forward N - 1 lines first."
23494 (let ((origin (point))
23495 (special (pcase org-special-ctrl-a/e
23496 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23498 ;; First move to a visible line.
23499 (if (bound-and-true-p visual-line-mode)
23500 (beginning-of-visual-line n)
23501 (move-beginning-of-line n)
23502 ;; `move-beginning-of-line' may leave point after invisible
23503 ;; characters if line starts with such of these (e.g., with
23504 ;; a link at column 0). Really move to the beginning of the
23505 ;; current visible line.
23506 (beginning-of-line))
23508 ;; No special behavior. Point is already at the beginning of
23509 ;; a line, logical or visual.
23511 ;; `beginning-of-visual-line' left point before logical beginning
23512 ;; of line: point is at the beginning of a visual line. Bail
23514 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23515 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23516 ;; At a headline, special position is before the title, but
23517 ;; after any TODO keyword or priority cookie.
23518 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23519 (line-end-position)))
23521 (if (eq special 'reversed)
23522 (when (and (= origin bol) (eq last-command this-command))
23523 (goto-char refpos))
23524 (when (or (> origin refpos) (= origin bol))
23525 (goto-char refpos)))))
23526 ((and (looking-at org-list-full-item-re)
23527 (memq (org-element-type (save-match-data (org-element-at-point)))
23528 '(item plain-list)))
23529 ;; Set special position at first white space character after
23530 ;; bullet, and check-box, if any.
23531 (let ((after-bullet
23532 (let ((box (match-end 3)))
23533 (cond ((not box) (match-end 1))
23534 ((eq (char-after box) ?\s) (1+ box))
23536 (if (eq special 'reversed)
23537 (when (and (= (point) origin) (eq last-command this-command))
23538 (goto-char after-bullet))
23539 (when (or (> origin after-bullet) (= (point) origin))
23540 (goto-char after-bullet)))))
23541 ;; No special context. Point is already at beginning of line.
23544 (defun org-end-of-line (&optional n)
23545 "Go to the end of the line, but before ellipsis, if any.
23547 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23548 tags on the first attempt, and only move to after the tags when
23549 the cursor is already beyond the end of the headline.
23551 With argument N not nil or 1, move forward N - 1 lines first."
23553 (let ((origin (point))
23554 (special (pcase org-special-ctrl-a/e
23555 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23557 ;; First move to a visible line.
23558 (if (bound-and-true-p visual-line-mode)
23559 (beginning-of-visual-line n)
23560 (move-beginning-of-line n))
23562 ;; At a headline, with tags.
23565 (beginning-of-line)
23566 (let ((case-fold-search nil))
23567 (looking-at org-complex-heading-regexp)))
23569 (let ((tags (save-excursion
23570 (goto-char (match-beginning 5))
23571 (skip-chars-backward " \t")
23573 (visual-end (and (bound-and-true-p visual-line-mode)
23575 (end-of-visual-line)
23577 ;; If `end-of-visual-line' brings us before end of line or
23578 ;; even tags, i.e., the headline spans over multiple visual
23579 ;; lines, move there.
23580 (cond ((and visual-end
23581 (< visual-end tags)
23582 (<= origin visual-end))
23583 (goto-char visual-end))
23584 ((eq special 'reversed)
23585 (if (and (= origin (line-end-position))
23586 (eq this-command last-command))
23590 (if (or (< origin tags) (= origin (line-end-position)))
23593 ((bound-and-true-p visual-line-mode)
23594 (let ((bol (line-beginning-position)))
23595 (end-of-visual-line)
23596 ;; If `end-of-visual-line' gets us past the ellipsis at the
23597 ;; end of a line, backtrack and use `end-of-line' instead.
23598 (when (/= bol (line-beginning-position))
23601 (t (end-of-line)))))
23603 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23604 (define-key org-mode-map "\C-e" 'org-end-of-line)
23606 (defun org-backward-sentence (&optional _arg)
23607 "Go to beginning of sentence, or beginning of table field.
23608 This will call `backward-sentence' or `org-table-beginning-of-field',
23609 depending on context."
23611 (let* ((element (org-element-at-point))
23612 (contents-begin (org-element-property :contents-begin element))
23613 (table (org-element-lineage element '(table) t)))
23615 (> (point) contents-begin)
23616 (<= (point) (org-element-property :contents-end table)))
23617 (call-interactively #'org-table-beginning-of-field)
23619 (when (and contents-begin
23620 (< (point-min) contents-begin)
23621 (> (point) contents-begin))
23622 (narrow-to-region contents-begin
23623 (org-element-property :contents-end element)))
23624 (call-interactively #'backward-sentence)))))
23626 (defun org-forward-sentence (&optional _arg)
23627 "Go to end of sentence, or end of table field.
23628 This will call `forward-sentence' or `org-table-end-of-field',
23629 depending on context."
23631 (if (and (org-at-heading-p)
23632 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23634 (narrow-to-region (line-beginning-position) (line-end-position))
23635 (call-interactively #'forward-sentence))
23636 (let* ((element (org-element-at-point))
23637 (contents-end (org-element-property :contents-end element))
23638 (table (org-element-lineage element '(table) t)))
23640 (>= (point) (org-element-property :contents-begin table))
23641 (< (point) contents-end))
23642 (call-interactively #'org-table-end-of-field)
23644 (when (and contents-end
23645 (> (point-max) contents-end)
23646 ;; Skip blank lines between elements.
23647 (< (org-element-property :end element)
23648 (save-excursion (goto-char contents-end)
23649 (skip-chars-forward " \r\t\n"))))
23650 (narrow-to-region (org-element-property :contents-begin element)
23652 ;; End of heading is considered as the end of a sentence.
23653 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23654 (call-interactively #'forward-sentence)))))))
23656 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23657 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23659 (defun org-kill-line (&optional _arg)
23660 "Kill line, to tags or end of line."
23663 ((or (not org-special-ctrl-k)
23665 (not (org-at-heading-p)))
23666 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23667 org-ctrl-k-protect-subtree
23668 (or (eq org-ctrl-k-protect-subtree 'error)
23669 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23670 (user-error "C-k aborted as it would kill a hidden subtree"))
23671 (call-interactively
23672 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23673 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23674 (kill-region (point) (match-beginning 1))
23675 (org-set-tags nil t))
23676 (t (kill-region (point) (point-at-eol)))))
23678 (define-key org-mode-map "\C-k" 'org-kill-line)
23680 (defun org-yank (&optional arg)
23681 "Yank. If the kill is a subtree, treat it specially.
23682 This command will look at the current kill and check if is a single
23683 subtree, or a series of subtrees[1]. If it passes the test, and if the
23684 cursor is at the beginning of a line or after the stars of a currently
23685 empty headline, then the yank is handled specially. How exactly depends
23686 on the value of the following variables.
23688 `org-yank-folded-subtrees'
23689 By default, this variable is non-nil, which results in
23690 subtree(s) being folded after insertion, except if doing so
23691 would swallow text after the yanked text.
23693 `org-yank-adjusted-subtrees'
23694 When non-nil (the default value is nil), the subtree will be
23695 promoted or demoted in order to fit into the local outline tree
23696 structure, which means that the level will be adjusted so that it
23697 becomes the smaller one of the two *visible* surrounding headings.
23699 Any prefix to this command will cause `yank' to be called directly with
23700 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23702 plainly yank the text as it is.
23704 \[1] The test checks if the first non-white line is a heading
23705 and if there are no other headings with fewer stars."
23707 (org-yank-generic 'yank arg))
23709 (defun org-yank-generic (command arg)
23710 "Perform some yank-like command.
23712 This function implements the behavior described in the `org-yank'
23713 documentation. However, it has been generalized to work for any
23714 interactive command with similar behavior."
23716 ;; pretend to be command COMMAND
23717 (setq this-command command)
23720 (call-interactively command)
23722 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23723 (and (org-kill-is-subtree-p)
23725 (and (looking-at "[ \t]*$")
23728 (buffer-substring (point-at-bol) (point)))))))
23731 ((and subtreep org-yank-folded-subtrees)
23732 (let ((beg (point))
23734 (if (and subtreep org-yank-adjusted-subtrees)
23735 (org-paste-subtree nil nil 'for-yank)
23736 (call-interactively command))
23740 (when (and (bolp) subtreep
23741 (not (setq swallowp
23742 (org-yank-folding-would-swallow-text beg end))))
23743 (org-with-limited-levels
23744 (or (looking-at org-outline-regexp)
23745 (re-search-forward org-outline-regexp-bol end t))
23746 (while (and (< (point) end) (looking-at org-outline-regexp))
23747 (outline-hide-subtree)
23748 (org-cycle-show-empty-lines 'folded)
23749 (condition-case nil
23750 (outline-forward-same-level 1)
23751 (error (goto-char end))))))
23754 "Inserted text not folded because that would swallow text"))
23757 (skip-chars-forward " \t\n\r")
23758 (beginning-of-line 1)
23759 (push-mark beg 'nomsg)))
23760 ((and subtreep org-yank-adjusted-subtrees)
23761 (let ((beg (point-at-bol)))
23762 (org-paste-subtree nil nil 'for-yank)
23763 (push-mark beg 'nomsg)))
23765 (call-interactively command))))))
23767 (defun org-yank-folding-would-swallow-text (beg end)
23768 "Would hide-subtree at BEG swallow any text after END?"
23770 (org-with-limited-levels
23773 (when (or (looking-at org-outline-regexp)
23774 (re-search-forward org-outline-regexp-bol end t))
23775 (setq level (org-outline-level)))
23777 (skip-chars-forward " \t\r\n\v\f")
23779 (and (bolp) (looking-at-p org-outline-regexp)
23780 (<= (org-outline-level) level))))))))
23782 (define-key org-mode-map "\C-y" 'org-yank)
23784 (defun org-truely-invisible-p ()
23785 "Check if point is at a character currently not visible.
23786 This version does not only check the character property, but also
23788 (unless (bound-and-true-p visible-mode)
23789 (org-invisible-p)))
23791 (defun org-invisible-p2 ()
23792 "Check if point is at a character currently not visible.
23794 If the point is at EOL (and not at the beginning of a buffer too),
23795 move it back by one char before doing this check."
23797 (when (and (eolp) (not (bobp)))
23799 (org-invisible-p)))
23801 (defun org-back-to-heading (&optional invisible-ok)
23802 "Call `outline-back-to-heading', but provide a better error message."
23803 (condition-case nil
23804 (outline-back-to-heading invisible-ok)
23805 (error (error "Before first headline at position %d in buffer %s"
23806 (point) (current-buffer)))))
23808 (defun org-before-first-heading-p ()
23809 "Before first heading?"
23812 (null (re-search-backward org-outline-regexp-bol nil t))))
23814 (defun org-at-heading-p (&optional ignored)
23815 (outline-on-heading-p t))
23817 (defun org-in-commented-heading-p (&optional no-inheritance)
23818 "Non-nil if point is under a commented heading.
23819 This function also checks ancestors of the current headline,
23820 unless optional argument NO-INHERITANCE is non-nil."
23822 ((org-before-first-heading-p) nil)
23823 ((let ((headline (nth 4 (org-heading-components))))
23825 (let ((case-fold-search nil))
23826 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23828 (no-inheritance nil)
23830 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23832 (defun org-at-comment-p nil
23833 "Is cursor in a commented line?"
23836 (beginning-of-line)
23837 (looking-at "^[ \t]*# "))))
23839 (defun org-at-drawer-p nil
23840 "Is cursor at a drawer keyword?"
23842 (move-beginning-of-line 1)
23843 (looking-at org-drawer-regexp)))
23845 (defun org-at-block-p nil
23846 "Is cursor at a block keyword?"
23848 (move-beginning-of-line 1)
23849 (looking-at org-block-regexp)))
23851 (defun org-point-at-end-of-empty-headline ()
23852 "If point is at the end of an empty headline, return t, else nil.
23853 If the heading only contains a TODO keyword, it is still still considered
23855 (let ((case-fold-search nil))
23856 (and (looking-at "[ \t]*$")
23857 org-todo-line-regexp
23859 (beginning-of-line)
23860 (looking-at org-todo-line-regexp)
23861 (string= (match-string 3) "")))))
23863 (defun org-at-heading-or-item-p ()
23864 (or (org-at-heading-p) (org-at-item-p)))
23866 (defun org-at-target-p ()
23867 (or (org-in-regexp org-radio-target-regexp)
23868 (org-in-regexp org-target-regexp)))
23869 ;; Compatibility alias with Org versions < 7.8.03
23870 (defalias 'org-on-target-p 'org-at-target-p)
23872 (defun org-up-heading-all (arg)
23873 "Move to the heading line of which the present line is a subheading.
23874 This function considers both visible and invisible heading lines.
23875 With argument, move up ARG levels."
23876 (outline-up-heading arg t))
23878 (defun org-up-heading-safe ()
23879 "Move to the heading line of which the present line is a subheading.
23880 This version will not throw an error. It will return the level of the
23881 headline found, or nil if no higher level is found.
23883 Also, this function will be a lot faster than `outline-up-heading',
23884 because it relies on stars being the outline starters. This can really
23885 make a significant difference in outlines with very many siblings."
23886 (when (ignore-errors (org-back-to-heading t))
23887 (let ((level-up (1- (funcall outline-level))))
23888 (and (> level-up 0)
23889 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23890 (funcall outline-level)))))
23892 (defun org-first-sibling-p ()
23893 "Is this heading the first child of its parents?"
23895 (let ((re org-outline-regexp-bol)
23897 (unless (org-at-heading-p t)
23898 (user-error "Not at a heading"))
23899 (setq level (funcall outline-level))
23901 (if (not (re-search-backward re nil t))
23903 (setq l (funcall outline-level))
23906 (defun org-goto-sibling (&optional previous)
23907 "Goto the next sibling, even if it is invisible.
23908 When PREVIOUS is set, go to the previous sibling instead. Returns t
23909 when a sibling was found. When none is found, return nil and don't
23911 (let ((fun (if previous 're-search-backward 're-search-forward))
23913 (re org-outline-regexp-bol)
23915 (when (ignore-errors (org-back-to-heading t))
23916 (setq level (funcall outline-level))
23918 (or previous (forward-char 1))
23919 (while (funcall fun re nil t)
23920 (setq l (funcall outline-level))
23921 (when (< l level) (goto-char pos) (throw 'exit nil))
23922 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23926 (defun org-show-siblings ()
23927 "Show all siblings of the current headline."
23929 (while (org-goto-sibling) (org-flag-heading nil)))
23931 (while (org-goto-sibling 'previous)
23932 (org-flag-heading nil))))
23934 (defun org-goto-first-child ()
23935 "Goto the first child, even if it is invisible.
23936 Return t when a child was found. Otherwise don't move point and
23938 (let (level (pos (point)) (re org-outline-regexp-bol))
23939 (when (ignore-errors (org-back-to-heading t))
23940 (setq level (outline-level))
23942 (if (and (re-search-forward re nil t) (> (outline-level) level))
23943 (progn (goto-char (match-beginning 0)) t)
23944 (goto-char pos) nil))))
23946 (defun org-show-hidden-entry ()
23947 "Show an entry where even the heading is hidden."
23951 (defun org-flag-heading (flag &optional entry)
23952 "Flag the current heading. FLAG non-nil means make invisible.
23953 When ENTRY is non-nil, show the entire entry."
23955 (org-back-to-heading t)
23956 ;; Check if we should show the entire entry
23961 (and (outline-next-heading)
23962 (org-flag-heading nil))))
23963 (outline-flag-region (max (point-min) (1- (point)))
23964 (save-excursion (outline-end-of-heading) (point))
23967 (defun org-get-next-sibling ()
23968 "Move to next heading of the same level, and return point.
23969 If there is no such heading, return nil.
23970 This is like outline-next-sibling, but invisible headings are ok."
23971 (let ((level (funcall outline-level)))
23972 (outline-next-heading)
23973 (while (and (not (eobp)) (> (funcall outline-level) level))
23974 (outline-next-heading))
23975 (unless (or (eobp) (< (funcall outline-level) level))
23978 (defun org-get-last-sibling ()
23979 "Move to previous heading of the same level, and return point.
23980 If there is no such heading, return nil."
23981 (let ((opoint (point))
23982 (level (funcall outline-level)))
23983 (outline-previous-heading)
23984 (when (and (/= (point) opoint) (outline-on-heading-p t))
23985 (while (and (> (funcall outline-level) level)
23987 (outline-previous-heading))
23988 (unless (< (funcall outline-level) level)
23991 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23992 "Goto to the end of a subtree."
23993 ;; This contains an exact copy of the original function, but it uses
23994 ;; `org-back-to-heading', to make it work also in invisible
23995 ;; trees. And is uses an invisible-ok argument.
23996 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23997 ;; Furthermore, when used inside Org, finding the end of a large subtree
23998 ;; with many children and grandchildren etc, this can be much faster
23999 ;; than the outline version.
24000 (org-back-to-heading invisible-ok)
24002 (level (funcall outline-level)))
24003 (if (and (derived-mode-p 'org-mode) (< level 1000))
24004 ;; A true heading (not a plain list item), in Org
24005 ;; This means we can easily find the end by looking
24006 ;; only for the right number of stars. Using a regexp to do
24007 ;; this is so much faster than using a Lisp loop.
24008 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24010 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24011 ;; something else, do it the slow way
24012 (while (and (not (eobp))
24013 (or first (> (funcall outline-level) level)))
24015 (outline-next-heading)))
24017 (when (memq (preceding-char) '(?\n ?\^M))
24018 ;; Go to end of line before heading
24020 (when (memq (preceding-char) '(?\n ?\^M))
24021 ;; leave blank line before heading
24022 (forward-char -1)))))
24025 (defun org-end-of-meta-data (&optional full)
24026 "Skip planning line and properties drawer in current entry.
24027 When optional argument FULL is non-nil, also skip empty lines,
24028 clocking lines and regular drawers at the beginning of the
24030 (org-back-to-heading t)
24032 (when (looking-at-p org-planning-line-re) (forward-line))
24033 (when (looking-at org-property-drawer-re)
24034 (goto-char (match-end 0))
24036 (when (and full (not (org-at-heading-p)))
24038 (let ((end (save-excursion (outline-next-heading) (point)))
24039 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24040 (while (not (eobp))
24041 (cond ((looking-at-p org-drawer-regexp)
24042 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24045 ((looking-at-p re) (forward-line))
24046 (t (throw 'exit t))))))))
24048 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24049 "Move forward to the ARG'th subheading at same level as this one.
24050 Stop at the first and last subheadings of a superior heading.
24051 Normally this only looks at visible headings, but when INVISIBLE-OK is
24052 non-nil it will also look at invisible ones."
24054 (let ((backward? (and arg (< arg 0))))
24055 (if (org-before-first-heading-p)
24056 (if backward? (goto-char (point-min)) (outline-next-heading))
24057 (org-back-to-heading invisible-ok)
24058 (unless backward? (end-of-line)) ;do not match current headline
24059 (let ((level (- (match-end 0) (match-beginning 0) 1))
24060 (f (if backward? #'re-search-backward #'re-search-forward))
24061 (count (if arg (abs arg) 1))
24063 (while (and (> count 0)
24064 (funcall f org-outline-regexp-bol nil 'move))
24065 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24066 (cond ((< l level) (setq count 0))
24069 (not (org-invisible-p
24070 (line-beginning-position)))))
24072 (when (= l level) (setq result (point)))))))
24073 (goto-char result))
24074 (beginning-of-line))))
24076 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24077 "Move backward to the ARG'th subheading at same level as this one.
24078 Stop at the first and last subheadings of a superior heading."
24080 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24082 (defun org-next-visible-heading (arg)
24083 "Move to the next visible heading.
24085 This function wraps `outline-next-visible-heading' with
24086 `org-with-limited-levels' in order to skip over inline tasks and
24087 respect customization of `org-odd-levels-only'."
24089 (org-with-limited-levels
24090 (outline-next-visible-heading arg)))
24092 (defun org-previous-visible-heading (arg)
24093 "Move to the previous visible heading.
24095 This function wraps `outline-previous-visible-heading' with
24096 `org-with-limited-levels' in order to skip over inline tasks and
24097 respect customization of `org-odd-levels-only'."
24099 (org-with-limited-levels
24100 (outline-previous-visible-heading arg)))
24102 (defun org-next-block (arg &optional backward block-regexp)
24103 "Jump to the next block.
24105 With a prefix argument ARG, jump forward ARG many blocks.
24107 When BACKWARD is non-nil, jump to the previous block.
24109 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24110 Match data is set according to this regexp when the function
24113 Return point at beginning of the opening line of found block.
24114 Throw an error if no block is found."
24116 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24117 (case-fold-search t)
24118 (search-fn (if backward #'re-search-backward #'re-search-forward))
24122 (if backward (beginning-of-line) (end-of-line))
24123 (while (and (> count 0) (funcall search-fn re nil t))
24124 (let ((element (save-excursion
24125 (goto-char (match-beginning 0))
24126 (save-match-data (org-element-at-point)))))
24127 (when (and (memq (org-element-type element)
24128 '(center-block comment-block dynamic-block
24129 example-block export-block quote-block
24130 special-block src-block verse-block))
24131 (<= (match-beginning 0)
24132 (org-element-property :post-affiliated element)))
24133 (setq last-element element)
24136 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24137 (save-match-data (org-show-context)))
24139 (user-error "No %s code blocks" (if backward "previous" "further")))))
24141 (defun org-previous-block (arg &optional block-regexp)
24142 "Jump to the previous block.
24143 With a prefix argument ARG, jump backward ARG many source blocks.
24144 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24146 (org-next-block arg t block-regexp))
24148 (defun org-forward-paragraph ()
24149 "Move forward to beginning of next paragraph or equivalent.
24151 The function moves point to the beginning of the next visible
24152 structural element, which can be a paragraph, a table, a list
24153 item, etc. It also provides some special moves for convenience:
24155 - On an affiliated keyword, jump to the beginning of the
24157 - On an item or a footnote definition, move to the second
24158 element inside, if any.
24159 - On a table or a property drawer, jump after it.
24160 - On a verse or source block, stop after blank lines."
24163 (let* ((deactivate-mark nil)
24164 (element (org-element-at-point))
24165 (type (org-element-type element))
24166 (post-affiliated (org-element-property :post-affiliated element))
24167 (contents-begin (org-element-property :contents-begin element))
24168 (contents-end (org-element-property :contents-end element))
24169 (end (let ((end (org-element-property :end element)) (parent element))
24170 (while (and (setq parent (org-element-property :parent parent))
24171 (= (org-element-property :contents-end parent) end))
24172 (setq end (org-element-property :end parent)))
24174 (cond ((not element)
24175 (skip-chars-forward " \r\t\n")
24176 (or (eobp) (beginning-of-line)))
24177 ;; On affiliated keywords, move to element's beginning.
24178 ((< (point) post-affiliated)
24179 (goto-char post-affiliated))
24180 ;; At a table row, move to the end of the table. Similarly,
24181 ;; at a node property, move to the end of the property
24183 ((memq type '(node-property table-row))
24184 (goto-char (org-element-property
24185 :end (org-element-property :parent element))))
24186 ((memq type '(property-drawer table)) (goto-char end))
24187 ;; Consider blank lines as separators in verse and source
24188 ;; blocks to ease editing.
24189 ((memq type '(src-block verse-block))
24190 (when (eq type 'src-block)
24192 (save-excursion (goto-char end)
24193 (skip-chars-backward " \r\t\n")
24194 (line-beginning-position))))
24195 (beginning-of-line)
24196 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24197 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24199 (skip-chars-forward " \r\t\n")
24200 (if (= (point) contents-end) (goto-char end)
24201 (beginning-of-line))))
24202 ;; With no contents, just skip element.
24203 ((not contents-begin) (goto-char end))
24204 ;; If contents are invisible, skip the element altogether.
24205 ((org-invisible-p (line-end-position))
24208 (org-with-limited-levels (outline-next-visible-heading 1)))
24209 ;; At a plain list, make sure we move to the next item
24210 ;; instead of skipping the whole list.
24211 (plain-list (forward-char)
24212 (org-forward-paragraph))
24213 (otherwise (goto-char end))))
24214 ((>= (point) contents-end) (goto-char end))
24215 ((>= (point) contents-begin)
24216 ;; This can only happen on paragraphs and plain lists.
24218 (paragraph (goto-char end))
24219 ;; At a plain list, try to move to second element in
24220 ;; first item, if possible.
24221 (plain-list (end-of-line)
24222 (org-forward-paragraph))))
24223 ;; When contents start on the middle of a line (e.g. in
24224 ;; items and footnote definitions), try to reach first
24225 ;; element starting after current line.
24226 ((> (line-end-position) contents-begin)
24228 (org-forward-paragraph))
24229 (t (goto-char contents-begin))))))
24231 (defun org-backward-paragraph ()
24232 "Move backward to start of previous paragraph or equivalent.
24234 The function moves point to the beginning of the current
24235 structural element, which can be a paragraph, a table, a list
24236 item, etc., or to the beginning of the previous visible one if
24237 point is already there. It also provides some special moves for
24240 - On an affiliated keyword, jump to the first one.
24241 - On a table or a property drawer, move to its beginning.
24242 - On comment, example, export, src and verse blocks, stop
24243 before blank lines."
24246 (let* ((deactivate-mark nil)
24247 (element (org-element-at-point))
24248 (type (org-element-type element))
24249 (contents-end (org-element-property :contents-end element))
24250 (post-affiliated (org-element-property :post-affiliated element))
24251 (begin (org-element-property :begin element))
24252 (special? ;blocks handled specially
24253 (memq type '(comment-block example-block export-block src-block
24257 ;; These types have no proper contents. Fake line
24258 ;; below the block opening line as contents beginning.
24259 (save-excursion (goto-char begin) (line-beginning-position 2))
24260 (org-element-property :contents-begin element))))
24262 ((not element) (goto-char (point-min)))
24265 (org-backward-paragraph))
24266 ((<= (point) post-affiliated) (goto-char begin))
24267 ;; Special behavior: on a table or a property drawer, move to
24269 ((memq type '(node-property table-row))
24270 (goto-char (org-element-property
24271 :post-affiliated (org-element-property :parent element))))
24273 (if (<= (point) contents-begin) (goto-char post-affiliated)
24274 ;; Inside a verse block, see blank lines as paragraph
24276 (let ((origin (point)))
24277 (skip-chars-backward " \r\t\n" contents-begin)
24278 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24279 (skip-chars-forward " \r\t\n" origin)
24280 (if (= (point) origin) (goto-char contents-begin)
24281 (beginning-of-line))))))
24282 ((eq type 'paragraph) (goto-char contents-begin)
24283 ;; When at first paragraph in an item or a footnote definition,
24284 ;; move directly to beginning of line.
24285 (let ((parent-contents
24286 (org-element-property
24287 :contents-begin (org-element-property :parent element))))
24288 (when (and parent-contents (= parent-contents contents-begin))
24289 (beginning-of-line))))
24290 ;; At the end of a greater element, move to the beginning of
24291 ;; the last element within.
24292 ((and contents-end (>= (point) contents-end))
24293 (goto-char (1- contents-end))
24294 (org-backward-paragraph))
24295 (t (goto-char (or post-affiliated begin))))
24296 ;; Ensure we never leave point invisible.
24297 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24299 (defun org-forward-element ()
24300 "Move forward by one element.
24301 Move to the next element at the same level, when possible."
24303 (cond ((eobp) (user-error "Cannot move further down"))
24304 ((org-with-limited-levels (org-at-heading-p))
24305 (let ((origin (point)))
24306 (goto-char (org-end-of-subtree nil t))
24307 (unless (org-with-limited-levels (org-at-heading-p))
24309 (user-error "Cannot move further down"))))
24311 (let* ((elem (org-element-at-point))
24312 (end (org-element-property :end elem))
24313 (parent (org-element-property :parent elem)))
24314 (cond ((and parent (= (org-element-property :contents-end parent) end))
24315 (goto-char (org-element-property :end parent)))
24316 ((integer-or-marker-p end) (goto-char end))
24317 (t (message "No element at point")))))))
24319 (defun org-backward-element ()
24320 "Move backward by one element.
24321 Move to the previous element at the same level, when possible."
24323 (cond ((bobp) (user-error "Cannot move further up"))
24324 ((org-with-limited-levels (org-at-heading-p))
24325 ;; At a headline, move to the previous one, if any, or stay
24327 (let ((origin (point)))
24328 (org-with-limited-levels (org-backward-heading-same-level 1))
24329 ;; When current headline has no sibling above, move to its
24331 (when (= (point) origin)
24332 (or (org-with-limited-levels (org-up-heading-safe))
24333 (progn (goto-char origin)
24334 (user-error "Cannot move further up"))))))
24336 (let* ((elem (org-element-at-point))
24337 (beg (org-element-property :begin elem)))
24339 ;; Move to beginning of current element if point isn't
24341 ((null beg) (message "No element at point"))
24342 ((/= (point) beg) (goto-char beg))
24344 (skip-chars-backward " \r\t\n")
24346 (let ((prev (org-element-at-point)))
24347 (goto-char (org-element-property :begin prev))
24348 (while (and (setq prev (org-element-property :parent prev))
24349 (<= (org-element-property :end prev) beg))
24350 (goto-char (org-element-property :begin prev)))))))))))
24352 (defun org-up-element ()
24353 "Move to upper element."
24355 (if (org-with-limited-levels (org-at-heading-p))
24356 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24357 (let* ((elem (org-element-at-point))
24358 (parent (org-element-property :parent elem)))
24359 (if parent (goto-char (org-element-property :begin parent))
24360 (if (org-with-limited-levels (org-before-first-heading-p))
24361 (user-error "No surrounding element")
24362 (org-with-limited-levels (org-back-to-heading)))))))
24364 (defun org-down-element ()
24365 "Move to inner element."
24367 (let ((element (org-element-at-point)))
24369 ((memq (org-element-type element) '(plain-list table))
24370 (goto-char (org-element-property :contents-begin element))
24372 ((memq (org-element-type element) org-element-greater-elements)
24373 ;; If contents are hidden, first disclose them.
24374 (when (org-invisible-p (line-end-position)) (org-cycle))
24375 (goto-char (or (org-element-property :contents-begin element)
24376 (user-error "No content for this element"))))
24377 (t (user-error "No inner element")))))
24379 (defun org-drag-element-backward ()
24380 "Move backward element at point."
24382 (let ((elem (or (org-element-at-point)
24383 (user-error "No element at point"))))
24384 (if (eq (org-element-type elem) 'headline)
24385 ;; Preserve point when moving a whole tree, even if point was
24386 ;; on blank lines below the headline.
24387 (let ((offset (skip-chars-backward " \t\n")))
24388 (unwind-protect (org-move-subtree-up)
24389 (forward-char (- offset))))
24392 (goto-char (org-element-property :begin elem))
24393 (skip-chars-backward " \r\t\n")
24395 (let* ((beg (org-element-property :begin elem))
24396 (prev (org-element-at-point))
24398 (while (and (setq up (org-element-property :parent up))
24399 (<= (org-element-property :end up) beg))
24402 ;; Error out if no previous element or previous element is
24403 ;; a parent of the current one.
24404 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24405 (user-error "Cannot drag element backward")
24406 (let ((pos (point)))
24407 (org-element-swap-A-B prev-elem elem)
24408 (goto-char (+ (org-element-property :begin prev-elem)
24409 (- pos (org-element-property :begin elem))))))))))
24411 (defun org-drag-element-forward ()
24412 "Move forward element at point."
24414 (let* ((pos (point))
24415 (elem (or (org-element-at-point)
24416 (user-error "No element at point"))))
24417 (when (= (point-max) (org-element-property :end elem))
24418 (user-error "Cannot drag element forward"))
24419 (goto-char (org-element-property :end elem))
24420 (let ((next-elem (org-element-at-point)))
24421 (when (or (org-element-nested-p elem next-elem)
24422 (and (eq (org-element-type next-elem) 'headline)
24423 (not (eq (org-element-type elem) 'headline))))
24425 (user-error "Cannot drag element forward"))
24426 ;; Compute new position of point: it's shifted by NEXT-ELEM
24427 ;; body's length (without final blanks) and by the length of
24428 ;; blanks between ELEM and NEXT-ELEM.
24429 (let ((size-next (- (save-excursion
24430 (goto-char (org-element-property :end next-elem))
24431 (skip-chars-backward " \r\t\n")
24433 ;; Small correction if buffer doesn't end
24434 ;; with a newline character.
24435 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24436 (org-element-property :begin next-elem)))
24437 (size-blank (- (org-element-property :end elem)
24439 (goto-char (org-element-property :end elem))
24440 (skip-chars-backward " \r\t\n")
24443 (org-element-swap-A-B elem next-elem)
24444 (goto-char (+ pos size-next size-blank))))))
24446 (defun org-drag-line-forward (arg)
24447 "Drag the line at point ARG lines forward."
24449 (dotimes (_ (abs arg))
24450 (let ((c (current-column)))
24453 (beginning-of-line 2)
24454 (transpose-lines 1)
24455 (beginning-of-line 0))
24456 (transpose-lines 1)
24457 (beginning-of-line -1))
24458 (org-move-to-column c))))
24460 (defun org-drag-line-backward (arg)
24461 "Drag the line at point ARG lines backward."
24463 (org-drag-line-forward (- arg)))
24465 (defun org-mark-element ()
24466 "Put point at beginning of this element, mark at end.
24468 Interactively, if this command is repeated or (in Transient Mark
24469 mode) if the mark is active, it marks the next element after the
24470 ones already marked."
24472 (let (deactivate-mark)
24473 (if (and (called-interactively-p 'any)
24474 (or (and (eq last-command this-command) (mark t))
24475 (and transient-mark-mode mark-active)))
24479 (goto-char (org-element-property :end (org-element-at-point)))))
24480 (let ((element (org-element-at-point)))
24482 (push-mark (org-element-property :end element) t t)
24483 (goto-char (org-element-property :begin element))))))
24485 (defun org-narrow-to-element ()
24486 "Narrow buffer to current element."
24488 (let ((elem (org-element-at-point)))
24490 ((eq (car elem) 'headline)
24492 (org-element-property :begin elem)
24493 (org-element-property :end elem)))
24494 ((memq (car elem) org-element-greater-elements)
24496 (org-element-property :contents-begin elem)
24497 (org-element-property :contents-end elem)))
24500 (org-element-property :begin elem)
24501 (org-element-property :end elem))))))
24503 (defun org-transpose-element ()
24504 "Transpose current and previous elements, keeping blank lines between.
24505 Point is moved after both elements."
24507 (org-skip-whitespace)
24508 (let ((end (org-element-property :end (org-element-at-point))))
24509 (org-drag-element-backward)
24512 (defun org-unindent-buffer ()
24513 "Un-indent the visible part of the buffer.
24514 Relative indentation (between items, inside blocks, etc.) isn't
24517 (unless (eq major-mode 'org-mode)
24518 (user-error "Cannot un-indent a buffer not in Org mode"))
24519 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24522 (dolist (element (reverse contents))
24523 (if (memq (org-element-type element) '(headline section))
24524 (funcall unindent-tree (org-element-contents element))
24528 (org-element-property :begin element)
24529 (org-element-property :end element))
24530 (org-do-remove-indentation))))))))
24531 (funcall unindent-tree (org-element-contents parse-tree))))
24533 (defun org-show-children (&optional level)
24534 "Show all direct subheadings of this heading.
24535 Prefix arg LEVEL is how many levels below the current level
24536 should be shown. Default is enough to cause the following
24537 heading to appear."
24539 ;; If `orgstruct-mode' is active, use the slower version.
24540 (if orgstruct-mode (call-interactively #'outline-show-children)
24542 (org-back-to-heading t)
24543 (let* ((current-level (funcall outline-level))
24544 (max-level (org-get-valid-level
24546 (if level (prefix-numeric-value level) 1)))
24547 (end (save-excursion (org-end-of-subtree t t)))
24548 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24549 (past-first-child nil)
24550 ;; Make sure to skip inlinetasks.
24551 (re (format regexp-fmt
24554 ((not (featurep 'org-inlinetask)) "")
24555 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24557 (t (1- org-inlinetask-min-level))))))
24558 ;; Display parent heading.
24559 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24561 ;; Display children. First child may be deeper than expected
24562 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24563 ;; MAX-LEVEL accordingly.
24564 (while (re-search-forward re end t)
24565 (unless past-first-child
24566 (setq re (format regexp-fmt
24568 (max (funcall outline-level) max-level)))
24569 (setq past-first-child t))
24570 (outline-flag-region
24571 (line-end-position 0) (line-end-position) nil))))))
24573 (defun org-show-subtree ()
24574 "Show everything after this heading at deeper levels."
24576 (outline-flag-region
24579 (org-end-of-subtree t t))
24582 (defun org-show-entry ()
24583 "Show the body directly following this heading.
24584 Show the heading too, if it is currently invisible."
24588 (org-back-to-heading t)
24589 (outline-flag-region
24590 (max (point-min) (1- (point)))
24592 (if (re-search-forward
24593 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24594 (match-beginning 1)
24597 (org-cycle-hide-drawers 'children))))
24599 (defun org-make-options-regexp (kwds &optional extra)
24600 "Make a regular expression for keyword lines.
24601 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24602 when non-nil, is a regexp matching keywords names."
24603 (concat "^[ \t]*#\\+\\("
24605 (and extra (concat (and kwds "\\|") extra))
24606 "\\):[ \t]*\\(.*\\)"))
24608 ;;;; Integration with and fixes for other packages
24612 (defvar-local org-imenu-markers nil
24613 "All markers currently used by Imenu.")
24615 (defun org-imenu-new-marker (&optional pos)
24616 "Return a new marker for use by Imenu, and remember the marker."
24617 (let ((m (make-marker)))
24618 (move-marker m (or pos (point)))
24619 (push m org-imenu-markers)
24622 (defun org-imenu-get-tree ()
24623 "Produce the index for Imenu."
24624 (dolist (x org-imenu-markers) (move-marker x nil))
24625 (setq org-imenu-markers nil)
24626 (let* ((case-fold-search nil)
24627 (n org-imenu-depth)
24628 (re (concat "^" (org-get-limited-outline-regexp)))
24629 (subs (make-vector (1+ n) nil))
24631 m level head0 head)
24632 (org-with-wide-buffer
24633 (goto-char (point-max))
24634 (while (re-search-backward re nil t)
24635 (setq level (org-reduced-level (funcall outline-level)))
24636 (when (and (<= level n)
24637 (looking-at org-complex-heading-regexp)
24638 (setq head0 (match-string-no-properties 4)))
24639 (setq head (org-link-display-format head0)
24640 m (org-imenu-new-marker))
24641 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24642 (if (>= level last-level)
24643 (push (cons head m) (aref subs level))
24644 (push (cons head (aref subs (1+ level))) (aref subs level))
24645 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24646 (setq last-level level))))
24649 (eval-after-load "imenu"
24651 (add-hook 'imenu-after-jump-hook
24653 (when (derived-mode-p 'org-mode)
24654 (org-show-context 'org-goto))))))
24656 (defun org-link-display-format (s)
24657 "Replace links in string S with their description.
24658 If there is no description, use the link target."
24660 (replace-regexp-in-string
24661 org-bracket-link-analytic-regexp
24663 (if (match-end 5) (match-string 5 m)
24664 (concat (match-string 1 m) (match-string 3 m))))
24667 (defun org-toggle-link-display ()
24668 "Toggle the literal or descriptive display of links."
24670 (if org-descriptive-links
24671 (progn (org-remove-from-invisibility-spec '(org-link))
24672 (org-restart-font-lock)
24673 (setq org-descriptive-links nil))
24674 (progn (add-to-invisibility-spec '(org-link))
24675 (org-restart-font-lock)
24676 (setq org-descriptive-links t))))
24678 ;; Speedbar support
24680 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24681 "Overlay marking the agenda restriction line in speedbar.")
24682 (overlay-put org-speedbar-restriction-lock-overlay
24683 'face 'org-agenda-restriction-lock)
24684 (overlay-put org-speedbar-restriction-lock-overlay
24685 'help-echo "Agendas are currently limited to this item.")
24686 (delete-overlay org-speedbar-restriction-lock-overlay)
24688 (defun org-speedbar-set-agenda-restriction ()
24689 "Restrict future agenda commands to the location at point in speedbar.
24690 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24692 (require 'org-agenda)
24693 (let (p m tp np dir txt)
24695 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24697 (setq m (get-text-property p 'org-imenu-marker))
24698 (with-current-buffer (marker-buffer m)
24700 (org-agenda-set-restriction-lock 'subtree)))
24701 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24702 'speedbar-function 'speedbar-find-file))
24703 (setq tp (previous-single-property-change
24704 (1+ p) 'speedbar-function)
24705 np (next-single-property-change
24706 tp 'speedbar-function)
24707 dir (speedbar-line-directory)
24708 txt (buffer-substring-no-properties (or tp (point-min))
24709 (or np (point-max))))
24710 (with-current-buffer (find-file-noselect
24711 (let ((default-directory dir))
24712 (expand-file-name txt)))
24713 (unless (derived-mode-p 'org-mode)
24714 (user-error "Cannot restrict to non-Org mode file"))
24715 (org-agenda-set-restriction-lock 'file)))
24716 (t (user-error "Don't know how to restrict Org mode agenda")))
24717 (move-overlay org-speedbar-restriction-lock-overlay
24718 (point-at-bol) (point-at-eol))
24719 (setq current-prefix-arg nil)
24720 (org-agenda-maybe-redo)))
24722 (defvar speedbar-file-key-map)
24723 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24724 (eval-after-load "speedbar"
24726 (speedbar-add-supported-extension ".org")
24727 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24728 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24729 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24730 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24731 (add-hook 'speedbar-visiting-tag-hook
24732 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24734 ;;; Fixes and Hacks for problems with other packages
24736 (defun org--flyspell-object-check-p (element)
24737 "Non-nil when Flyspell can check object at point.
24738 ELEMENT is the element at point."
24739 (let ((object (save-excursion
24740 (when (looking-at-p "\\>") (backward-char))
24741 (org-element-context element))))
24742 (cl-case (org-element-type object)
24743 ;; Prevent checks in links due to keybinding conflict with
24745 ((code entity export-snippet inline-babel-call
24746 inline-src-block line-break latex-fragment link macro
24747 statistics-cookie target timestamp verbatim)
24749 (footnote-reference
24750 ;; Only in inline footnotes, within the definition.
24751 (and (eq (org-element-property :type object) 'inline)
24753 (goto-char (org-element-property :begin object))
24754 (search-forward ":" nil t 2))
24758 (defun org-mode-flyspell-verify ()
24759 "Function used for `flyspell-generic-check-word-predicate'."
24760 (if (org-at-heading-p)
24761 ;; At a headline or an inlinetask, check title only. This is
24762 ;; faster than relying on `org-element-at-point'.
24763 (and (save-excursion (beginning-of-line)
24764 (and (let ((case-fold-search t))
24765 (not (looking-at-p "\\*+ END[ \t]*$")))
24766 (let ((case-fold-search nil))
24767 (looking-at org-complex-heading-regexp))))
24768 (match-beginning 4)
24769 (>= (point) (match-beginning 4))
24770 (or (not (match-beginning 5))
24771 (< (point) (match-beginning 5))))
24772 (let* ((element (org-element-at-point))
24773 (post-affiliated (org-element-property :post-affiliated element)))
24775 ;; Ignore checks in all affiliated keywords but captions.
24776 ((< (point) post-affiliated)
24777 (and (save-excursion
24778 (beginning-of-line)
24779 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24780 (> (point) (match-end 0))
24781 (org--flyspell-object-check-p element)))
24782 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24783 ((let ((log (org-log-into-drawer)))
24785 (let ((drawer (org-element-lineage element '(drawer))))
24787 (eq (compare-strings
24789 (org-element-property :drawer-name drawer) nil nil t)
24793 (cl-case (org-element-type element)
24794 ((comment quote-section) t)
24796 ;; Allow checks between block markers, not on them.
24797 (and (> (line-beginning-position) post-affiliated)
24800 (skip-chars-forward " \r\t\n")
24801 (< (point) (org-element-property :end element)))))
24802 ;; Arbitrary list of keywords where checks are meaningful.
24803 ;; Make sure point is on the value part of the element.
24805 (and (member (org-element-property :key element)
24806 '("DESCRIPTION" "TITLE"))
24808 (search-backward ":" (line-beginning-position) t))))
24809 ;; Check is globally allowed in paragraphs verse blocks and
24810 ;; table rows (after affiliated keywords) but some objects
24811 ;; must not be affected.
24812 ((paragraph table-row verse-block)
24813 (let ((cbeg (org-element-property :contents-begin element))
24814 (cend (org-element-property :contents-end element)))
24815 (and cbeg (>= (point) cbeg) (< (point) cend)
24816 (org--flyspell-object-check-p element))))))))))
24817 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24819 (defun org-remove-flyspell-overlays-in (beg end)
24820 "Remove flyspell overlays in region."
24821 (and (bound-and-true-p flyspell-mode)
24822 (fboundp 'flyspell-delete-region-overlays)
24823 (flyspell-delete-region-overlays beg end)))
24825 (defvar flyspell-delayed-commands)
24826 (eval-after-load "flyspell"
24827 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24829 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24830 (eval-after-load "bookmark"
24831 '(if (boundp 'bookmark-after-jump-hook)
24832 ;; We can use the hook
24833 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24834 ;; Hook not available, use advice
24835 (defadvice bookmark-jump (after org-make-visible activate)
24836 "Make the position visible."
24837 (org-bookmark-jump-unhide))))
24839 ;; Make sure saveplace shows the location if it was hidden
24840 (eval-after-load "saveplace"
24841 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24842 "Make the position visible."
24843 (org-bookmark-jump-unhide)))
24845 ;; Make sure ecb shows the location if it was hidden
24846 (eval-after-load "ecb"
24847 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24848 "Make hierarchy visible when jumping into location from ECB tree buffer."
24849 (when (derived-mode-p 'org-mode)
24850 (org-show-context))))
24852 (defun org-bookmark-jump-unhide ()
24853 "Unhide the current position, to show the bookmark location."
24854 (and (derived-mode-p 'org-mode)
24855 (or (org-invisible-p)
24856 (save-excursion (goto-char (max (point-min) (1- (point))))
24857 (org-invisible-p)))
24858 (org-show-context 'bookmark-jump)))
24860 (defun org-mark-jump-unhide ()
24861 "Make the point visible with `org-show-context' after jumping to the mark."
24862 (when (and (derived-mode-p 'org-mode)
24864 (org-show-context 'mark-goto)))
24866 (eval-after-load "simple"
24867 '(defadvice pop-to-mark-command (after org-make-visible activate)
24868 "Make the point visible with `org-show-context'."
24869 (org-mark-jump-unhide)))
24871 (eval-after-load "simple"
24872 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24873 "Make the point visible with `org-show-context'."
24874 (org-mark-jump-unhide)))
24876 (eval-after-load "simple"
24877 '(defadvice pop-global-mark (after org-make-visible activate)
24878 "Make the point visible with `org-show-context'."
24879 (org-mark-jump-unhide)))
24881 ;; Make session.el ignore our circular variable
24882 (defvar session-globals-exclude)
24883 (eval-after-load "session"
24884 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24890 (run-hooks 'org-load-hook)
24892 ;;; org.el ends here