Move `org-completing-read' into "org-macs.el"
[org-mode.git] / lisp / org.el
blob99eba2da3f44c9469ea35a9172a9b243453fbcc7
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp) ;Silence byte-compiler
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (eval-and-compile
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'."))
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
717 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
722 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
723 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
724 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
725 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
726 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
727 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
728 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
729 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
730 (const :tag "C man: Support for links to manpages in Org mode" org-man)
731 (const :tag "C mew: Links to Mew folders/messages" org-mew)
732 (const :tag "C mtags: Support for muse-like tags" org-mtags)
733 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
734 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
735 (const :tag "C registry: A registry for Org links" org-registry)
736 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
737 (const :tag "C secretary: Team management with org-mode" org-secretary)
738 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
739 (const :tag "C toc: Table of contents for Org buffer" org-toc)
740 (const :tag "C track: Keep up with Org mode development" org-track)
741 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
742 (const :tag "C vm: Links to VM folders/messages" org-vm)
743 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
744 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
745 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
747 (defvar org-export-registered-backends) ; From ox.el.
748 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
749 (declare-function org-export-backend-name "ox" (backend) t)
750 (defcustom org-export-backends '(ascii html icalendar latex odt)
751 "List of export back-ends that should be always available.
753 If a description starts with <C>, the file is not part of Emacs
754 and loading it will require that you have downloaded and properly
755 installed the Org mode distribution.
757 Unlike to `org-modules', libraries in this list will not be
758 loaded along with Org, but only once the export framework is
759 needed.
761 This variable needs to be set before org.el is loaded. If you
762 need to make a change while Emacs is running, use the customize
763 interface or run the following code, where VAL stands for the new
764 value of the variable, after updating it:
766 (progn
767 (setq org-export-registered-backends
768 (cl-remove-if-not
769 (lambda (backend)
770 (let ((name (org-export-backend-name backend)))
771 (or (memq name val)
772 (catch \\='parentp
773 (dolist (b val)
774 (and (org-export-derived-backend-p b name)
775 (throw \\='parentp t)))))))
776 org-export-registered-backends))
777 (let ((new-list (mapcar #\\='org-export-backend-name
778 org-export-registered-backends)))
779 (dolist (backend val)
780 (cond
781 ((not (load (format \"ox-%s\" backend) t t))
782 (message \"Problems while trying to load export back-end \\=`%s\\='\"
783 backend))
784 ((not (memq backend new-list)) (push backend new-list))))
785 (set-default \\='org-export-backends new-list)))
787 Adding a back-end to this list will also pull the back-end it
788 depends on, if any."
789 :group 'org
790 :group 'org-export
791 :version "26.1"
792 :package-version '(Org . "9.0")
793 :initialize 'custom-initialize-set
794 :set (lambda (var val)
795 (if (not (featurep 'ox)) (set-default var val)
796 ;; Any back-end not required anymore (not present in VAL and not
797 ;; a parent of any back-end in the new value) is removed from the
798 ;; list of registered back-ends.
799 (setq org-export-registered-backends
800 (cl-remove-if-not
801 (lambda (backend)
802 (let ((name (org-export-backend-name backend)))
803 (or (memq name val)
804 (catch 'parentp
805 (dolist (b val)
806 (and (org-export-derived-backend-p b name)
807 (throw 'parentp t)))))))
808 org-export-registered-backends))
809 ;; Now build NEW-LIST of both new back-ends and required
810 ;; parents.
811 (let ((new-list (mapcar #'org-export-backend-name
812 org-export-registered-backends)))
813 (dolist (backend val)
814 (cond
815 ((not (load (format "ox-%s" backend) t t))
816 (message "Problems while trying to load export back-end `%s'"
817 backend))
818 ((not (memq backend new-list)) (push backend new-list))))
819 ;; Set VAR to that list with fixed dependencies.
820 (set-default var new-list))))
821 :type '(set :greedy t
822 (const :tag " ascii Export buffer to ASCII format" ascii)
823 (const :tag " beamer Export buffer to Beamer presentation" beamer)
824 (const :tag " html Export buffer to HTML format" html)
825 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
826 (const :tag " latex Export buffer to LaTeX format" latex)
827 (const :tag " man Export buffer to MAN format" man)
828 (const :tag " md Export buffer to Markdown format" md)
829 (const :tag " odt Export buffer to ODT format" odt)
830 (const :tag " org Export buffer to Org format" org)
831 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
832 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
833 (const :tag "C deck Export buffer to deck.js presentations" deck)
834 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
835 (const :tag "C groff Export buffer to Groff format" groff)
836 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
837 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
838 (const :tag "C s5 Export buffer to s5 presentations" s5)
839 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
841 (eval-after-load 'ox
842 '(dolist (backend org-export-backends)
843 (condition-case nil (require (intern (format "ox-%s" backend)))
844 (error (message "Problems while trying to load export back-end `%s'"
845 backend)))))
847 (defcustom org-support-shift-select nil
848 "Non-nil means make shift-cursor commands select text when possible.
849 \\<org-mode-map>\
851 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
852 start selecting a region, or enlarge regions started in this way.
853 In Org mode, in special contexts, these same keys are used for
854 other purposes, important enough to compete with shift selection.
855 Org tries to balance these needs by supporting `shift-select-mode'
856 outside these special contexts, under control of this variable.
858 The default of this variable is nil, to avoid confusing behavior. Shifted
859 cursor keys will then execute Org commands in the following contexts:
860 - on a headline, changing TODO state (left/right) and priority (up/down)
861 - on a time stamp, changing the time
862 - in a plain list item, changing the bullet type
863 - in a property definition line, switching between allowed values
864 - in the BEGIN line of a clock table (changing the time block).
865 Outside these contexts, the commands will throw an error.
867 When this variable is t and the cursor is not in a special
868 context, Org mode will support shift-selection for making and
869 enlarging regions. To make this more effective, the bullet
870 cycling will no longer happen anywhere in an item line, but only
871 if the cursor is exactly on the bullet.
873 If you set this variable to the symbol `always', then the keys
874 will not be special in headlines, property lines, and item lines,
875 to make shift selection work there as well. If this is what you
876 want, you can use the following alternative commands:
877 `\\[org-todo]' and `\\[org-priority]' \
878 to change TODO state and priority,
879 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
880 can be used to switch TODO sets,
881 `\\[org-ctrl-c-minus]' to cycle item bullet types,
882 and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up."
886 :group 'org
887 :type '(choice
888 (const :tag "Never" nil)
889 (const :tag "When outside special context" t)
890 (const :tag "Everywhere except timestamps" always)))
892 (defcustom org-loop-over-headlines-in-active-region nil
893 "Shall some commands act upon headlines in the active region?
895 When set to t, some commands will be performed in all headlines
896 within the active region.
898 When set to `start-level', some commands will be performed in all
899 headlines within the active region, provided that these headlines
900 are of the same level than the first one.
902 When set to a string, those commands will be performed on the
903 matching headlines within the active region. Such string must be
904 a tags/property/todo match as it is used in the agenda tags view.
906 The list of commands is: `org-schedule', `org-deadline',
907 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
908 `org-archive-to-archive-sibling'. The archiving commands skip
909 already archived entries."
910 :type '(choice (const :tag "Don't loop" nil)
911 (const :tag "All headlines in active region" t)
912 (const :tag "In active region, headlines at the same level than the first one" start-level)
913 (string :tag "Tags/Property/Todo matcher"))
914 :version "24.1"
915 :group 'org-todo
916 :group 'org-archive)
918 (defgroup org-startup nil
919 "Options concerning startup of Org mode."
920 :tag "Org Startup"
921 :group 'org)
923 (defcustom org-startup-folded t
924 "Non-nil means entering Org mode will switch to OVERVIEW.
926 This can also be configured on a per-file basis by adding one of
927 the following lines anywhere in the buffer:
929 #+STARTUP: fold (or `overview', this is equivalent)
930 #+STARTUP: nofold (or `showall', this is equivalent)
931 #+STARTUP: content
932 #+STARTUP: showeverything
934 Set `org-agenda-inhibit-startup' to a non-nil value if you want
935 to ignore this option when Org opens agenda files for the first
936 time."
937 :group 'org-startup
938 :type '(choice
939 (const :tag "nofold: show all" nil)
940 (const :tag "fold: overview" t)
941 (const :tag "content: all headlines" content)
942 (const :tag "show everything, even drawers" showeverything)))
944 (defcustom org-startup-truncated t
945 "Non-nil means entering Org mode will set `truncate-lines'.
946 This is useful since some lines containing links can be very long and
947 uninteresting. Also tables look terrible when wrapped.
949 The variable `org-startup-truncated' allows to configure
950 truncation for Org mode different to the other modes that use the
951 variable `truncate-lines' and as a shortcut instead of putting
952 the variable `truncate-lines' into the `org-mode-hook'. If one
953 wants to configure truncation for Org mode not statically but
954 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
955 the variable `truncate-lines' has to be used because in such a
956 case it is too late to set the variable `org-startup-truncated'."
957 :group 'org-startup
958 :type 'boolean)
960 (defcustom org-startup-indented nil
961 "Non-nil means turn on `org-indent-mode' on startup.
962 This can also be configured on a per-file basis by adding one of
963 the following lines anywhere in the buffer:
965 #+STARTUP: indent
966 #+STARTUP: noindent"
967 :group 'org-structure
968 :type '(choice
969 (const :tag "Not" nil)
970 (const :tag "Globally (slow on startup in large files)" t)))
972 (defcustom org-use-sub-superscripts t
973 "Non-nil means interpret \"_\" and \"^\" for display.
975 If you want to control how Org exports those characters, see
976 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
977 used to be an alias for `org-export-with-sub-superscripts' in
978 Org <8.0, it is not anymore.
980 When this option is turned on, you can use TeX-like syntax for
981 sub- and superscripts within the buffer. Several characters after
982 \"_\" or \"^\" will be considered as a single item - so grouping
983 with {} is normally not needed. For example, the following things
984 will be parsed as single sub- or superscripts:
986 10^24 or 10^tau several digits will be considered 1 item.
987 10^-12 or 10^-tau a leading sign with digits or a word
988 x^2-y^3 will be read as x^2 - y^3, because items are
989 terminated by almost any nonword/nondigit char.
990 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
992 Still, ambiguity is possible. So when in doubt, use {} to enclose
993 the sub/superscript. If you set this variable to the symbol `{}',
994 the braces are *required* in order to trigger interpretations as
995 sub/superscript. This can be helpful in documents that need \"_\"
996 frequently in plain text."
997 :group 'org-startup
998 :version "24.4"
999 :package-version '(Org . "8.0")
1000 :type '(choice
1001 (const :tag "Always interpret" t)
1002 (const :tag "Only with braces" {})
1003 (const :tag "Never interpret" nil)))
1005 (defcustom org-startup-with-beamer-mode nil
1006 "Non-nil means turn on `org-beamer-mode' on startup.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1010 #+STARTUP: beamer"
1011 :group 'org-startup
1012 :version "24.1"
1013 :type 'boolean)
1015 (defcustom org-startup-align-all-tables nil
1016 "Non-nil means align all tables when visiting a file.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1019 #+STARTUP: align
1020 #+STARTUP: noalign"
1021 :group 'org-startup
1022 :type 'boolean)
1024 (defcustom org-startup-shrink-all-tables nil
1025 "Non-nil means shrink all table columns with a width cookie.
1026 This can also be configured on a per-file basis by adding one of
1027 the following lines anywhere in the buffer:
1028 #+STARTUP: shrink"
1029 :group 'org-startup
1030 :type 'boolean
1031 :version "27.1"
1032 :package-version '(Org . "9.2")
1033 :safe #'booleanp)
1035 (defcustom org-startup-with-inline-images nil
1036 "Non-nil means show inline images when loading a new Org file.
1037 This can also be configured on a per-file basis by adding one of
1038 the following lines anywhere in the buffer:
1039 #+STARTUP: inlineimages
1040 #+STARTUP: noinlineimages"
1041 :group 'org-startup
1042 :version "24.1"
1043 :type 'boolean)
1045 (defcustom org-startup-with-latex-preview nil
1046 "Non-nil means preview LaTeX fragments when loading a new Org file.
1048 This can also be configured on a per-file basis by adding one of
1049 the following lines anywhere in the buffer:
1050 #+STARTUP: latexpreview
1051 #+STARTUP: nolatexpreview"
1052 :group 'org-startup
1053 :version "24.4"
1054 :package-version '(Org . "8.0")
1055 :type 'boolean)
1057 (defcustom org-insert-mode-line-in-empty-file nil
1058 "Non-nil means insert the first line setting Org mode in empty files.
1059 When the function `org-mode' is called interactively in an empty file, this
1060 normally means that the file name does not automatically trigger Org mode.
1061 To ensure that the file will always be in Org mode in the future, a
1062 line enforcing Org mode will be inserted into the buffer, if this option
1063 has been set."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-replace-disputed-keys nil
1068 "Non-nil means use alternative key bindings for some keys.
1069 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1070 These keys are also used by other packages like shift-selection-mode'
1071 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1072 If you want to use Org mode together with one of these other modes,
1073 or more generally if you would like to move some Org mode commands to
1074 other keys, set this variable and configure the keys with the variable
1075 `org-disputed-keys'.
1077 This option is only relevant at load-time of Org mode, and must be set
1078 *before* org.el is loaded. Changing it requires a restart of Emacs to
1079 become effective."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defcustom org-use-extra-keys nil
1084 "Non-nil means use extra key sequence definitions for certain commands.
1085 This happens automatically if `window-system' is nil. This
1086 variable lets you do the same manually. You must set it before
1087 loading Org."
1088 :group 'org-startup
1089 :type 'boolean)
1091 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1093 (defcustom org-disputed-keys
1094 '(([(shift up)] . [(meta p)])
1095 ([(shift down)] . [(meta n)])
1096 ([(shift left)] . [(meta -)])
1097 ([(shift right)] . [(meta +)])
1098 ([(control shift right)] . [(meta shift +)])
1099 ([(control shift left)] . [(meta shift -)]))
1100 "Keys for which Org mode and other modes compete.
1101 This is an alist, cars are the default keys, second element specifies
1102 the alternative to use when `org-replace-disputed-keys' is t.
1104 Keys can be specified in any syntax supported by `define-key'.
1105 The value of this option takes effect only at Org mode startup,
1106 therefore you'll have to restart Emacs to apply it after changing."
1107 :group 'org-startup
1108 :type 'alist)
1110 (defun org-key (key)
1111 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1112 Or return the original if not disputed."
1113 (when org-replace-disputed-keys
1114 (let* ((nkey (key-description key))
1115 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1116 org-disputed-keys)))
1117 (setq key (if x (cdr x) key))))
1118 key)
1120 (defun org-defkey (keymap key def)
1121 "Define a key, possibly translated, as returned by `org-key'."
1122 (define-key keymap (org-key key) def))
1124 (defcustom org-ellipsis nil
1125 "The ellipsis to use in the Org mode outline.
1127 When nil, just use the standard three dots. When a non-empty string,
1128 use that string instead.
1130 The change affects only Org mode (which will then use its own display table).
1131 Changing this requires executing `\\[org-mode]' in a buffer to become
1132 effective."
1133 :group 'org-startup
1134 :type '(choice (const :tag "Default" nil)
1135 (string :tag "String" :value "...#"))
1136 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1138 (defvar org-display-table nil
1139 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1141 (defgroup org-keywords nil
1142 "Keywords in Org mode."
1143 :tag "Org Keywords"
1144 :group 'org)
1146 (defcustom org-closed-keep-when-no-todo nil
1147 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1148 :group 'org-todo
1149 :group 'org-keywords
1150 :version "24.4"
1151 :package-version '(Org . "8.0")
1152 :type 'boolean)
1154 (defgroup org-structure nil
1155 "Options concerning the general structure of Org files."
1156 :tag "Org Structure"
1157 :group 'org)
1159 (defgroup org-reveal-location nil
1160 "Options about how to make context of a location visible."
1161 :tag "Org Reveal Location"
1162 :group 'org-structure)
1164 (defcustom org-show-context-detail '((agenda . local)
1165 (bookmark-jump . lineage)
1166 (isearch . lineage)
1167 (default . ancestors))
1168 "Alist between context and visibility span when revealing a location.
1170 \\<org-mode-map>Some actions may move point into invisible
1171 locations. As a consequence, Org always expose a neighborhood
1172 around point. How much is shown depends on the initial action,
1173 or context. Valid contexts are
1175 agenda when exposing an entry from the agenda
1176 org-goto when using the command `org-goto' (`\\[org-goto]')
1177 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1178 tags-tree when constructing a sparse tree based on tags matches
1179 link-search when exposing search matches associated with a link
1180 mark-goto when exposing the jump goal of a mark
1181 bookmark-jump when exposing a bookmark location
1182 isearch when exiting from an incremental search
1183 default default for all contexts not set explicitly
1185 Allowed visibility spans are
1187 minimal show current headline; if point is not on headline,
1188 also show entry
1190 local show current headline, entry and next headline
1192 ancestors show current headline and its direct ancestors; if
1193 point is not on headline, also show entry
1195 lineage show current headline, its direct ancestors and all
1196 their children; if point is not on headline, also show
1197 entry and first child
1199 tree show current headline, its direct ancestors and all
1200 their children; if point is not on headline, also show
1201 entry and all children
1203 canonical show current headline, its direct ancestors along with
1204 their entries and children; if point is not located on
1205 the headline, also show current entry and all children
1207 As special cases, a nil or t value means show all contexts in
1208 `minimal' or `canonical' view, respectively.
1210 Some views can make displayed information very compact, but also
1211 make it harder to edit the location of the match. In such
1212 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1213 more context."
1214 :group 'org-reveal-location
1215 :version "26.1"
1216 :package-version '(Org . "9.0")
1217 :type '(choice
1218 (const :tag "Canonical" t)
1219 (const :tag "Minimal" nil)
1220 (repeat :greedy t :tag "Individual contexts"
1221 (cons
1222 (choice :tag "Context"
1223 (const agenda)
1224 (const org-goto)
1225 (const occur-tree)
1226 (const tags-tree)
1227 (const link-search)
1228 (const mark-goto)
1229 (const bookmark-jump)
1230 (const isearch)
1231 (const default))
1232 (choice :tag "Detail level"
1233 (const minimal)
1234 (const local)
1235 (const ancestors)
1236 (const lineage)
1237 (const tree)
1238 (const canonical))))))
1240 (defcustom org-indirect-buffer-display 'other-window
1241 "How should indirect tree buffers be displayed?
1243 This applies to indirect buffers created with the commands
1244 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1246 Valid values are:
1247 current-window Display in the current window
1248 other-window Just display in another window.
1249 dedicated-frame Create one new frame, and re-use it each time.
1250 new-frame Make a new frame each time. Note that in this case
1251 previously-made indirect buffers are kept, and you need to
1252 kill these buffers yourself."
1253 :group 'org-structure
1254 :group 'org-agenda-windows
1255 :type '(choice
1256 (const :tag "In current window" current-window)
1257 (const :tag "In current frame, other window" other-window)
1258 (const :tag "Each time a new frame" new-frame)
1259 (const :tag "One dedicated frame" dedicated-frame)))
1261 (defcustom org-use-speed-commands nil
1262 "Non-nil means activate single letter commands at beginning of a headline.
1263 This may also be a function to test for appropriate locations where speed
1264 commands should be active.
1266 For example, to activate speed commands when the point is on any
1267 star at the beginning of the headline, you can do this:
1269 (setq org-use-speed-commands
1270 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1271 :group 'org-structure
1272 :type '(choice
1273 (const :tag "Never" nil)
1274 (const :tag "At beginning of headline stars" t)
1275 (function)))
1277 (defcustom org-speed-commands-user nil
1278 "Alist of additional speed commands.
1279 This list will be checked before `org-speed-commands-default'
1280 when the variable `org-use-speed-commands' is non-nil
1281 and when the cursor is at the beginning of a headline.
1282 The car if each entry is a string with a single letter, which must
1283 be assigned to `self-insert-command' in the global map.
1284 The cdr is either a command to be called interactively, a function
1285 to be called, or a form to be evaluated.
1286 An entry that is just a list with a single string will be interpreted
1287 as a descriptive headline that will be added when listing the speed
1288 commands in the Help buffer using the `?' speed command."
1289 :group 'org-structure
1290 :type '(repeat :value ("k" . ignore)
1291 (choice :value ("k" . ignore)
1292 (list :tag "Descriptive Headline" (string :tag "Headline"))
1293 (cons :tag "Letter and Command"
1294 (string :tag "Command letter")
1295 (choice
1296 (function)
1297 (sexp))))))
1299 (defcustom org-bookmark-names-plist
1300 '(:last-capture "org-capture-last-stored"
1301 :last-refile "org-refile-last-stored"
1302 :last-capture-marker "org-capture-last-stored-marker")
1303 "Names for bookmarks automatically set by some Org commands.
1304 This can provide strings as names for a number of bookmarks Org sets
1305 automatically. The following keys are currently implemented:
1306 :last-capture
1307 :last-capture-marker
1308 :last-refile
1309 When a key does not show up in the property list, the corresponding bookmark
1310 is not set."
1311 :group 'org-structure
1312 :type 'plist)
1314 (defgroup org-cycle nil
1315 "Options concerning visibility cycling in Org mode."
1316 :tag "Org Cycle"
1317 :group 'org-structure)
1319 (defcustom org-cycle-skip-children-state-if-no-children t
1320 "Non-nil means skip CHILDREN state in entries that don't have any."
1321 :group 'org-cycle
1322 :type 'boolean)
1324 (defcustom org-cycle-max-level nil
1325 "Maximum level which should still be subject to visibility cycling.
1326 Levels higher than this will, for cycling, be treated as text, not a headline.
1327 When `org-odd-levels-only' is set, a value of N in this variable actually
1328 means 2N-1 stars as the limiting headline.
1329 When nil, cycle all levels.
1330 Note that the limiting level of cycling is also influenced by
1331 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1332 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1333 than its value."
1334 :group 'org-cycle
1335 :type '(choice
1336 (const :tag "No limit" nil)
1337 (integer :tag "Maximum level")))
1339 (defcustom org-hide-block-startup nil
1340 "Non-nil means entering Org mode will fold all blocks.
1341 This can also be set in on a per-file basis with
1343 #+STARTUP: hideblocks
1344 #+STARTUP: showblocks"
1345 :group 'org-startup
1346 :group 'org-cycle
1347 :type 'boolean)
1349 (defcustom org-cycle-global-at-bob nil
1350 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1352 This makes it possible to do global cycling without having to use `S-TAB'
1353 or `\\[universal-argument] TAB'. For this special case to work, the first \
1354 line of the buffer
1355 must not be a headline -- it may be empty or some other text.
1357 When used in this way, `org-cycle-hook' is disabled temporarily to make
1358 sure the cursor stays at the beginning of the buffer.
1360 When this option is nil, don't do anything special at the beginning of
1361 the buffer."
1362 :group 'org-cycle
1363 :type 'boolean)
1365 (defcustom org-cycle-level-after-item/entry-creation t
1366 "Non-nil means cycle entry level or item indentation in new empty entries.
1368 When the cursor is at the end of an empty headline, i.e., with only stars
1369 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1370 and then all possible ancestor states, before returning to the original state.
1371 This makes data entry extremely fast: M-RET to create a new headline,
1372 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1374 When the cursor is at the end of an empty plain list item, one TAB will
1375 make it a subitem, two or more tabs will back up to make this an item
1376 higher up in the item hierarchy."
1377 :group 'org-cycle
1378 :type 'boolean)
1380 (defcustom org-cycle-emulate-tab t
1381 "Where should `org-cycle' emulate TAB.
1382 nil Never
1383 white Only in completely white lines
1384 whitestart Only at the beginning of lines, before the first non-white char
1385 t Everywhere except in headlines
1386 exc-hl-bol Everywhere except at the start of a headline
1387 If TAB is used in a place where it does not emulate TAB, the current subtree
1388 visibility is cycled."
1389 :group 'org-cycle
1390 :type '(choice (const :tag "Never" nil)
1391 (const :tag "Only in completely white lines" white)
1392 (const :tag "Before first char in a line" whitestart)
1393 (const :tag "Everywhere except in headlines" t)
1394 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1396 (defcustom org-cycle-separator-lines 2
1397 "Number of empty lines needed to keep an empty line between collapsed trees.
1398 If you leave an empty line between the end of a subtree and the following
1399 headline, this empty line is hidden when the subtree is folded.
1400 Org mode will leave (exactly) one empty line visible if the number of
1401 empty lines is equal or larger to the number given in this variable.
1402 So the default 2 means at least 2 empty lines after the end of a subtree
1403 are needed to produce free space between a collapsed subtree and the
1404 following headline.
1406 If the number is negative, and the number of empty lines is at least -N,
1407 all empty lines are shown.
1409 Special case: when 0, never leave empty lines in collapsed view."
1410 :group 'org-cycle
1411 :type 'integer)
1412 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1414 (defcustom org-pre-cycle-hook nil
1415 "Hook that is run before visibility cycling is happening.
1416 The function(s) in this hook must accept a single argument which indicates
1417 the new state that will be set right after running this hook. The
1418 argument is a symbol. Before a global state change, it can have the values
1419 `overview', `content', or `all'. Before a local state change, it can have
1420 the values `folded', `children', or `subtree'."
1421 :group 'org-cycle
1422 :type 'hook)
1424 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1425 org-cycle-hide-drawers
1426 org-cycle-show-empty-lines
1427 org-optimize-window-after-visibility-change)
1428 "Hook that is run after `org-cycle' has changed the buffer visibility.
1429 The function(s) in this hook must accept a single argument which indicates
1430 the new state that was set by the most recent `org-cycle' command. The
1431 argument is a symbol. After a global state change, it can have the values
1432 `overview', `contents', or `all'. After a local state change, it can have
1433 the values `folded', `children', or `subtree'."
1434 :group 'org-cycle
1435 :type 'hook
1436 :version "26.1"
1437 :package-version '(Org . "8.3"))
1439 (defgroup org-edit-structure nil
1440 "Options concerning structure editing in Org mode."
1441 :tag "Org Edit Structure"
1442 :group 'org-structure)
1444 (defcustom org-odd-levels-only nil
1445 "Non-nil means skip even levels and only use odd levels for the outline.
1446 This has the effect that two stars are being added/taken away in
1447 promotion/demotion commands. It also influences how levels are
1448 handled by the exporters.
1449 Changing it requires restart of `font-lock-mode' to become effective
1450 for fontification also in regions already fontified.
1451 You may also set this on a per-file basis by adding one of the following
1452 lines to the buffer:
1454 #+STARTUP: odd
1455 #+STARTUP: oddeven"
1456 :group 'org-edit-structure
1457 :group 'org-appearance
1458 :type 'boolean)
1460 (defcustom org-adapt-indentation t
1461 "Non-nil means adapt indentation to outline node level.
1463 When this variable is set, Org assumes that you write outlines by
1464 indenting text in each node to align with the headline (after the
1465 stars). The following issues are influenced by this variable:
1467 - The indentation is increased by one space in a demotion
1468 command, and decreased by one in a promotion command. However,
1469 in the latter case, if shifting some line in the entry body
1470 would alter document structure (e.g., insert a new headline),
1471 indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented
1474 when this variable is set. When nil, they will not be indented.
1476 - TAB indents a line relative to current level. The lines below
1477 a headline will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and
1480 removing space characters. See also `org-indent.el' which does
1481 level-dependent indentation in a virtual way, i.e. at display
1482 time in Emacs."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-special-ctrl-a/e nil
1487 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1489 When t, `C-a' will bring back the cursor to the beginning of the
1490 headline text, i.e. after the stars and after a possible TODO
1491 keyword. In an item, this will be the position after bullet and
1492 check-box, if any. When the cursor is already at that position,
1493 another `C-a' will bring it to the beginning of the line.
1495 `C-e' will jump to the end of the headline, ignoring the presence
1496 of tags in the headline. A second `C-e' will then jump to the
1497 true end of the line, after any tags. This also means that, when
1498 this variable is non-nil, `C-e' also will never jump beyond the
1499 end of the heading of a folded section, i.e. not after the
1500 ellipses.
1502 When set to the symbol `reversed', the first `C-a' or `C-e' works
1503 normally, going to the true line boundary first. Only a directly
1504 following, identical keypress will bring the cursor to the
1505 special positions.
1507 This may also be a cons cell where the behavior for `C-a' and
1508 `C-e' is set separately."
1509 :group 'org-edit-structure
1510 :type '(choice
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet and before tags first" t)
1513 (const :tag "reversed: true line boundary first" reversed)
1514 (cons :tag "Set C-a and C-e separately"
1515 (choice :tag "Special C-a"
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet first" t)
1518 (const :tag "reversed: before stars/bullet first" reversed))
1519 (choice :tag "Special C-e"
1520 (const :tag "off" nil)
1521 (const :tag "on: before tags first" t)
1522 (const :tag "reversed: after tags first" reversed)))))
1523 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1525 (defcustom org-special-ctrl-k nil
1526 "Non-nil means `C-k' will behave specially in headlines.
1527 When nil, `C-k' will call the default `kill-line' command.
1528 When t, the following will happen while the cursor is in the headline:
1530 - When the cursor is at the beginning of a headline, kill the entire
1531 line and possible the folded subtree below the line.
1532 - When in the middle of the headline text, kill the headline up to the tags.
1533 - When after the headline text, kill the tags."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-ctrl-k-protect-subtree nil
1538 "Non-nil means, do not delete a hidden subtree with C-k.
1539 When set to the symbol `error', simply throw an error when C-k is
1540 used to kill (part-of) a headline that has hidden text behind it.
1541 Any other non-nil value will result in a query to the user, if it is
1542 OK to kill that hidden subtree. When nil, kill without remorse."
1543 :group 'org-edit-structure
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Do not protect hidden subtrees" nil)
1547 (const :tag "Protect hidden subtrees with a security query" t)
1548 (const :tag "Never kill a hidden subtree with C-k" error)))
1550 (defcustom org-special-ctrl-o t
1551 "Non-nil means, make `C-o' insert a row in tables."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-catch-invisible-edits nil
1556 "Check if in invisible region before inserting or deleting a character.
1557 Valid values are:
1559 nil Do not check, so just do invisible edits.
1560 error Throw an error and do nothing.
1561 show Make point visible, and do the requested edit.
1562 show-and-error Make point visible, then throw an error and abort the edit.
1563 smart Make point visible, and do insertion/deletion if it is
1564 adjacent to visible text and the change feels predictable.
1565 Never delete a previously invisible character or add in the
1566 middle or right after an invisible region. Basically, this
1567 allows insertion and backward-delete right before ellipses.
1568 FIXME: maybe in this case we should not even show?"
1569 :group 'org-edit-structure
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Do not check" nil)
1573 (const :tag "Throw error when trying to edit" error)
1574 (const :tag "Unhide, but do not do the edit" show-and-error)
1575 (const :tag "Show invisible part and do the edit" show)
1576 (const :tag "Be smart and do the right thing" smart)))
1578 (defcustom org-yank-folded-subtrees t
1579 "Non-nil means when yanking subtrees, fold them.
1580 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1581 it starts with a heading and all other headings in it are either children
1582 or siblings, then fold all the subtrees. However, do this only if no
1583 text after the yank would be swallowed into a folded tree by this action."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-yank-adjusted-subtrees nil
1588 "Non-nil means when yanking subtrees, adjust the level.
1589 With this setting, `org-paste-subtree' is used to insert the subtree, see
1590 this function for details."
1591 :group 'org-edit-structure
1592 :type 'boolean)
1594 (defcustom org-M-RET-may-split-line '((default . t))
1595 "Non-nil means M-RET will split the line at the cursor position.
1596 When nil, it will go to the end of the line before making a
1597 new line.
1598 You may also set this option in a different way for different
1599 contexts. Valid contexts are:
1601 headline when creating a new headline
1602 item when creating a new item
1603 table in a table field
1604 default the value to be used for all contexts not explicitly
1605 customized"
1606 :group 'org-structure
1607 :group 'org-table
1608 :type '(choice
1609 (const :tag "Always" t)
1610 (const :tag "Never" nil)
1611 (repeat :greedy t :tag "Individual contexts"
1612 (cons
1613 (choice :tag "Context"
1614 (const headline)
1615 (const item)
1616 (const table)
1617 (const default))
1618 (boolean)))))
1621 (defcustom org-insert-heading-respect-content nil
1622 "Non-nil means insert new headings after the current subtree.
1623 \\<org-mode-map>
1624 When nil, the new heading is created directly after the current line.
1625 The commands `\\[org-insert-heading-respect-content]' and \
1626 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1627 for the duration of the command."
1628 :group 'org-structure
1629 :type 'boolean)
1631 (defcustom org-blank-before-new-entry '((heading . auto)
1632 (plain-list-item . auto))
1633 "Should `org-insert-heading' leave a blank line before new heading/item?
1634 The value is an alist, with `heading' and `plain-list-item' as CAR,
1635 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1636 which case Org will look at the surrounding headings/items and try to
1637 make an intelligent decision whether to insert a blank line or not."
1638 :group 'org-edit-structure
1639 :type '(list
1640 (cons (const heading)
1641 (choice (const :tag "Never" nil)
1642 (const :tag "Always" t)
1643 (const :tag "Auto" auto)))
1644 (cons (const plain-list-item)
1645 (choice (const :tag "Never" nil)
1646 (const :tag "Always" t)
1647 (const :tag "Auto" auto)))))
1649 (defcustom org-insert-heading-hook nil
1650 "Hook being run after inserting a new heading."
1651 :group 'org-edit-structure
1652 :type 'hook)
1654 (defcustom org-enable-fixed-width-editor t
1655 "Non-nil means lines starting with \":\" are treated as fixed-width.
1656 This currently only means they are never auto-wrapped.
1657 When nil, such lines will be treated like ordinary lines."
1658 :group 'org-edit-structure
1659 :type 'boolean)
1661 (defcustom org-goto-auto-isearch t
1662 "Non-nil means typing characters in `org-goto' starts incremental search.
1663 When nil, you can use these keybindings to navigate the buffer:
1665 q Quit the org-goto interface
1666 n Go to the next visible heading
1667 p Go to the previous visible heading
1668 f Go one heading forward on same level
1669 b Go one heading backward on same level
1670 u Go one heading up"
1671 :group 'org-edit-structure
1672 :type 'boolean)
1674 (defgroup org-sparse-trees nil
1675 "Options concerning sparse trees in Org mode."
1676 :tag "Org Sparse Trees"
1677 :group 'org-structure)
1679 (defcustom org-highlight-sparse-tree-matches t
1680 "Non-nil means highlight all matches that define a sparse tree.
1681 The highlights will automatically disappear the next time the buffer is
1682 changed by an edit command."
1683 :group 'org-sparse-trees
1684 :type 'boolean)
1686 (defcustom org-remove-highlights-with-change t
1687 "Non-nil means any change to the buffer will remove temporary highlights.
1688 \\<org-mode-map>\
1689 Such highlights are created by `org-occur' and `org-clock-display'.
1690 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1691 to get rid of the highlights.
1692 The highlights created by `org-toggle-latex-fragment' always need
1693 `\\[org-toggle-latex-fragment]' to be removed."
1694 :group 'org-sparse-trees
1695 :group 'org-time
1696 :type 'boolean)
1698 (defcustom org-occur-case-fold-search t
1699 "Non-nil means `org-occur' should be case-insensitive.
1700 If set to `smart' the search will be case-insensitive only if it
1701 doesn't specify any upper case character."
1702 :group 'org-sparse-trees
1703 :version "26.1"
1704 :type '(choice
1705 (const :tag "Case-sensitive" nil)
1706 (const :tag "Case-insensitive" t)
1707 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1709 (defcustom org-occur-hook '(org-first-headline-recenter)
1710 "Hook that is run after `org-occur' has constructed a sparse tree.
1711 This can be used to recenter the window to show as much of the structure
1712 as possible."
1713 :group 'org-sparse-trees
1714 :type 'hook)
1716 (defgroup org-imenu-and-speedbar nil
1717 "Options concerning imenu and speedbar in Org mode."
1718 :tag "Org Imenu and Speedbar"
1719 :group 'org-structure)
1721 (defcustom org-imenu-depth 2
1722 "The maximum level for Imenu access to Org headlines.
1723 This also applied for speedbar access."
1724 :group 'org-imenu-and-speedbar
1725 :type 'integer)
1727 (defgroup org-table nil
1728 "Options concerning tables in Org mode."
1729 :tag "Org Table"
1730 :group 'org)
1732 (defcustom org-self-insert-cluster-for-undo nil
1733 "Non-nil means cluster self-insert commands for undo when possible.
1734 If this is set, then, like in the Emacs command loop, 20 consecutive
1735 characters will be undone together.
1736 This is configurable, because there is some impact on typing performance."
1737 :group 'org-table
1738 :type 'boolean)
1740 (defcustom org-table-tab-recognizes-table.el t
1741 "Non-nil means TAB will automatically notice a table.el table.
1742 When it sees such a table, it moves point into it and - if necessary -
1743 calls `table-recognize-table'."
1744 :group 'org-table-editing
1745 :type 'boolean)
1747 (defgroup org-link nil
1748 "Options concerning links in Org mode."
1749 :tag "Org Link"
1750 :group 'org)
1752 (defvar-local org-link-abbrev-alist-local nil
1753 "Buffer-local version of `org-link-abbrev-alist', which see.
1754 The value of this is taken from the #+LINK lines.")
1756 (defcustom org-link-parameters
1757 '(("doi" :follow org--open-doi-link)
1758 ("elisp" :follow org--open-elisp-link)
1759 ("file" :complete org-file-complete-link)
1760 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1761 ("help" :follow org--open-help-link)
1762 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1763 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1764 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1765 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1766 ("shell" :follow org--open-shell-link))
1767 "An alist of properties that defines all the links in Org mode.
1768 The key in each association is a string of the link type.
1769 Subsequent optional elements make up a p-list of link properties.
1771 :follow - A function that takes the link path as an argument.
1773 :export - A function that takes the link path, description and
1774 export-backend as arguments.
1776 :store - A function responsible for storing the link. See the
1777 function `org-store-link-functions'.
1779 :complete - A function that inserts a link with completion. The
1780 function takes one optional prefix arg.
1782 :face - A face for the link, or a function that returns a face.
1783 The function takes one argument which is the link path. The
1784 default face is `org-link'.
1786 :mouse-face - The mouse-face. The default is `highlight'.
1788 :display - `full' will not fold the link in descriptive
1789 display. Default is `org-link'.
1791 :help-echo - A string or function that takes (window object position)
1792 as arguments and returns a string.
1794 :keymap - A keymap that is active on the link. The default is
1795 `org-mouse-map'.
1797 :htmlize-link - A function for the htmlize-link. Defaults
1798 to (list :uri \"type:path\")
1800 :activate-func - A function to run at the end of font-lock
1801 activation. The function must accept (link-start link-end path bracketp)
1802 as arguments."
1803 :group 'org-link
1804 :type '(alist :tag "Link display parameters"
1805 :value-type plist)
1806 :version "26.1"
1807 :package-version '(Org . "9.1"))
1809 (defun org-link-get-parameter (type key)
1810 "Get TYPE link property for KEY.
1811 TYPE is a string and KEY is a plist keyword."
1812 (plist-get
1813 (cdr (assoc type org-link-parameters))
1814 key))
1816 (defun org-link-set-parameters (type &rest parameters)
1817 "Set link TYPE properties to PARAMETERS.
1818 PARAMETERS should be :key val pairs."
1819 (let ((data (assoc type org-link-parameters)))
1820 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1821 (push (cons type parameters) org-link-parameters)
1822 (org-make-link-regexps)
1823 (org-element-update-syntax))))
1825 (defun org-link-types ()
1826 "Return a list of known link types."
1827 (mapcar #'car org-link-parameters))
1829 (defcustom org-link-abbrev-alist nil
1830 "Alist of link abbreviations.
1831 The car of each element is a string, to be replaced at the start of a link.
1832 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1833 links in Org buffers can have an optional tag after a double colon, e.g.,
1835 [[linkkey:tag][description]]
1837 The `linkkey' must be a single word, starting with a letter, followed
1838 by letters, numbers, `-' or `_'.
1840 If REPLACE is a string, the tag will simply be appended to create the link.
1841 If the string contains \"%s\", the tag will be inserted there. If the string
1842 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1843 at that point (see the function `url-hexify-string'). If the string contains
1844 the specifier \"%(my-function)\", then the custom function `my-function' will
1845 be invoked: this function takes the tag as its only argument and must return
1846 a string.
1848 REPLACE may also be a function that will be called with the tag as the
1849 only argument to create the link, which should be returned as a string.
1851 See the manual for examples."
1852 :group 'org-link
1853 :type '(repeat
1854 (cons
1855 (string :tag "Protocol")
1856 (choice
1857 (string :tag "Format")
1858 (function)))))
1860 (defcustom org-descriptive-links t
1861 "Non-nil means Org will display descriptive links.
1862 E.g. [[http://orgmode.org][Org website]] will be displayed as
1863 \"Org Website\", hiding the link itself and just displaying its
1864 description. When set to nil, Org will display the full links
1865 literally.
1867 You can interactively set the value of this variable by calling
1868 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1869 :group 'org-link
1870 :type 'boolean)
1872 (defcustom org-link-file-path-type 'adaptive
1873 "How the path name in file links should be stored.
1874 Valid values are:
1876 relative Relative to the current directory, i.e. the directory of the file
1877 into which the link is being inserted.
1878 absolute Absolute path, if possible with ~ for home directory.
1879 noabbrev Absolute path, no abbreviation of home directory.
1880 adaptive Use relative path for files in the current directory and sub-
1881 directories of it. For other files, use an absolute path."
1882 :group 'org-link
1883 :type '(choice
1884 (const relative)
1885 (const absolute)
1886 (const noabbrev)
1887 (const adaptive)))
1889 (defvaralias 'org-activate-links 'org-highlight-links)
1890 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1891 "Types of links that should be highlighted in Org files.
1893 This is a list of symbols, each one of them leading to the
1894 highlighting of a certain link type.
1896 You can still open links that are not highlighted.
1898 In principle, it does not hurt to turn on highlighting for all
1899 link types. There may be a small gain when turning off unused
1900 link types. The types are:
1902 bracket The recommended [[link][description]] or [[link]] links with hiding.
1903 angle Links in angular brackets that may contain whitespace like
1904 <bbdb:Carsten Dominik>.
1905 plain Plain links in normal text, no whitespace, like http://google.com.
1906 radio Text that is matched by a radio target, see manual for details.
1907 tag Tag settings in a headline (link to tag search).
1908 date Time stamps (link to calendar).
1909 footnote Footnote labels.
1911 If you set this variable during an Emacs session, use `org-mode-restart'
1912 in the Org buffer so that the change takes effect."
1913 :group 'org-link
1914 :group 'org-appearance
1915 :type '(set :greedy t
1916 (const :tag "Double bracket links" bracket)
1917 (const :tag "Angular bracket links" angle)
1918 (const :tag "Plain text links" plain)
1919 (const :tag "Radio target matches" radio)
1920 (const :tag "Tags" tag)
1921 (const :tag "Timestamps" date)
1922 (const :tag "Footnotes" footnote)))
1924 (defcustom org-make-link-description-function nil
1925 "Function to use for generating link descriptions from links.
1926 This function must take two parameters: the first one is the
1927 link, the second one is the description generated by
1928 `org-insert-link'. The function should return the description to
1929 use."
1930 :group 'org-link
1931 :type '(choice (const nil) (function)))
1933 (defgroup org-link-store nil
1934 "Options concerning storing links in Org mode."
1935 :tag "Org Store Link"
1936 :group 'org-link)
1938 (defcustom org-url-hexify-p t
1939 "When non-nil, hexify URL when creating a link."
1940 :type 'boolean
1941 :version "24.3"
1942 :group 'org-link-store)
1944 (defcustom org-email-link-description-format "Email %c: %.30s"
1945 "Format of the description part of a link to an email or usenet message.
1946 The following %-escapes will be replaced by corresponding information:
1948 %F full \"From\" field
1949 %f name, taken from \"From\" field, address if no name
1950 %T full \"To\" field
1951 %t first name in \"To\" field, address if no name
1952 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1953 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1954 %s subject
1955 %d date
1956 %m message-id.
1958 You may use normal field width specification between the % and the letter.
1959 This is for example useful to limit the length of the subject.
1961 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1962 :group 'org-link-store
1963 :type 'string)
1965 (defcustom org-from-is-user-regexp
1966 (let (r1 r2)
1967 (when (and user-mail-address (not (string= user-mail-address "")))
1968 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1969 (when (and user-full-name (not (string= user-full-name "")))
1970 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1971 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1972 "Regexp matched against the \"From:\" header of an email or usenet message.
1973 It should match if the message is from the user him/herself."
1974 :group 'org-link-store
1975 :type 'regexp)
1977 (defcustom org-context-in-file-links t
1978 "Non-nil means file links from `org-store-link' contain context.
1979 \\<org-mode-map>
1980 A search string will be added to the file name with :: as separator
1981 and used to find the context when the link is activated by the command
1982 `org-open-at-point'. When this option is t, the entire active region
1983 will be placed in the search string of the file link. If set to a
1984 positive integer, only the first n lines of context will be stored.
1986 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1987 \\[org-store-link]')
1988 negates this setting for the duration of the command."
1989 :group 'org-link-store
1990 :type '(choice boolean integer))
1992 (defcustom org-keep-stored-link-after-insertion nil
1993 "Non-nil means keep link in list for entire session.
1994 \\<org-mode-map>
1995 The command `org-store-link' adds a link pointing to the current
1996 location to an internal list. These links accumulate during a session.
1997 The command `org-insert-link' can be used to insert links into any
1998 Org file (offering completion for all stored links).
2000 When this option is nil, every link which has been inserted once using
2001 `\\[org-insert-link]' will be removed from the list, to make completing the \
2002 unused
2003 links more efficient."
2004 :group 'org-link-store
2005 :type 'boolean)
2007 (defgroup org-link-follow nil
2008 "Options concerning following links in Org mode."
2009 :tag "Org Follow Link"
2010 :group 'org-link)
2012 (defcustom org-link-translation-function nil
2013 "Function to translate links with different syntax to Org syntax.
2014 This can be used to translate links created for example by the Planner
2015 or emacs-wiki packages to Org syntax.
2016 The function must accept two parameters, a TYPE containing the link
2017 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2018 which is everything after the link protocol. It should return a cons
2019 with possibly modified values of type and path.
2020 Org contains a function for this, so if you set this variable to
2021 `org-translate-link-from-planner', you should be able follow many
2022 links created by planner."
2023 :group 'org-link-follow
2024 :type '(choice (const nil) (function)))
2026 (defcustom org-follow-link-hook nil
2027 "Hook that is run after a link has been followed."
2028 :group 'org-link-follow
2029 :type 'hook)
2031 (defcustom org-tab-follows-link nil
2032 "Non-nil means on links TAB will follow the link.
2033 Needs to be set before org.el is loaded.
2034 This really should not be used, it does not make sense, and the
2035 implementation is bad."
2036 :group 'org-link-follow
2037 :type 'boolean)
2039 (defcustom org-return-follows-link nil
2040 "Non-nil means on links RET will follow the link.
2041 In tables, the special behavior of RET has precedence."
2042 :group 'org-link-follow
2043 :type 'boolean)
2045 (defcustom org-mouse-1-follows-link
2046 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2047 "Non-nil means mouse-1 on a link will follow the link.
2048 A longer mouse click will still set point. Needs to be set
2049 before org.el is loaded."
2050 :group 'org-link-follow
2051 :version "26.1"
2052 :package-version '(Org . "8.3")
2053 :type '(choice
2054 (const :tag "A double click follows the link" double)
2055 (const :tag "Unconditionally follow the link with mouse-1" t)
2056 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2058 (defcustom org-mark-ring-length 4
2059 "Number of different positions to be recorded in the ring.
2060 Changing this requires a restart of Emacs to work correctly."
2061 :group 'org-link-follow
2062 :type 'integer)
2064 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2065 "Non-nil means internal fuzzy links can only match headlines.
2067 When nil, the a fuzzy link may point to a target or a named
2068 construct in the document. When set to the special value
2069 `query-to-create', offer to create a new headline when none
2070 matched.
2072 Spaces and statistics cookies are ignored during heading searches."
2073 :group 'org-link-follow
2074 :version "24.1"
2075 :type '(choice
2076 (const :tag "Use fuzzy text search" nil)
2077 (const :tag "Match only exact headline" t)
2078 (const :tag "Match exact headline or query to create it"
2079 query-to-create))
2080 :safe #'symbolp)
2082 (defcustom org-link-frame-setup
2083 '((vm . vm-visit-folder-other-frame)
2084 (vm-imap . vm-visit-imap-folder-other-frame)
2085 (gnus . org-gnus-no-new-news)
2086 (file . find-file-other-window)
2087 (wl . wl-other-frame))
2088 "Setup the frame configuration for following links.
2089 When following a link with Emacs, it may often be useful to display
2090 this link in another window or frame. This variable can be used to
2091 set this up for the different types of links.
2092 For VM, use any of
2093 `vm-visit-folder'
2094 `vm-visit-folder-other-window'
2095 `vm-visit-folder-other-frame'
2096 For Gnus, use any of
2097 `gnus'
2098 `gnus-other-frame'
2099 `org-gnus-no-new-news'
2100 For FILE, use any of
2101 `find-file'
2102 `find-file-other-window'
2103 `find-file-other-frame'
2104 For Wanderlust use any of
2105 `wl'
2106 `wl-other-frame'
2107 For the calendar, use the variable `calendar-setup'.
2108 For BBDB, it is currently only possible to display the matches in
2109 another window."
2110 :group 'org-link-follow
2111 :type '(list
2112 (cons (const vm)
2113 (choice
2114 (const vm-visit-folder)
2115 (const vm-visit-folder-other-window)
2116 (const vm-visit-folder-other-frame)))
2117 (cons (const vm-imap)
2118 (choice
2119 (const vm-visit-imap-folder)
2120 (const vm-visit-imap-folder-other-window)
2121 (const vm-visit-imap-folder-other-frame)))
2122 (cons (const gnus)
2123 (choice
2124 (const gnus)
2125 (const gnus-other-frame)
2126 (const org-gnus-no-new-news)))
2127 (cons (const file)
2128 (choice
2129 (const find-file)
2130 (const find-file-other-window)
2131 (const find-file-other-frame)))
2132 (cons (const wl)
2133 (choice
2134 (const wl)
2135 (const wl-other-frame)))))
2137 (defcustom org-display-internal-link-with-indirect-buffer nil
2138 "Non-nil means use indirect buffer to display infile links.
2139 Activating internal links (from one location in a file to another location
2140 in the same file) normally just jumps to the location. When the link is
2141 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2142 is displayed in
2143 another window. When this option is set, the other window actually displays
2144 an indirect buffer clone of the current buffer, to avoid any visibility
2145 changes to the current buffer."
2146 :group 'org-link-follow
2147 :type 'boolean)
2149 (defcustom org-open-non-existing-files nil
2150 "Non-nil means `org-open-file' will open non-existing files.
2151 When nil, an error will be generated.
2152 This variable applies only to external applications because they
2153 might choke on non-existing files. If the link is to a file that
2154 will be opened in Emacs, the variable is ignored."
2155 :group 'org-link-follow
2156 :type 'boolean)
2158 (defcustom org-open-directory-means-index-dot-org nil
2159 "Non-nil means a link to a directory really means to index.org.
2160 When nil, following a directory link will run dired or open a finder/explorer
2161 window on that directory."
2162 :group 'org-link-follow
2163 :type 'boolean)
2165 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2166 "Non-nil means ask for confirmation before executing shell links.
2167 Shell links can be dangerous: just think about a link
2169 [[shell:rm -rf ~/*][Google Search]]
2171 This link would show up in your Org document as \"Google Search\",
2172 but really it would remove your entire home directory.
2173 Therefore we advise against setting this variable to nil.
2174 Just change it to `y-or-n-p' if you want to confirm with a
2175 single keystroke rather than having to type \"yes\"."
2176 :group 'org-link-follow
2177 :type '(choice
2178 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2179 (const :tag "with y-or-n (faster)" y-or-n-p)
2180 (const :tag "no confirmation (dangerous)" nil)))
2181 (put 'org-confirm-shell-link-function
2182 'safe-local-variable
2183 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2185 (defcustom org-confirm-shell-link-not-regexp ""
2186 "A regexp to skip confirmation for shell links."
2187 :group 'org-link-follow
2188 :version "24.1"
2189 :type 'regexp)
2191 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2192 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2193 Elisp links can be dangerous: just think about a link
2195 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2197 This link would show up in your Org document as \"Google Search\",
2198 but really it would remove your entire home directory.
2199 Therefore we advise against setting this variable to nil.
2200 Just change it to `y-or-n-p' if you want to confirm with a
2201 single keystroke rather than having to type \"yes\"."
2202 :group 'org-link-follow
2203 :type '(choice
2204 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2205 (const :tag "with y-or-n (faster)" y-or-n-p)
2206 (const :tag "no confirmation (dangerous)" nil)))
2207 (put 'org-confirm-shell-link-function
2208 'safe-local-variable
2209 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2211 (defcustom org-confirm-elisp-link-not-regexp ""
2212 "A regexp to skip confirmation for Elisp links."
2213 :group 'org-link-follow
2214 :version "24.1"
2215 :type 'regexp)
2217 (defconst org-file-apps-defaults-gnu
2218 '((remote . emacs)
2219 (system . mailcap)
2220 (t . mailcap))
2221 "Default file applications on a UNIX or GNU/Linux system.
2222 See `org-file-apps'.")
2224 (defconst org-file-apps-defaults-macosx
2225 '((remote . emacs)
2226 (system . "open %s")
2227 ("ps.gz" . "gv %s")
2228 ("eps.gz" . "gv %s")
2229 ("dvi" . "xdvi %s")
2230 ("fig" . "xfig %s")
2231 (t . "open %s"))
2232 "Default file applications on a macOS system.
2233 The system \"open\" is known as a default, but we use X11 applications
2234 for some files for which the OS does not have a good default.
2235 See `org-file-apps'.")
2237 (defconst org-file-apps-defaults-windowsnt
2238 (list '(remote . emacs)
2239 (cons 'system (lambda (file _path)
2240 (with-no-warnings (w32-shell-execute "open" file))))
2241 (cons t (lambda (file _path)
2242 (with-no-warnings (w32-shell-execute "open" file)))))
2243 "Default file applications on a Windows NT system.
2244 The system \"open\" is used for most files.
2245 See `org-file-apps'.")
2247 (defcustom org-file-apps
2248 '((auto-mode . emacs)
2249 ("\\.mm\\'" . default)
2250 ("\\.x?html?\\'" . default)
2251 ("\\.pdf\\'" . default))
2252 "External applications for opening `file:path' items in a document.
2253 \\<org-mode-map>\
2255 Org mode uses system defaults for different file types, but
2256 you can use this variable to set the application for a given file
2257 extension. The entries in this list are cons cells where the car identifies
2258 files and the cdr the corresponding command.
2260 Possible values for the file identifier are:
2262 \"string\" A string as a file identifier can be interpreted in different
2263 ways, depending on its contents:
2265 - Alphanumeric characters only:
2266 Match links with this file extension.
2267 Example: (\"pdf\" . \"evince %s\")
2268 to open PDFs with evince.
2270 - Regular expression: Match links where the
2271 filename matches the regexp. If you want to
2272 use groups here, use shy groups.
2274 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2275 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2276 to open *.html and *.xhtml with firefox.
2278 - Regular expression which contains (non-shy) groups:
2279 Match links where the whole link, including \"::\", and
2280 anything after that, matches the regexp.
2281 In a custom command string, %1, %2, etc. are replaced with
2282 the parts of the link that were matched by the groups.
2283 For backwards compatibility, if a command string is given
2284 that does not use any of the group matches, this case is
2285 handled identically to the second one (i.e. match against
2286 file name only).
2287 In a custom function, you can access the group matches with
2288 (match-string n link).
2290 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2291 \"evince -p %1 %s\")
2292 to open [[file:document.pdf::5]] with evince at page 5.
2294 `directory' Matches a directory
2295 `remote' Matches a remote file, accessible through tramp or efs.
2296 Remote files most likely should be visited through Emacs
2297 because external applications cannot handle such paths.
2298 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2299 so all files Emacs knows how to handle. Using this with
2300 command `emacs' will open most files in Emacs. Beware that this
2301 will also open html files inside Emacs, unless you add
2302 (\"html\" . default) to the list as well.
2303 `system' The system command to open files, like `open' on Windows
2304 and macOS, and mailcap under GNU/Linux. This is the command
2305 that will be selected if you call `org-open-at-point' with a
2306 double prefix argument (`\\[universal-argument] \
2307 \\[universal-argument] \\[org-open-at-point]').
2308 t Default for files not matched by any of the other options.
2310 Possible values for the command are:
2312 `emacs' The file will be visited by the current Emacs process.
2313 `default' Use the default application for this file type, which is the
2314 association for t in the list, most likely in the system-specific
2315 part. This can be used to overrule an unwanted setting in the
2316 system-specific variable.
2317 `system' Use the system command for opening files, like \"open\".
2318 This command is specified by the entry whose car is `system'.
2319 Most likely, the system-specific version of this variable
2320 does define this command, but you can overrule/replace it
2321 here.
2322 `mailcap' Use command specified in the mailcaps.
2323 string A command to be executed by a shell; %s will be replaced
2324 by the path to the file.
2325 function A Lisp function, which will be called with two arguments:
2326 the file path and the original link string, without the
2327 \"file:\" prefix.
2329 For more examples, see the system specific constants
2330 `org-file-apps-defaults-macosx'
2331 `org-file-apps-defaults-windowsnt'
2332 `org-file-apps-defaults-gnu'."
2333 :group 'org-link-follow
2334 :type '(repeat
2335 (cons (choice :value ""
2336 (string :tag "Extension")
2337 (const :tag "System command to open files" system)
2338 (const :tag "Default for unrecognized files" t)
2339 (const :tag "Remote file" remote)
2340 (const :tag "Links to a directory" directory)
2341 (const :tag "Any files that have Emacs modes"
2342 auto-mode))
2343 (choice :value ""
2344 (const :tag "Visit with Emacs" emacs)
2345 (const :tag "Use default" default)
2346 (const :tag "Use the system command" system)
2347 (string :tag "Command")
2348 (function :tag "Function")))))
2350 (defcustom org-doi-server-url "http://dx.doi.org/"
2351 "The URL of the DOI server."
2352 :type 'string
2353 :version "24.3"
2354 :group 'org-link-follow)
2356 (defgroup org-refile nil
2357 "Options concerning refiling entries in Org mode."
2358 :tag "Org Refile"
2359 :group 'org)
2361 (defcustom org-directory "~/org"
2362 "Directory with Org files.
2363 This is just a default location to look for Org files. There is no need
2364 at all to put your files into this directory. It is used in the
2365 following situations:
2367 1. When a capture template specifies a target file that is not an
2368 absolute path. The path will then be interpreted relative to
2369 `org-directory'
2370 2. When the value of variable `org-agenda-files' is a single file, any
2371 relative paths in this file will be taken as relative to
2372 `org-directory'."
2373 :group 'org-refile
2374 :group 'org-capture
2375 :type 'directory)
2377 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2378 "Default target for storing notes.
2379 Used as a fall back file for org-capture.el, for templates that
2380 do not specify a target file."
2381 :group 'org-refile
2382 :group 'org-capture
2383 :type 'file)
2385 (defcustom org-goto-interface 'outline
2386 "The default interface to be used for `org-goto'.
2387 Allowed values are:
2388 outline The interface shows an outline of the relevant file
2389 and the correct heading is found by moving through
2390 the outline or by searching with incremental search.
2391 outline-path-completion Headlines in the current buffer are offered via
2392 completion. This is the interface also used by
2393 the refile command."
2394 :group 'org-refile
2395 :type '(choice
2396 (const :tag "Outline" outline)
2397 (const :tag "Outline-path-completion" outline-path-completion)))
2399 (defcustom org-goto-max-level 5
2400 "Maximum target level when running `org-goto' with refile interface."
2401 :group 'org-refile
2402 :type 'integer)
2404 (defcustom org-reverse-note-order nil
2405 "Non-nil means store new notes at the beginning of a file or entry.
2406 When nil, new notes will be filed to the end of a file or entry.
2407 This can also be a list with cons cells of regular expressions that
2408 are matched against file names, and values."
2409 :group 'org-capture
2410 :group 'org-refile
2411 :type '(choice
2412 (const :tag "Reverse always" t)
2413 (const :tag "Reverse never" nil)
2414 (repeat :tag "By file name regexp"
2415 (cons regexp boolean))))
2417 (defcustom org-log-refile nil
2418 "Information to record when a task is refiled.
2420 Possible values are:
2422 nil Don't add anything
2423 time Add a time stamp to the task
2424 note Prompt for a note and add it with template `org-log-note-headings'
2426 This option can also be set with on a per-file-basis with
2428 #+STARTUP: nologrefile
2429 #+STARTUP: logrefile
2430 #+STARTUP: lognoterefile
2432 You can have local logging settings for a subtree by setting the LOGGING
2433 property to one or more of these keywords.
2435 When bulk-refiling from the agenda, the value `note' is forbidden and
2436 will temporarily be changed to `time'."
2437 :group 'org-refile
2438 :group 'org-progress
2439 :version "24.1"
2440 :type '(choice
2441 (const :tag "No logging" nil)
2442 (const :tag "Record timestamp" time)
2443 (const :tag "Record timestamp with note." note)))
2445 (defcustom org-refile-targets nil
2446 "Targets for refiling entries with `\\[org-refile]'.
2447 This is a list of cons cells. Each cell contains:
2448 - a specification of the files to be considered, either a list of files,
2449 or a symbol whose function or variable value will be used to retrieve
2450 a file name or a list of file names. If you use `org-agenda-files' for
2451 that, all agenda files will be scanned for targets. Nil means consider
2452 headings in the current buffer.
2453 - A specification of how to find candidate refile targets. This may be
2454 any of:
2455 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2456 This tag has to be present in all target headlines, inheritance will
2457 not be considered.
2458 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2459 todo keyword.
2460 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2461 headlines that are refiling targets.
2462 - a cons cell (:level . N). Any headline of level N is considered a target.
2463 Note that, when `org-odd-levels-only' is set, level corresponds to
2464 order in hierarchy, not to the number of stars.
2465 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2466 Note that, when `org-odd-levels-only' is set, level corresponds to
2467 order in hierarchy, not to the number of stars.
2469 Each element of this list generates a set of possible targets.
2470 The union of these sets is presented (with completion) to
2471 the user by `org-refile'.
2473 You can set the variable `org-refile-target-verify-function' to a function
2474 to verify each headline found by the simple criteria above.
2476 When this variable is nil, all top-level headlines in the current buffer
2477 are used, equivalent to the value `((nil . (:level . 1))'."
2478 :group 'org-refile
2479 :type '(repeat
2480 (cons
2481 (choice :value org-agenda-files
2482 (const :tag "All agenda files" org-agenda-files)
2483 (const :tag "Current buffer" nil)
2484 (function) (variable) (file))
2485 (choice :tag "Identify target headline by"
2486 (cons :tag "Specific tag" (const :value :tag) (string))
2487 (cons :tag "TODO keyword" (const :value :todo) (string))
2488 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2489 (cons :tag "Level number" (const :value :level) (integer))
2490 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2492 (defcustom org-refile-target-verify-function nil
2493 "Function to verify if the headline at point should be a refile target.
2494 The function will be called without arguments, with point at the
2495 beginning of the headline. It should return t and leave point
2496 where it is if the headline is a valid target for refiling.
2498 If the target should not be selected, the function must return nil.
2499 In addition to this, it may move point to a place from where the search
2500 should be continued. For example, the function may decide that the entire
2501 subtree of the current entry should be excluded and move point to the end
2502 of the subtree."
2503 :group 'org-refile
2504 :type '(choice
2505 (const nil)
2506 (function)))
2508 (defcustom org-refile-use-cache nil
2509 "Non-nil means cache refile targets to speed up the process.
2510 \\<org-mode-map>\
2511 The cache for a particular file will be updated automatically when
2512 the buffer has been killed, or when any of the marker used for flagging
2513 refile targets no longer points at a live buffer.
2514 If you have added new entries to a buffer that might themselves be targets,
2515 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2516 if you find that easier, \
2517 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2518 \\[org-refile]'."
2519 :group 'org-refile
2520 :version "24.1"
2521 :type 'boolean)
2523 (defcustom org-refile-use-outline-path nil
2524 "Non-nil means provide refile targets as paths.
2525 So a level 3 headline will be available as level1/level2/level3.
2527 When the value is `file', also include the file name (without directory)
2528 into the path. In this case, you can also stop the completion after
2529 the file name, to get entries inserted as top level in the file.
2531 When `full-file-path', include the full file path.
2533 When `buffer-name', use the buffer name."
2534 :group 'org-refile
2535 :type '(choice
2536 (const :tag "Not" nil)
2537 (const :tag "Yes" t)
2538 (const :tag "Start with file name" file)
2539 (const :tag "Start with full file path" full-file-path)
2540 (const :tag "Start with buffer name" buffer-name)))
2542 (defcustom org-outline-path-complete-in-steps t
2543 "Non-nil means complete the outline path in hierarchical steps.
2544 When Org uses the refile interface to select an outline path (see
2545 `org-refile-use-outline-path'), the completion of the path can be
2546 done in a single go, or it can be done in steps down the headline
2547 hierarchy. Going in steps is probably the best if you do not use
2548 a special completion package like `ido' or `icicles'. However,
2549 when using these packages, going in one step can be very fast,
2550 while still showing the whole path to the entry."
2551 :group 'org-refile
2552 :type 'boolean)
2554 (defcustom org-refile-allow-creating-parent-nodes nil
2555 "Non-nil means allow the creation of new nodes as refile targets.
2556 New nodes are then created by adding \"/new node name\" to the completion
2557 of an existing node. When the value of this variable is `confirm',
2558 new node creation must be confirmed by the user (recommended).
2559 When nil, the completion must match an existing entry.
2561 Note that, if the new heading is not seen by the criteria
2562 listed in `org-refile-targets', multiple instances of the same
2563 heading would be created by trying again to file under the new
2564 heading."
2565 :group 'org-refile
2566 :type '(choice
2567 (const :tag "Never" nil)
2568 (const :tag "Always" t)
2569 (const :tag "Prompt for confirmation" confirm)))
2571 (defcustom org-refile-active-region-within-subtree nil
2572 "Non-nil means also refile active region within a subtree.
2574 By default `org-refile' doesn't allow refiling regions if they
2575 don't contain a set of subtrees, but it might be convenient to
2576 do so sometimes: in that case, the first line of the region is
2577 converted to a headline before refiling."
2578 :group 'org-refile
2579 :version "24.1"
2580 :type 'boolean)
2582 (defgroup org-todo nil
2583 "Options concerning TODO items in Org mode."
2584 :tag "Org TODO"
2585 :group 'org)
2587 (defgroup org-progress nil
2588 "Options concerning Progress logging in Org mode."
2589 :tag "Org Progress"
2590 :group 'org-time)
2592 (defvar org-todo-interpretation-widgets
2593 '((:tag "Sequence (cycling hits every state)" sequence)
2594 (:tag "Type (cycling directly to DONE)" type))
2595 "The available interpretation symbols for customizing `org-todo-keywords'.
2596 Interested libraries should add to this list.")
2598 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2599 "List of TODO entry keyword sequences and their interpretation.
2600 \\<org-mode-map>This is a list of sequences.
2602 Each sequence starts with a symbol, either `sequence' or `type',
2603 indicating if the keywords should be interpreted as a sequence of
2604 action steps, or as different types of TODO items. The first
2605 keywords are states requiring action - these states will select a headline
2606 for inclusion into the global TODO list Org produces. If one of the
2607 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2608 signify that no further action is necessary. If \"|\" is not found,
2609 the last keyword is treated as the only DONE state of the sequence.
2611 The command `\\[org-todo]' cycles an entry through these states, and one
2612 additional state where no keyword is present. For details about this
2613 cycling, see the manual.
2615 TODO keywords and interpretation can also be set on a per-file basis with
2616 the special #+SEQ_TODO and #+TYP_TODO lines.
2618 Each keyword can optionally specify a character for fast state selection
2619 \(in combination with the variable `org-use-fast-todo-selection')
2620 and specifiers for state change logging, using the same syntax that
2621 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2622 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2623 indicates to record a time stamp each time this state is selected.
2625 Each keyword may also specify if a timestamp or a note should be
2626 recorded when entering or leaving the state, by adding additional
2627 characters in the parenthesis after the keyword. This looks like this:
2628 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2629 record only the time of the state change. With X and Y being either
2630 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2631 Y when leaving the state if and only if the *target* state does not
2632 define X. You may omit any of the fast-selection key or X or /Y,
2633 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2635 For backward compatibility, this variable may also be just a list
2636 of keywords. In this case the interpretation (sequence or type) will be
2637 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2638 :group 'org-todo
2639 :group 'org-keywords
2640 :type '(choice
2641 (repeat :tag "Old syntax, just keywords"
2642 (string :tag "Keyword"))
2643 (repeat :tag "New syntax"
2644 (cons
2645 (choice
2646 :tag "Interpretation"
2647 ;;Quick and dirty way to see
2648 ;;`org-todo-interpretations'. This takes the
2649 ;;place of item arguments
2650 :convert-widget
2651 (lambda (widget)
2652 (widget-put widget
2653 :args (mapcar
2654 (lambda (x)
2655 (widget-convert
2656 (cons 'const x)))
2657 org-todo-interpretation-widgets))
2658 widget))
2659 (repeat
2660 (string :tag "Keyword"))))))
2662 (defvar-local org-todo-keywords-1 nil
2663 "All TODO and DONE keywords active in a buffer.")
2664 (defvar org-todo-keywords-for-agenda nil)
2665 (defvar org-done-keywords-for-agenda nil)
2666 (defvar org-todo-keyword-alist-for-agenda nil)
2667 (defvar org-tag-alist-for-agenda nil
2668 "Alist of all tags from all agenda files.")
2669 (defvar org-tag-groups-alist-for-agenda nil
2670 "Alist of all groups tags from all current agenda files.")
2671 (defvar-local org-tag-groups-alist nil)
2672 (defvar org-agenda-contributing-files nil)
2673 (defvar-local org-current-tag-alist nil
2674 "Alist of all tag groups in current buffer.
2675 This variable takes into consideration `org-tag-alist',
2676 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2677 (defvar-local org-not-done-keywords nil)
2678 (defvar-local org-done-keywords nil)
2679 (defvar-local org-todo-heads nil)
2680 (defvar-local org-todo-sets nil)
2681 (defvar-local org-todo-log-states nil)
2682 (defvar-local org-todo-kwd-alist nil)
2683 (defvar-local org-todo-key-alist nil)
2684 (defvar-local org-todo-key-trigger nil)
2686 (defcustom org-todo-interpretation 'sequence
2687 "Controls how TODO keywords are interpreted.
2688 This variable is in principle obsolete and is only used for
2689 backward compatibility, if the interpretation of todo keywords is
2690 not given already in `org-todo-keywords'. See that variable for
2691 more information."
2692 :group 'org-todo
2693 :group 'org-keywords
2694 :type '(choice (const sequence)
2695 (const type)))
2697 (defcustom org-use-fast-todo-selection t
2698 "\\<org-mode-map>\
2699 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2700 This variable describes if and under what circumstances the cycling
2701 mechanism for TODO keywords will be replaced by a single-key, direct
2702 selection scheme.
2704 When nil, fast selection is never used.
2706 When the symbol `prefix', it will be used when `org-todo' is called
2707 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2708 in an Org buffer, and
2709 `\\[universal-argument] t' in an agenda buffer.
2711 When t, fast selection is used by default. In this case, the prefix
2712 argument forces cycling instead.
2714 In all cases, the special interface is only used if access keys have
2715 actually been assigned by the user, i.e. if keywords in the configuration
2716 are followed by a letter in parenthesis, like TODO(t)."
2717 :group 'org-todo
2718 :type '(choice
2719 (const :tag "Never" nil)
2720 (const :tag "By default" t)
2721 (const :tag "Only with C-u C-c C-t" prefix)))
2723 (defcustom org-provide-todo-statistics t
2724 "Non-nil means update todo statistics after insert and toggle.
2725 ALL-HEADLINES means update todo statistics by including headlines
2726 with no TODO keyword as well, counting them as not done.
2727 A list of TODO keywords means the same, but skip keywords that are
2728 not in this list.
2729 When set to a list of two lists, the first list contains keywords
2730 to consider as TODO keywords, the second list contains keywords
2731 to consider as DONE keywords.
2733 When this is set, todo statistics is updated in the parent of the
2734 current entry each time a todo state is changed."
2735 :group 'org-todo
2736 :type '(choice
2737 (const :tag "Yes, only for TODO entries" t)
2738 (const :tag "Yes, including all entries" all-headlines)
2739 (repeat :tag "Yes, for TODOs in this list"
2740 (string :tag "TODO keyword"))
2741 (list :tag "Yes, for TODOs and DONEs in these lists"
2742 (repeat (string :tag "TODO keyword"))
2743 (repeat (string :tag "DONE keyword")))
2744 (other :tag "No TODO statistics" nil)))
2746 (defcustom org-hierarchical-todo-statistics t
2747 "Non-nil means TODO statistics covers just direct children.
2748 When nil, all entries in the subtree are considered.
2749 This has only an effect if `org-provide-todo-statistics' is set.
2750 To set this to nil for only a single subtree, use a COOKIE_DATA
2751 property and include the word \"recursive\" into the value."
2752 :group 'org-todo
2753 :type 'boolean)
2755 (defcustom org-after-todo-state-change-hook nil
2756 "Hook which is run after the state of a TODO item was changed.
2757 The new state (a string with a TODO keyword, or nil) is available in the
2758 Lisp variable `org-state'."
2759 :group 'org-todo
2760 :type 'hook)
2762 (defvar org-blocker-hook nil
2763 "Hook for functions that are allowed to block a state change.
2765 Functions in this hook should not modify the buffer.
2766 Each function gets as its single argument a property list,
2767 see `org-trigger-hook' for more information about this list.
2769 If any of the functions in this hook returns nil, the state change
2770 is blocked.")
2772 (defvar org-trigger-hook nil
2773 "Hook for functions that are triggered by a state change.
2775 Each function gets as its single argument a property list with at
2776 least the following elements:
2778 (:type type-of-change :position pos-at-entry-start
2779 :from old-state :to new-state)
2781 Depending on the type, more properties may be present.
2783 This mechanism is currently implemented for:
2785 TODO state changes
2786 ------------------
2787 :type todo-state-change
2788 :from previous state (keyword as a string), or nil, or a symbol
2789 `todo' or `done', to indicate the general type of state.
2790 :to new state, like in :from")
2792 (defcustom org-enforce-todo-dependencies nil
2793 "Non-nil means undone TODO entries will block switching the parent to DONE.
2794 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2795 be blocked if any prior sibling is not yet done.
2796 Finally, if the parent is blocked because of ordered siblings of its own,
2797 the child will also be blocked."
2798 :set (lambda (var val)
2799 (set var val)
2800 (if val
2801 (add-hook 'org-blocker-hook
2802 'org-block-todo-from-children-or-siblings-or-parent)
2803 (remove-hook 'org-blocker-hook
2804 'org-block-todo-from-children-or-siblings-or-parent)))
2805 :group 'org-todo
2806 :type 'boolean)
2808 (defcustom org-enforce-todo-checkbox-dependencies nil
2809 "Non-nil means unchecked boxes will block switching the parent to DONE.
2810 When this is nil, checkboxes have no influence on switching TODO states.
2811 When non-nil, you first need to check off all check boxes before the TODO
2812 entry can be switched to DONE.
2813 This variable needs to be set before org.el is loaded, and you need to
2814 restart Emacs after a change to make the change effective. The only way
2815 to change is while Emacs is running is through the customize interface."
2816 :set (lambda (var val)
2817 (set var val)
2818 (if val
2819 (add-hook 'org-blocker-hook
2820 'org-block-todo-from-checkboxes)
2821 (remove-hook 'org-blocker-hook
2822 'org-block-todo-from-checkboxes)))
2823 :group 'org-todo
2824 :type 'boolean)
2826 (defcustom org-treat-insert-todo-heading-as-state-change nil
2827 "Non-nil means inserting a TODO heading is treated as state change.
2828 So when the command `\\[org-insert-todo-heading]' is used, state change
2829 logging will apply if appropriate. When nil, the new TODO item will
2830 be inserted directly, and no logging will take place."
2831 :group 'org-todo
2832 :type 'boolean)
2834 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2835 "Non-nil means switching TODO states with S-cursor counts as state change.
2836 This is the default behavior. However, setting this to nil allows a
2837 convenient way to select a TODO state and bypass any logging associated
2838 with that."
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-todo-state-tags-triggers nil
2843 "Tag changes that should be triggered by TODO state changes.
2844 This is a list. Each entry is
2846 (state-change (tag . flag) .......)
2848 State-change can be a string with a state, and empty string to indicate the
2849 state that has no TODO keyword, or it can be one of the symbols `todo'
2850 or `done', meaning any not-done or done state, respectively."
2851 :group 'org-todo
2852 :group 'org-tags
2853 :type '(repeat
2854 (cons (choice :tag "When changing to"
2855 (const :tag "Not-done state" todo)
2856 (const :tag "Done state" done)
2857 (string :tag "State"))
2858 (repeat
2859 (cons :tag "Tag action"
2860 (string :tag "Tag")
2861 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2863 (defcustom org-log-done nil
2864 "Information to record when a task moves to the DONE state.
2866 Possible values are:
2868 nil Don't add anything, just change the keyword
2869 time Add a time stamp to the task
2870 note Prompt for a note and add it with template `org-log-note-headings'
2872 This option can also be set with on a per-file-basis with
2874 #+STARTUP: nologdone
2875 #+STARTUP: logdone
2876 #+STARTUP: lognotedone
2878 You can have local logging settings for a subtree by setting the LOGGING
2879 property to one or more of these keywords."
2880 :group 'org-todo
2881 :group 'org-progress
2882 :type '(choice
2883 (const :tag "No logging" nil)
2884 (const :tag "Record CLOSED timestamp" time)
2885 (const :tag "Record CLOSED timestamp with note." note)))
2887 ;; Normalize old uses of org-log-done.
2888 (cond
2889 ((eq org-log-done t) (setq org-log-done 'time))
2890 ((and (listp org-log-done) (memq 'done org-log-done))
2891 (setq org-log-done 'note)))
2893 (defcustom org-log-reschedule nil
2894 "Information to record when the scheduling date of a tasks is modified.
2896 Possible values are:
2898 nil Don't add anything, just change the date
2899 time Add a time stamp to the task
2900 note Prompt for a note and add it with template `org-log-note-headings'
2902 This option can also be set with on a per-file-basis with
2904 #+STARTUP: nologreschedule
2905 #+STARTUP: logreschedule
2906 #+STARTUP: lognotereschedule"
2907 :group 'org-todo
2908 :group 'org-progress
2909 :type '(choice
2910 (const :tag "No logging" nil)
2911 (const :tag "Record timestamp" time)
2912 (const :tag "Record timestamp with note." note)))
2914 (defcustom org-log-redeadline nil
2915 "Information to record when the deadline date of a tasks is modified.
2917 Possible values are:
2919 nil Don't add anything, just change the date
2920 time Add a time stamp to the task
2921 note Prompt for a note and add it with template `org-log-note-headings'
2923 This option can also be set with on a per-file-basis with
2925 #+STARTUP: nologredeadline
2926 #+STARTUP: logredeadline
2927 #+STARTUP: lognoteredeadline
2929 You can have local logging settings for a subtree by setting the LOGGING
2930 property to one or more of these keywords."
2931 :group 'org-todo
2932 :group 'org-progress
2933 :type '(choice
2934 (const :tag "No logging" nil)
2935 (const :tag "Record timestamp" time)
2936 (const :tag "Record timestamp with note." note)))
2938 (defcustom org-log-note-clock-out nil
2939 "Non-nil means record a note when clocking out of an item.
2940 This can also be configured on a per-file basis by adding one of
2941 the following lines anywhere in the buffer:
2943 #+STARTUP: lognoteclock-out
2944 #+STARTUP: nolognoteclock-out"
2945 :group 'org-todo
2946 :group 'org-progress
2947 :type 'boolean)
2949 (defcustom org-log-done-with-time t
2950 "Non-nil means the CLOSED time stamp will contain date and time.
2951 When nil, only the date will be recorded."
2952 :group 'org-progress
2953 :type 'boolean)
2955 (defcustom org-log-note-headings
2956 '((done . "CLOSING NOTE %t")
2957 (state . "State %-12s from %-12S %t")
2958 (note . "Note taken on %t")
2959 (reschedule . "Rescheduled from %S on %t")
2960 (delschedule . "Not scheduled, was %S on %t")
2961 (redeadline . "New deadline from %S on %t")
2962 (deldeadline . "Removed deadline, was %S on %t")
2963 (refile . "Refiled on %t")
2964 (clock-out . ""))
2965 "Headings for notes added to entries.
2967 The value is an alist, with the car being a symbol indicating the
2968 note context, and the cdr is the heading to be used. The heading
2969 may also be the empty string. The following placeholders can be
2970 used:
2972 %t a time stamp.
2973 %T an active time stamp instead the default inactive one
2974 %d a short-format time stamp.
2975 %D an active short-format time stamp.
2976 %s the new TODO state or time stamp (inactive), in double quotes.
2977 %S the old TODO state or time stamp (inactive), in double quotes.
2978 %u the user name.
2979 %U full user name.
2981 In fact, it is not a good idea to change the `state' entry,
2982 because Agenda Log mode depends on the format of these entries."
2983 :group 'org-todo
2984 :group 'org-progress
2985 :type '(list :greedy t
2986 (cons (const :tag "Heading when closing an item" done) string)
2987 (cons (const :tag
2988 "Heading when changing todo state (todo sequence only)"
2989 state) string)
2990 (cons (const :tag "Heading when just taking a note" note) string)
2991 (cons (const :tag "Heading when rescheduling" reschedule) string)
2992 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2993 (cons (const :tag "Heading when changing deadline" redeadline) string)
2994 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2995 (cons (const :tag "Heading when refiling" refile) string)
2996 (cons (const :tag "Heading when clocking out" clock-out) string)))
2998 (unless (assq 'note org-log-note-headings)
2999 (push '(note . "%t") org-log-note-headings))
3001 (defcustom org-log-into-drawer nil
3002 "Non-nil means insert state change notes and time stamps into a drawer.
3003 When nil, state changes notes will be inserted after the headline and
3004 any scheduling and clock lines, but not inside a drawer.
3006 The value of this variable should be the name of the drawer to use.
3007 LOGBOOK is proposed as the default drawer for this purpose, you can
3008 also set this to a string to define the drawer of your choice.
3010 A value of t is also allowed, representing \"LOGBOOK\".
3012 A value of t or nil can also be set with on a per-file-basis with
3014 #+STARTUP: logdrawer
3015 #+STARTUP: nologdrawer
3017 If this variable is set, `org-log-state-notes-insert-after-drawers'
3018 will be ignored.
3020 You can set the property LOG_INTO_DRAWER to overrule this setting for
3021 a subtree.
3023 Do not check directly this variable in a Lisp program. Call
3024 function `org-log-into-drawer' instead."
3025 :group 'org-todo
3026 :group 'org-progress
3027 :type '(choice
3028 (const :tag "Not into a drawer" nil)
3029 (const :tag "LOGBOOK" t)
3030 (string :tag "Other")))
3032 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3034 (defun org-log-into-drawer ()
3035 "Name of the log drawer, as a string, or nil.
3036 This is the value of `org-log-into-drawer'. However, if the
3037 current entry has or inherits a LOG_INTO_DRAWER property, it will
3038 be used instead of the default value."
3039 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3040 (cond ((equal p "nil") nil)
3041 ((equal p "t") "LOGBOOK")
3042 ((stringp p) p)
3043 (p "LOGBOOK")
3044 ((stringp org-log-into-drawer) org-log-into-drawer)
3045 (org-log-into-drawer "LOGBOOK"))))
3047 (defcustom org-log-state-notes-insert-after-drawers nil
3048 "Non-nil means insert state change notes after any drawers in entry.
3049 Only the drawers that *immediately* follow the headline and the
3050 deadline/scheduled line are skipped.
3051 When nil, insert notes right after the heading and perhaps the line
3052 with deadline/scheduling if present.
3054 This variable will have no effect if `org-log-into-drawer' is
3055 set."
3056 :group 'org-todo
3057 :group 'org-progress
3058 :type 'boolean)
3060 (defcustom org-log-states-order-reversed t
3061 "Non-nil means the latest state note will be directly after heading.
3062 When nil, the state change notes will be ordered according to time.
3064 This option can also be set with on a per-file-basis with
3066 #+STARTUP: logstatesreversed
3067 #+STARTUP: nologstatesreversed"
3068 :group 'org-todo
3069 :group 'org-progress
3070 :type 'boolean)
3072 (defcustom org-todo-repeat-to-state nil
3073 "The TODO state to which a repeater should return the repeating task.
3074 By default this is the first task in a TODO sequence, or the previous state
3075 in a TODO_TYP set. But you can specify another task here.
3076 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3077 :group 'org-todo
3078 :version "24.1"
3079 :type '(choice (const :tag "Head of sequence" nil)
3080 (string :tag "Specific state")))
3082 (defcustom org-log-repeat 'time
3083 "Non-nil means record moving through the DONE state when triggering repeat.
3084 An auto-repeating task is immediately switched back to TODO when
3085 marked DONE. If you are not logging state changes (by adding \"@\"
3086 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3087 record a closing note, there will be no record of the task moving
3088 through DONE. This variable forces taking a note anyway.
3090 nil Don't force a record
3091 time Record a time stamp
3092 note Prompt for a note and add it with template `org-log-note-headings'
3094 This option can also be set with on a per-file-basis with
3096 #+STARTUP: nologrepeat
3097 #+STARTUP: logrepeat
3098 #+STARTUP: lognoterepeat
3100 You can have local logging settings for a subtree by setting the LOGGING
3101 property to one or more of these keywords."
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type '(choice
3105 (const :tag "Don't force a record" nil)
3106 (const :tag "Force recording the DONE state" time)
3107 (const :tag "Force recording a note with the DONE state" note)))
3110 (defgroup org-priorities nil
3111 "Priorities in Org mode."
3112 :tag "Org Priorities"
3113 :group 'org-todo)
3115 (defcustom org-enable-priority-commands t
3116 "Non-nil means priority commands are active.
3117 When nil, these commands will be disabled, so that you never accidentally
3118 set a priority."
3119 :group 'org-priorities
3120 :type 'boolean)
3122 (defcustom org-highest-priority ?A
3123 "The highest priority of TODO items. A character like ?A, ?B etc.
3124 Must have a smaller ASCII number than `org-lowest-priority'."
3125 :group 'org-priorities
3126 :type 'character)
3128 (defcustom org-lowest-priority ?C
3129 "The lowest priority of TODO items. A character like ?A, ?B etc.
3130 Must have a larger ASCII number than `org-highest-priority'."
3131 :group 'org-priorities
3132 :type 'character)
3134 (defcustom org-default-priority ?B
3135 "The default priority of TODO items.
3136 This is the priority an item gets if no explicit priority is given.
3137 When starting to cycle on an empty priority the first step in the cycle
3138 depends on `org-priority-start-cycle-with-default'. The resulting first
3139 step priority must not exceed the range from `org-highest-priority' to
3140 `org-lowest-priority' which means that `org-default-priority' has to be
3141 in this range exclusive or inclusive the range boundaries. Else the
3142 first step refuses to set the default and the second will fall back
3143 to (depending on the command used) the highest or lowest priority."
3144 :group 'org-priorities
3145 :type 'character)
3147 (defcustom org-priority-start-cycle-with-default t
3148 "Non-nil means start with default priority when starting to cycle.
3149 When this is nil, the first step in the cycle will be (depending on the
3150 command used) one higher or lower than the default priority.
3151 See also `org-default-priority'."
3152 :group 'org-priorities
3153 :type 'boolean)
3155 (defcustom org-get-priority-function nil
3156 "Function to extract the priority from a string.
3157 The string is normally the headline. If this is nil Org computes the
3158 priority from the priority cookie like [#A] in the headline. It returns
3159 an integer, increasing by 1000 for each priority level.
3160 The user can set a different function here, which should take a string
3161 as an argument and return the numeric priority."
3162 :group 'org-priorities
3163 :version "24.1"
3164 :type '(choice
3165 (const nil)
3166 (function)))
3168 (defgroup org-time nil
3169 "Options concerning time stamps and deadlines in Org mode."
3170 :tag "Org Time"
3171 :group 'org)
3173 (defcustom org-time-stamp-rounding-minutes '(0 5)
3174 "Number of minutes to round time stamps to.
3175 \\<org-mode-map>\
3176 These are two values, the first applies when first creating a time stamp.
3177 The second applies when changing it with the commands `S-up' and `S-down'.
3178 When changing the time stamp, this means that it will change in steps
3179 of N minutes, as given by the second value.
3181 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3182 numbers should be factors of 60, so for example 5, 10, 15.
3184 When this is larger than 1, you can still force an exact time stamp by using
3185 a double prefix argument to a time stamp command like \
3186 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3187 and by using a prefix arg to `S-up/down' to specify the exact number
3188 of minutes to shift."
3189 :group 'org-time
3190 :get (lambda (var) ; Make sure both elements are there
3191 (if (integerp (default-value var))
3192 (list (default-value var) 5)
3193 (default-value var)))
3194 :type '(list
3195 (integer :tag "when inserting times")
3196 (integer :tag "when modifying times")))
3198 ;; Normalize old customizations of this variable.
3199 (when (integerp org-time-stamp-rounding-minutes)
3200 (setq org-time-stamp-rounding-minutes
3201 (list org-time-stamp-rounding-minutes
3202 org-time-stamp-rounding-minutes)))
3204 (defcustom org-display-custom-times nil
3205 "Non-nil means overlay custom formats over all time stamps.
3206 The formats are defined through the variable `org-time-stamp-custom-formats'.
3207 To turn this on on a per-file basis, insert anywhere in the file:
3208 #+STARTUP: customtime"
3209 :group 'org-time
3210 :set 'set-default
3211 :type 'sexp)
3212 (make-variable-buffer-local 'org-display-custom-times)
3214 (defcustom org-time-stamp-custom-formats
3215 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3216 "Custom formats for time stamps. See `format-time-string' for the syntax.
3217 These are overlaid over the default ISO format if the variable
3218 `org-display-custom-times' is set. Time like %H:%M should be at the
3219 end of the second format. The custom formats are also honored by export
3220 commands, if custom time display is turned on at the time of export."
3221 :group 'org-time
3222 :type 'sexp)
3224 (defun org-time-stamp-format (&optional long inactive)
3225 "Get the right format for a time string."
3226 (let ((f (if long (cdr org-time-stamp-formats)
3227 (car org-time-stamp-formats))))
3228 (if inactive
3229 (concat "[" (substring f 1 -1) "]")
3230 f)))
3232 (defcustom org-deadline-warning-days 14
3233 "Number of days before expiration during which a deadline becomes active.
3234 This variable governs the display in sparse trees and in the agenda.
3235 When 0 or negative, it means use this number (the absolute value of it)
3236 even if a deadline has a different individual lead time specified.
3238 Custom commands can set this variable in the options section."
3239 :group 'org-time
3240 :group 'org-agenda-daily/weekly
3241 :type 'integer)
3243 (defcustom org-scheduled-delay-days 0
3244 "Number of days before a scheduled item becomes active.
3245 This variable governs the display in sparse trees and in the agenda.
3246 The default value (i.e. 0) means: don't delay scheduled item.
3247 When negative, it means use this number (the absolute value of it)
3248 even if a scheduled item has a different individual delay time
3249 specified.
3251 Custom commands can set this variable in the options section."
3252 :group 'org-time
3253 :group 'org-agenda-daily/weekly
3254 :version "24.4"
3255 :package-version '(Org . "8.0")
3256 :type 'integer)
3258 (defcustom org-read-date-prefer-future t
3259 "Non-nil means assume future for incomplete date input from user.
3260 This affects the following situations:
3261 1. The user gives a month but not a year.
3262 For example, if it is April and you enter \"feb 2\", this will be read
3263 as Feb 2, *next* year. \"May 5\", however, will be this year.
3264 2. The user gives a day, but no month.
3265 For example, if today is the 15th, and you enter \"3\", Org will read
3266 this as the third of *next* month. However, if you enter \"17\",
3267 it will be considered as *this* month.
3269 If you set this variable to the symbol `time', then also the following
3270 will work:
3272 3. If the user gives a time.
3273 If the time is before now, it will be interpreted as tomorrow.
3275 Currently none of this works for ISO week specifications.
3277 When this option is nil, the current day, month and year will always be
3278 used as defaults.
3280 See also `org-agenda-jump-prefer-future'."
3281 :group 'org-time
3282 :type '(choice
3283 (const :tag "Never" nil)
3284 (const :tag "Check month and day" t)
3285 (const :tag "Check month, day, and time" time)))
3287 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3288 "Should the agenda jump command prefer the future for incomplete dates?
3289 The default is to do the same as configured in `org-read-date-prefer-future'.
3290 But you can also set a deviating value here.
3291 This may t or nil, or the symbol `org-read-date-prefer-future'."
3292 :group 'org-agenda
3293 :group 'org-time
3294 :version "24.1"
3295 :type '(choice
3296 (const :tag "Use org-read-date-prefer-future"
3297 org-read-date-prefer-future)
3298 (const :tag "Never" nil)
3299 (const :tag "Always" t)))
3301 (defcustom org-read-date-force-compatible-dates t
3302 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3304 Depending on the system Emacs is running on, certain dates cannot
3305 be represented with the type used internally to represent time.
3306 Dates between 1970-1-1 and 2038-1-1 can always be represented
3307 correctly. Some systems allow for earlier dates, some for later,
3308 some for both. One way to find out it to insert any date into an
3309 Org buffer, putting the cursor on the year and hitting S-up and
3310 S-down to test the range.
3312 When this variable is set to t, the date/time prompt will not let
3313 you specify dates outside the 1970-2037 range, so it is certain that
3314 these dates will work in whatever version of Emacs you are
3315 running, and also that you can move a file from one Emacs implementation
3316 to another. WHenever Org is forcing the year for you, it will display
3317 a message and beep.
3319 When this variable is nil, Org will check if the date is
3320 representable in the specific Emacs implementation you are using.
3321 If not, it will force a year, usually the current year, and beep
3322 to remind you. Currently this setting is not recommended because
3323 the likelihood that you will open your Org files in an Emacs that
3324 has limited date range is not negligible.
3326 A workaround for this problem is to use diary sexp dates for time
3327 stamps outside of this range."
3328 :group 'org-time
3329 :version "24.1"
3330 :type 'boolean)
3332 (defcustom org-read-date-display-live t
3333 "Non-nil means display current interpretation of date prompt live.
3334 This display will be in an overlay, in the minibuffer."
3335 :group 'org-time
3336 :type 'boolean)
3338 (defcustom org-read-date-popup-calendar t
3339 "Non-nil means pop up a calendar when prompting for a date.
3340 In the calendar, the date can be selected with mouse-1. However, the
3341 minibuffer will also be active, and you can simply enter the date as well.
3342 When nil, only the minibuffer will be available."
3343 :group 'org-time
3344 :type 'boolean)
3345 (defvaralias 'org-popup-calendar-for-date-prompt
3346 'org-read-date-popup-calendar)
3348 (defcustom org-extend-today-until 0
3349 "The hour when your day really ends. Must be an integer.
3350 This has influence for the following applications:
3351 - When switching the agenda to \"today\". It it is still earlier than
3352 the time given here, the day recognized as TODAY is actually yesterday.
3353 - When a date is read from the user and it is still before the time given
3354 here, the current date and time will be assumed to be yesterday, 23:59.
3355 Also, timestamps inserted in capture templates follow this rule.
3357 IMPORTANT: This is a feature whose implementation is and likely will
3358 remain incomplete. Really, it is only here because past midnight seems to
3359 be the favorite working time of John Wiegley :-)"
3360 :group 'org-time
3361 :type 'integer)
3363 (defcustom org-use-effective-time nil
3364 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3365 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3366 \"effective time\" of any timestamps between midnight and 8am will be
3367 23:59 of the previous day."
3368 :group 'org-time
3369 :version "24.1"
3370 :type 'boolean)
3372 (defcustom org-use-last-clock-out-time-as-effective-time nil
3373 "When non-nil, use the last clock out time for `org-todo'.
3374 Note that this option has precedence over the combined use of
3375 `org-use-effective-time' and `org-extend-today-until'."
3376 :group 'org-time
3377 :version "24.4"
3378 :package-version '(Org . "8.0")
3379 :type 'boolean)
3381 (defcustom org-edit-timestamp-down-means-later nil
3382 "Non-nil means S-down will increase the time in a time stamp.
3383 When nil, S-up will increase."
3384 :group 'org-time
3385 :type 'boolean)
3387 (defcustom org-calendar-follow-timestamp-change t
3388 "Non-nil means make the calendar window follow timestamp changes.
3389 When a timestamp is modified and the calendar window is visible, it will be
3390 moved to the new date."
3391 :group 'org-time
3392 :type 'boolean)
3394 (defgroup org-tags nil
3395 "Options concerning tags in Org mode."
3396 :tag "Org Tags"
3397 :group 'org)
3399 (defcustom org-tag-alist nil
3400 "Default tags available in Org files.
3402 The value of this variable is an alist. Associations either:
3404 (TAG)
3405 (TAG . SELECT)
3406 (SPECIAL)
3408 where TAG is a tag as a string, SELECT is character, used to
3409 select that tag through the fast tag selection interface, and
3410 SPECIAL is one of the following keywords: `:startgroup',
3411 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3412 `:newline'. These keywords are used to define a hierarchy of
3413 tags. See manual for details.
3415 When this variable is nil, Org mode bases tag input on what is
3416 already in the buffer. The value can be overridden locally by
3417 using a TAGS keyword, e.g.,
3419 #+TAGS: tag1 tag2
3421 See also `org-tag-persistent-alist' to sidestep this behavior."
3422 :group 'org-tags
3423 :type '(repeat
3424 (choice
3425 (cons :tag "Tag with key"
3426 (string :tag "Tag name")
3427 (character :tag "Access char"))
3428 (list :tag "Tag" (string :tag "Tag name"))
3429 (const :tag "Start radio group" (:startgroup))
3430 (const :tag "Start tag group, non distinct" (:startgrouptag))
3431 (const :tag "Group tags delimiter" (:grouptags))
3432 (const :tag "End radio group" (:endgroup))
3433 (const :tag "End tag group, non distinct" (:endgrouptag))
3434 (const :tag "New line" (:newline)))))
3436 (defcustom org-tag-persistent-alist nil
3437 "Tags always available in Org files.
3439 The value of this variable is an alist. Associations either:
3441 (TAG)
3442 (TAG . SELECT)
3443 (SPECIAL)
3445 where TAG is a tag as a string, SELECT is a character, used to
3446 select that tag through the fast tag selection interface, and
3447 SPECIAL is one of the following keywords: `:startgroup',
3448 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3449 `:newline'. These keywords are used to define a hierarchy of
3450 tags. See manual for details.
3452 Unlike to `org-tag-alist', tags defined in this variable do not
3453 depend on a local TAGS keyword. Instead, to disable these tags
3454 on a per-file basis, insert anywhere in the file:
3456 #+STARTUP: noptag"
3457 :group 'org-tags
3458 :type '(repeat
3459 (choice
3460 (cons :tag "Tag with key"
3461 (string :tag "Tag name")
3462 (character :tag "Access char"))
3463 (list :tag "Tag" (string :tag "Tag name"))
3464 (const :tag "Start radio group" (:startgroup))
3465 (const :tag "Start tag group, non distinct" (:startgrouptag))
3466 (const :tag "Group tags delimiter" (:grouptags))
3467 (const :tag "End radio group" (:endgroup))
3468 (const :tag "End tag group, non distinct" (:endgrouptag))
3469 (const :tag "New line" (:newline)))))
3471 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3472 "If non-nil, always offer completion for all tags of all agenda files.
3473 Instead of customizing this variable directly, you might want to
3474 set it locally for capture buffers, because there no list of
3475 tags in that file can be created dynamically (there are none).
3477 (add-hook \\='org-capture-mode-hook
3478 (lambda ()
3479 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3480 :group 'org-tags
3481 :version "24.1"
3482 :type 'boolean)
3484 (defvar org-file-tags nil
3485 "List of tags that can be inherited by all entries in the file.
3486 The tags will be inherited if the variable `org-use-tag-inheritance'
3487 says they should be.
3488 This variable is populated from #+FILETAGS lines.")
3490 (defcustom org-use-fast-tag-selection 'auto
3491 "Non-nil means use fast tag selection scheme.
3492 This is a special interface to select and deselect tags with single keys.
3493 When nil, fast selection is never used.
3494 When the symbol `auto', fast selection is used if and only if selection
3495 characters for tags have been configured, either through the variable
3496 `org-tag-alist' or through a #+TAGS line in the buffer.
3497 When t, fast selection is always used and selection keys are assigned
3498 automatically if necessary."
3499 :group 'org-tags
3500 :type '(choice
3501 (const :tag "Always" t)
3502 (const :tag "Never" nil)
3503 (const :tag "When selection characters are configured" auto)))
3505 (defcustom org-fast-tag-selection-single-key nil
3506 "Non-nil means fast tag selection exits after first change.
3507 When nil, you have to press RET to exit it.
3508 During fast tag selection, you can toggle this flag with `C-c'.
3509 This variable can also have the value `expert'. In this case, the window
3510 displaying the tags menu is not even shown, until you press C-c again."
3511 :group 'org-tags
3512 :type '(choice
3513 (const :tag "No" nil)
3514 (const :tag "Yes" t)
3515 (const :tag "Expert" expert)))
3517 (defvar org-fast-tag-selection-include-todo nil
3518 "Non-nil means fast tags selection interface will also offer TODO states.
3519 This is an undocumented feature, you should not rely on it.")
3521 (defcustom org-tags-column -77
3522 "The column to which tags should be indented in a headline.
3523 If this number is positive, it specifies the column. If it is negative,
3524 it means that the tags should be flushright to that column. For example,
3525 -80 works well for a normal 80 character screen.
3526 When 0, place tags directly after headline text, with only one space in
3527 between."
3528 :group 'org-tags
3529 :type 'integer)
3531 (defcustom org-auto-align-tags t
3532 "Non-nil keeps tags aligned when modifying headlines.
3533 Some operations (i.e. demoting) change the length of a headline and
3534 therefore shift the tags around. With this option turned on, after
3535 each such operation the tags are again aligned to `org-tags-column'."
3536 :group 'org-tags
3537 :type 'boolean)
3539 (defcustom org-use-tag-inheritance t
3540 "Non-nil means tags in levels apply also for sublevels.
3541 When nil, only the tags directly given in a specific line apply there.
3542 This may also be a list of tags that should be inherited, or a regexp that
3543 matches tags that should be inherited. Additional control is possible
3544 with the variable `org-tags-exclude-from-inheritance' which gives an
3545 explicit list of tags to be excluded from inheritance, even if the value of
3546 `org-use-tag-inheritance' would select it for inheritance.
3548 If this option is t, a match early-on in a tree can lead to a large
3549 number of matches in the subtree when constructing the agenda or creating
3550 a sparse tree. If you only want to see the first match in a tree during
3551 a search, check out the variable `org-tags-match-list-sublevels'."
3552 :group 'org-tags
3553 :type '(choice
3554 (const :tag "Not" nil)
3555 (const :tag "Always" t)
3556 (repeat :tag "Specific tags" (string :tag "Tag"))
3557 (regexp :tag "Tags matched by regexp")))
3559 (defcustom org-tags-exclude-from-inheritance nil
3560 "List of tags that should never be inherited.
3561 This is a way to exclude a few tags from inheritance. For way to do
3562 the opposite, to actively allow inheritance for selected tags,
3563 see the variable `org-use-tag-inheritance'."
3564 :group 'org-tags
3565 :type '(repeat (string :tag "Tag")))
3567 (defun org-tag-inherit-p (tag)
3568 "Check if TAG is one that should be inherited."
3569 (cond
3570 ((member tag org-tags-exclude-from-inheritance) nil)
3571 ((eq org-use-tag-inheritance t) t)
3572 ((not org-use-tag-inheritance) nil)
3573 ((stringp org-use-tag-inheritance)
3574 (string-match org-use-tag-inheritance tag))
3575 ((listp org-use-tag-inheritance)
3576 (member tag org-use-tag-inheritance))
3577 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3579 (defcustom org-tags-match-list-sublevels t
3580 "Non-nil means list also sublevels of headlines matching a search.
3581 This variable applies to tags/property searches, and also to stuck
3582 projects because this search is based on a tags match as well.
3584 When set to the symbol `indented', sublevels are indented with
3585 leading dots.
3587 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3588 the sublevels of a headline matching a tag search often also match
3589 the same search. Listing all of them can create very long lists.
3590 Setting this variable to nil causes subtrees of a match to be skipped.
3592 This variable is semi-obsolete and probably should always be true. It
3593 is better to limit inheritance to certain tags using the variables
3594 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3595 :group 'org-tags
3596 :type '(choice
3597 (const :tag "No, don't list them" nil)
3598 (const :tag "Yes, do list them" t)
3599 (const :tag "List them, indented with leading dots" indented)))
3601 (defcustom org-tags-sort-function nil
3602 "When set, tags are sorted using this function as a comparator."
3603 :group 'org-tags
3604 :type '(choice
3605 (const :tag "No sorting" nil)
3606 (const :tag "Alphabetical" string<)
3607 (const :tag "Reverse alphabetical" string>)
3608 (function :tag "Custom function" nil)))
3610 (defvar org-tags-history nil
3611 "History of minibuffer reads for tags.")
3612 (defvar org-last-tags-completion-table nil
3613 "The last used completion table for tags.")
3614 (defvar org-after-tags-change-hook nil
3615 "Hook that is run after the tags in a line have changed.")
3617 (defgroup org-properties nil
3618 "Options concerning properties in Org mode."
3619 :tag "Org Properties"
3620 :group 'org)
3622 (defcustom org-property-format "%-10s %s"
3623 "How property key/value pairs should be formatted by `indent-line'.
3624 When `indent-line' hits a property definition, it will format the line
3625 according to this format, mainly to make sure that the values are
3626 lined-up with respect to each other."
3627 :group 'org-properties
3628 :type 'string)
3630 (defcustom org-properties-postprocess-alist nil
3631 "Alist of properties and functions to adjust inserted values.
3632 Elements of this alist must be of the form
3634 ([string] [function])
3636 where [string] must be a property name and [function] must be a
3637 lambda expression: this lambda expression must take one argument,
3638 the value to adjust, and return the new value as a string.
3640 For example, this element will allow the property \"Remaining\"
3641 to be updated wrt the relation between the \"Effort\" property
3642 and the clock summary:
3644 ((\"Remaining\" (lambda(value)
3645 (let ((clocksum (org-clock-sum-current-item))
3646 (effort (org-duration-to-minutes
3647 (org-entry-get (point) \"Effort\"))))
3648 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3649 :group 'org-properties
3650 :version "24.1"
3651 :type '(alist :key-type (string :tag "Property")
3652 :value-type (function :tag "Function")))
3654 (defcustom org-use-property-inheritance nil
3655 "Non-nil means properties apply also for sublevels.
3657 This setting is chiefly used during property searches. Turning it on can
3658 cause significant overhead when doing a search, which is why it is not
3659 on by default.
3661 When nil, only the properties directly given in the current entry count.
3662 When t, every property is inherited. The value may also be a list of
3663 properties that should have inheritance, or a regular expression matching
3664 properties that should be inherited.
3666 However, note that some special properties use inheritance under special
3667 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3668 and the properties ending in \"_ALL\" when they are used as descriptor
3669 for valid values of a property.
3671 Note for programmers:
3672 When querying an entry with `org-entry-get', you can control if inheritance
3673 should be used. By default, `org-entry-get' looks only at the local
3674 properties. You can request inheritance by setting the inherit argument
3675 to t (to force inheritance) or to `selective' (to respect the setting
3676 in this variable)."
3677 :group 'org-properties
3678 :type '(choice
3679 (const :tag "Not" nil)
3680 (const :tag "Always" t)
3681 (repeat :tag "Specific properties" (string :tag "Property"))
3682 (regexp :tag "Properties matched by regexp")))
3684 (defun org-property-inherit-p (property)
3685 "Return a non-nil value if PROPERTY should be inherited."
3686 (cond
3687 ((eq org-use-property-inheritance t) t)
3688 ((not org-use-property-inheritance) nil)
3689 ((stringp org-use-property-inheritance)
3690 (string-match org-use-property-inheritance property))
3691 ((listp org-use-property-inheritance)
3692 (member-ignore-case property org-use-property-inheritance))
3693 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3695 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3696 "The default column format, if no other format has been defined.
3697 This variable can be set on the per-file basis by inserting a line
3699 #+COLUMNS: %25ITEM ....."
3700 :group 'org-properties
3701 :type 'string)
3703 (defcustom org-columns-ellipses ".."
3704 "The ellipses to be used when a field in column view is truncated.
3705 When this is the empty string, as many characters as possible are shown,
3706 but then there will be no visual indication that the field has been truncated.
3707 When this is a string of length N, the last N characters of a truncated
3708 field are replaced by this string. If the column is narrower than the
3709 ellipses string, only part of the ellipses string will be shown."
3710 :group 'org-properties
3711 :type 'string)
3713 (defconst org-global-properties-fixed
3714 '(("VISIBILITY_ALL" . "folded children content all")
3715 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3716 "List of property/value pairs that can be inherited by any entry.
3718 These are fixed values, for the preset properties. The user variable
3719 that can be used to add to this list is `org-global-properties'.
3721 The entries in this list are cons cells where the car is a property
3722 name and cdr is a string with the value. If the value represents
3723 multiple items like an \"_ALL\" property, separate the items by
3724 spaces.")
3726 (defcustom org-global-properties nil
3727 "List of property/value pairs that can be inherited by any entry.
3729 This list will be combined with the constant `org-global-properties-fixed'.
3731 The entries in this list are cons cells where the car is a property
3732 name and cdr is a string with the value.
3734 You can set buffer-local values for the same purpose in the variable
3735 `org-file-properties' this by adding lines like
3737 #+PROPERTY: NAME VALUE"
3738 :group 'org-properties
3739 :type '(repeat
3740 (cons (string :tag "Property")
3741 (string :tag "Value"))))
3743 (defvar-local org-file-properties nil
3744 "List of property/value pairs that can be inherited by any entry.
3745 Valid for the current buffer.
3746 This variable is populated from #+PROPERTY lines.")
3748 (defgroup org-agenda nil
3749 "Options concerning agenda views in Org mode."
3750 :tag "Org Agenda"
3751 :group 'org)
3753 (defvar-local org-category nil
3754 "Variable used by org files to set a category for agenda display.
3755 Such files should use a file variable to set it, for example
3757 # -*- mode: org; org-category: \"ELisp\"
3759 or contain a special line
3761 #+CATEGORY: ELisp
3763 If the file does not specify a category, then file's base name
3764 is used instead.")
3765 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3767 (defcustom org-agenda-files nil
3768 "The files to be used for agenda display.
3770 If an entry is a directory, all files in that directory that are matched
3771 by `org-agenda-file-regexp' will be part of the file list.
3773 If the value of the variable is not a list but a single file name, then
3774 the list of agenda files is actually stored and maintained in that file,
3775 one agenda file per line. In this file paths can be given relative to
3776 `org-directory'. Tilde expansion and environment variable substitution
3777 are also made.
3779 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3780 and removed with `\\[org-remove-file]'."
3781 :group 'org-agenda
3782 :type '(choice
3783 (repeat :tag "List of files and directories" file)
3784 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3786 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3787 "Regular expression to match files for `org-agenda-files'.
3788 If any element in the list in that variable contains a directory instead
3789 of a normal file, all files in that directory that are matched by this
3790 regular expression will be included."
3791 :group 'org-agenda
3792 :type 'regexp)
3794 (defcustom org-agenda-text-search-extra-files nil
3795 "List of extra files to be searched by text search commands.
3796 These files will be searched in addition to the agenda files by the
3797 commands `org-search-view' (`\\[org-agenda] s') \
3798 and `org-occur-in-agenda-files'.
3799 Note that these files will only be searched for text search commands,
3800 not for the other agenda views like todo lists, tag searches or the weekly
3801 agenda. This variable is intended to list notes and possibly archive files
3802 that should also be searched by these two commands.
3803 In fact, if the first element in the list is the symbol `agenda-archives',
3804 then all archive files of all agenda files will be added to the search
3805 scope."
3806 :group 'org-agenda
3807 :type '(set :greedy t
3808 (const :tag "Agenda Archives" agenda-archives)
3809 (repeat :inline t (file))))
3811 (defvaralias 'org-agenda-multi-occur-extra-files
3812 'org-agenda-text-search-extra-files)
3814 (defcustom org-agenda-skip-unavailable-files nil
3815 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3816 A nil value means to remove them, after a query, from the list."
3817 :group 'org-agenda
3818 :type 'boolean)
3820 (defcustom org-calendar-to-agenda-key [?c]
3821 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3822 The command `org-calendar-goto-agenda' will be bound to this key. The
3823 default is the character `c' because then `c' can be used to switch back and
3824 forth between agenda and calendar."
3825 :group 'org-agenda
3826 :type 'sexp)
3828 (defcustom org-calendar-insert-diary-entry-key [?i]
3829 "The key to be installed in `calendar-mode-map' for adding diary entries.
3830 This option is irrelevant until `org-agenda-diary-file' has been configured
3831 to point to an Org file. When that is the case, the command
3832 `org-agenda-diary-entry' will be bound to the key given here, by default
3833 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3834 if you want to continue doing this, you need to change this to a different
3835 key."
3836 :group 'org-agenda
3837 :type 'sexp)
3839 (defcustom org-agenda-diary-file 'diary-file
3840 "File to which to add new entries with the `i' key in agenda and calendar.
3841 When this is the symbol `diary-file', the functionality in the Emacs
3842 calendar will be used to add entries to the `diary-file'. But when this
3843 points to a file, `org-agenda-diary-entry' will be used instead."
3844 :group 'org-agenda
3845 :type '(choice
3846 (const :tag "The standard Emacs diary file" diary-file)
3847 (file :tag "Special Org file diary entries")))
3849 (eval-after-load "calendar"
3850 '(progn
3851 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3852 'org-calendar-goto-agenda)
3853 (add-hook 'calendar-mode-hook
3854 (lambda ()
3855 (unless (eq org-agenda-diary-file 'diary-file)
3856 (define-key calendar-mode-map
3857 org-calendar-insert-diary-entry-key
3858 'org-agenda-diary-entry))))))
3860 (defgroup org-latex nil
3861 "Options for embedding LaTeX code into Org mode."
3862 :tag "Org LaTeX"
3863 :group 'org)
3865 (defcustom org-format-latex-options
3866 '(:foreground default :background default :scale 1.0
3867 :html-foreground "Black" :html-background "Transparent"
3868 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3869 "Options for creating images from LaTeX fragments.
3870 This is a property list with the following properties:
3871 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3872 `default' means use the foreground of the default face.
3873 `auto' means use the foreground from the text face.
3874 :background the background color, or \"Transparent\".
3875 `default' means use the background of the default face.
3876 `auto' means use the background from the text face.
3877 :scale a scaling factor for the size of the images, to get more pixels
3878 :html-foreground, :html-background, :html-scale
3879 the same numbers for HTML export.
3880 :matchers a list indicating which matchers should be used to
3881 find LaTeX fragments. Valid members of this list are:
3882 \"begin\" find environments
3883 \"$1\" find single characters surrounded by $.$
3884 \"$\" find math expressions surrounded by $...$
3885 \"$$\" find math expressions surrounded by $$....$$
3886 \"\\(\" find math expressions surrounded by \\(...\\)
3887 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3888 :group 'org-latex
3889 :type 'plist)
3891 (defcustom org-format-latex-signal-error t
3892 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3893 When nil, just push out a message."
3894 :group 'org-latex
3895 :version "24.1"
3896 :type 'boolean)
3898 (defcustom org-latex-to-mathml-jar-file nil
3899 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3900 Use this to specify additional executable file say a jar file.
3902 When using MathToWeb as the converter, specify the full-path to
3903 your mathtoweb.jar file."
3904 :group 'org-latex
3905 :version "24.1"
3906 :type '(choice
3907 (const :tag "None" nil)
3908 (file :tag "JAR file" :must-match t)))
3910 (defcustom org-latex-to-mathml-convert-command nil
3911 "Command to convert LaTeX fragments to MathML.
3912 Replace format-specifiers in the command as noted below and use
3913 `shell-command' to convert LaTeX to MathML.
3914 %j: Executable file in fully expanded form as specified by
3915 `org-latex-to-mathml-jar-file'.
3916 %I: Input LaTeX file in fully expanded form.
3917 %i: The latex fragment to be converted.
3918 %o: Output MathML file.
3920 This command is used by `org-create-math-formula'.
3922 When using MathToWeb as the converter, set this option to
3923 \"java -jar %j -unicode -force -df %o %I\".
3925 When using LaTeXML set this option to
3926 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3927 :group 'org-latex
3928 :version "24.1"
3929 :type '(choice
3930 (const :tag "None" nil)
3931 (string :tag "\nShell command")))
3933 (defcustom org-preview-latex-default-process 'dvipng
3934 "The default process to convert LaTeX fragments to image files.
3935 All available processes and theirs documents can be found in
3936 `org-preview-latex-process-alist', which see."
3937 :group 'org-latex
3938 :version "26.1"
3939 :package-version '(Org . "9.0")
3940 :type 'symbol)
3942 (defcustom org-preview-latex-process-alist
3943 '((dvipng
3944 :programs ("latex" "dvipng")
3945 :description "dvi > png"
3946 :message "you need to install the programs: latex and dvipng."
3947 :image-input-type "dvi"
3948 :image-output-type "png"
3949 :image-size-adjust (1.0 . 1.0)
3950 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3951 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3952 (dvisvgm
3953 :programs ("latex" "dvisvgm")
3954 :description "dvi > svg"
3955 :message "you need to install the programs: latex and dvisvgm."
3956 :use-xcolor t
3957 :image-input-type "dvi"
3958 :image-output-type "svg"
3959 :image-size-adjust (1.7 . 1.5)
3960 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3961 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3962 (imagemagick
3963 :programs ("latex" "convert")
3964 :description "pdf > png"
3965 :message "you need to install the programs: latex and imagemagick."
3966 :use-xcolor t
3967 :image-input-type "pdf"
3968 :image-output-type "png"
3969 :image-size-adjust (1.0 . 1.0)
3970 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3971 :image-converter
3972 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3973 "Definitions of external processes for LaTeX previewing.
3974 Org mode can use some external commands to generate TeX snippet's images for
3975 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3976 `org-create-formula-image' how to call them.
3978 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3979 PROPERTIES accepts the following attributes:
3981 :programs list of strings, required programs.
3982 :description string, describe the process.
3983 :message string, message it when required programs cannot be found.
3984 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3985 :image-output-type string, output file type of image converter (e.g., \"png\").
3986 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3987 deal with background and foreground color of image.
3988 Otherwise, dvipng style background and foreground color
3989 format are generated. You may then refer to them in
3990 command options with \"%F\" and \"%B\".
3991 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3992 image size showed in buffer and the cdr element is for
3993 HTML file. This option is only useful for process
3994 developers, users should use variable
3995 `org-format-latex-options' instead.
3996 :post-clean list of strings, files matched are to be cleaned up once
3997 the image is generated. When nil, the files with \".dvi\",
3998 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3999 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4000 be cleaned up.
4001 :latex-header list of strings, the LaTeX header of the snippet file.
4002 When nil, the fallback value is used instead, which is
4003 controlled by `org-format-latex-header',
4004 `org-latex-default-packages-alist' and
4005 `org-latex-packages-alist', which see.
4006 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4007 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4008 replaced with values defined below.
4009 :image-converter list of image converter commands strings. Each of them is
4010 given to the shell and supports any of the following
4011 place-holders defined below.
4013 Place-holders used by `:image-converter' and `:latex-compiler':
4015 %f input file name
4016 %b base name of input file
4017 %o base directory of input file
4018 %O absolute output file name
4020 Place-holders only used by `:image-converter':
4022 %F foreground of image
4023 %B background of image
4024 %D dpi, which is used to adjust image size by some processing commands.
4025 %S the image size scale ratio, which is used to adjust image size by some
4026 processing commands."
4027 :group 'org-latex
4028 :version "26.1"
4029 :package-version '(Org . "9.0")
4030 :type '(alist :tag "LaTeX to image backends"
4031 :value-type (plist)))
4033 (defcustom org-preview-latex-image-directory "ltximg/"
4034 "Path to store latex preview images.
4035 A relative path here creates many directories relative to the
4036 processed org files paths. An absolute path puts all preview
4037 images at the same place."
4038 :group 'org-latex
4039 :version "26.1"
4040 :package-version '(Org . "9.0")
4041 :type 'string)
4043 (defun org-format-latex-mathml-available-p ()
4044 "Return t if `org-latex-to-mathml-convert-command' is usable."
4045 (save-match-data
4046 (when (and (boundp 'org-latex-to-mathml-convert-command)
4047 org-latex-to-mathml-convert-command)
4048 (let ((executable (car (split-string
4049 org-latex-to-mathml-convert-command))))
4050 (when (executable-find executable)
4051 (if (string-match
4052 "%j" org-latex-to-mathml-convert-command)
4053 (file-readable-p org-latex-to-mathml-jar-file)
4054 t))))))
4056 (defcustom org-format-latex-header "\\documentclass{article}
4057 \\usepackage[usenames]{color}
4058 \[PACKAGES]
4059 \[DEFAULT-PACKAGES]
4060 \\pagestyle{empty} % do not remove
4061 % The settings below are copied from fullpage.sty
4062 \\setlength{\\textwidth}{\\paperwidth}
4063 \\addtolength{\\textwidth}{-3cm}
4064 \\setlength{\\oddsidemargin}{1.5cm}
4065 \\addtolength{\\oddsidemargin}{-2.54cm}
4066 \\setlength{\\evensidemargin}{\\oddsidemargin}
4067 \\setlength{\\textheight}{\\paperheight}
4068 \\addtolength{\\textheight}{-\\headheight}
4069 \\addtolength{\\textheight}{-\\headsep}
4070 \\addtolength{\\textheight}{-\\footskip}
4071 \\addtolength{\\textheight}{-3cm}
4072 \\setlength{\\topmargin}{1.5cm}
4073 \\addtolength{\\topmargin}{-2.54cm}"
4074 "The document header used for processing LaTeX fragments.
4075 It is imperative that this header make sure that no page number
4076 appears on the page. The package defined in the variables
4077 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4078 will either replace the placeholder \"[PACKAGES]\" in this
4079 header, or they will be appended."
4080 :group 'org-latex
4081 :type 'string)
4083 (defun org-set-packages-alist (var val)
4084 "Set the packages alist and make sure it has 3 elements per entry."
4085 (set var (mapcar (lambda (x)
4086 (if (and (consp x) (= (length x) 2))
4087 (list (car x) (nth 1 x) t)
4089 val)))
4091 (defun org-get-packages-alist (var)
4092 "Get the packages alist and make sure it has 3 elements per entry."
4093 (mapcar (lambda (x)
4094 (if (and (consp x) (= (length x) 2))
4095 (list (car x) (nth 1 x) t)
4097 (default-value var)))
4099 (defcustom org-latex-default-packages-alist
4100 '(("AUTO" "inputenc" t ("pdflatex"))
4101 ("T1" "fontenc" t ("pdflatex"))
4102 ("" "graphicx" t)
4103 ("" "grffile" t)
4104 ("" "longtable" nil)
4105 ("" "wrapfig" nil)
4106 ("" "rotating" nil)
4107 ("normalem" "ulem" t)
4108 ("" "amsmath" t)
4109 ("" "textcomp" t)
4110 ("" "amssymb" t)
4111 ("" "capt-of" nil)
4112 ("" "hyperref" nil))
4113 "Alist of default packages to be inserted in the header.
4115 Change this only if one of the packages here causes an
4116 incompatibility with another package you are using.
4118 The packages in this list are needed by one part or another of
4119 Org mode to function properly:
4121 - inputenc, fontenc: for basic font and character selection
4122 - graphicx: for including images
4123 - grffile: allow periods and spaces in graphics file names
4124 - longtable: For multipage tables
4125 - wrapfig: for figure placement
4126 - rotating: for sideways figures and tables
4127 - ulem: for underline and strike-through
4128 - amsmath: for subscript and superscript and math environments
4129 - textcomp, amssymb: for various symbols used
4130 for interpreting the entities in `org-entities'. You can skip
4131 some of these packages if you don't use any of their symbols.
4132 - capt-of: for captions outside of floats
4133 - hyperref: for cross references
4135 Therefore you should not modify this variable unless you know
4136 what you are doing. The one reason to change it anyway is that
4137 you might be loading some other package that conflicts with one
4138 of the default packages. Each element is either a cell or
4139 a string.
4141 A cell is of the format
4143 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4145 If SNIPPET-FLAG is non-nil, the package also needs to be included
4146 when compiling LaTeX snippets into images for inclusion into
4147 non-LaTeX output. COMPILERS is a list of compilers that should
4148 include the package, see `org-latex-compiler'. If the document
4149 compiler is not in the list, and the list is non-nil, the package
4150 will not be inserted in the final document.
4152 A string will be inserted as-is in the header of the document."
4153 :group 'org-latex
4154 :group 'org-export-latex
4155 :set 'org-set-packages-alist
4156 :get 'org-get-packages-alist
4157 :version "26.1"
4158 :package-version '(Org . "8.3")
4159 :type '(repeat
4160 (choice
4161 (list :tag "options/package pair"
4162 (string :tag "options")
4163 (string :tag "package")
4164 (boolean :tag "Snippet"))
4165 (string :tag "A line of LaTeX"))))
4167 (defcustom org-latex-packages-alist nil
4168 "Alist of packages to be inserted in every LaTeX header.
4170 These will be inserted after `org-latex-default-packages-alist'.
4171 Each element is either a cell or a string.
4173 A cell is of the format:
4175 (\"options\" \"package\" SNIPPET-FLAG)
4177 SNIPPET-FLAG, when non-nil, indicates that this package is also
4178 needed when turning LaTeX snippets into images for inclusion into
4179 non-LaTeX output.
4181 A string will be inserted as-is in the header of the document.
4183 Make sure that you only list packages here which:
4185 - you want in every file;
4186 - do not conflict with the setup in `org-format-latex-header';
4187 - do not conflict with the default packages in
4188 `org-latex-default-packages-alist'."
4189 :group 'org-latex
4190 :group 'org-export-latex
4191 :set 'org-set-packages-alist
4192 :get 'org-get-packages-alist
4193 :type '(repeat
4194 (choice
4195 (list :tag "options/package pair"
4196 (string :tag "options")
4197 (string :tag "package")
4198 (boolean :tag "Snippet"))
4199 (string :tag "A line of LaTeX"))))
4201 (defgroup org-appearance nil
4202 "Settings for Org mode appearance."
4203 :tag "Org Appearance"
4204 :group 'org)
4206 (defcustom org-level-color-stars-only nil
4207 "Non-nil means fontify only the stars in each headline.
4208 When nil, the entire headline is fontified.
4209 Changing it requires restart of `font-lock-mode' to become effective
4210 also in regions already fontified."
4211 :group 'org-appearance
4212 :type 'boolean)
4214 (defcustom org-hide-leading-stars nil
4215 "Non-nil means hide the first N-1 stars in a headline.
4216 This works by using the face `org-hide' for these stars. This
4217 face is white for a light background, and black for a dark
4218 background. You may have to customize the face `org-hide' to
4219 make this work.
4220 Changing it requires restart of `font-lock-mode' to become effective
4221 also in regions already fontified.
4222 You may also set this on a per-file basis by adding one of the following
4223 lines to the buffer:
4225 #+STARTUP: hidestars
4226 #+STARTUP: showstars"
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-hidden-keywords nil
4231 "List of symbols corresponding to keywords to be hidden the org buffer.
4232 For example, a value \\='(title) for this list will make the document's title
4233 appear in the buffer without the initial #+TITLE: keyword."
4234 :group 'org-appearance
4235 :version "24.1"
4236 :type '(set (const :tag "#+AUTHOR" author)
4237 (const :tag "#+DATE" date)
4238 (const :tag "#+EMAIL" email)
4239 (const :tag "#+TITLE" title)))
4241 (defcustom org-custom-properties nil
4242 "List of properties (as strings) with a special meaning.
4243 The default use of these custom properties is to let the user
4244 hide them with `org-toggle-custom-properties-visibility'."
4245 :group 'org-properties
4246 :group 'org-appearance
4247 :version "24.3"
4248 :type '(repeat (string :tag "Property Name")))
4250 (defcustom org-fontify-done-headline nil
4251 "Non-nil means change the face of a headline if it is marked DONE.
4252 Normally, only the TODO/DONE keyword indicates the state of a headline.
4253 When this is non-nil, the headline after the keyword is set to the
4254 `org-headline-done' as an additional indication."
4255 :group 'org-appearance
4256 :type 'boolean)
4258 (defcustom org-fontify-emphasized-text t
4259 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4260 Changing this variable requires a restart of Emacs to take effect."
4261 :group 'org-appearance
4262 :type 'boolean)
4264 (defcustom org-fontify-whole-heading-line nil
4265 "Non-nil means fontify the whole line for headings.
4266 This is useful when setting a background color for the
4267 org-level-* faces."
4268 :group 'org-appearance
4269 :type 'boolean)
4271 (defcustom org-highlight-latex-and-related nil
4272 "Non-nil means highlight LaTeX related syntax in the buffer.
4273 When non nil, the value should be a list containing any of the
4274 following symbols:
4275 `latex' Highlight LaTeX snippets and environments.
4276 `script' Highlight subscript and superscript.
4277 `entities' Highlight entities."
4278 :group 'org-appearance
4279 :version "24.4"
4280 :package-version '(Org . "8.0")
4281 :type '(choice
4282 (const :tag "No highlighting" nil)
4283 (set :greedy t :tag "Highlight"
4284 (const :tag "LaTeX snippets and environments" latex)
4285 (const :tag "Subscript and superscript" script)
4286 (const :tag "Entities" entities))))
4288 (defcustom org-hide-emphasis-markers nil
4289 "Non-nil mean font-lock should hide the emphasis marker characters."
4290 :group 'org-appearance
4291 :type 'boolean)
4293 (defcustom org-hide-macro-markers nil
4294 "Non-nil mean font-lock should hide the brackets marking macro calls."
4295 :group 'org-appearance
4296 :type 'boolean)
4298 (defcustom org-pretty-entities nil
4299 "Non-nil means show entities as UTF8 characters.
4300 When nil, the \\name form remains in the buffer."
4301 :group 'org-appearance
4302 :version "24.1"
4303 :type 'boolean)
4305 (defcustom org-pretty-entities-include-sub-superscripts t
4306 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4307 :group 'org-appearance
4308 :version "24.1"
4309 :type 'boolean)
4311 (defvar org-emph-re nil
4312 "Regular expression for matching emphasis.
4313 After a match, the match groups contain these elements:
4314 0 The match of the full regular expression, including the characters
4315 before and after the proper match
4316 1 The character before the proper match, or empty at beginning of line
4317 2 The proper match, including the leading and trailing markers
4318 3 The leading marker like * or /, indicating the type of highlighting
4319 4 The text between the emphasis markers, not including the markers
4320 5 The character after the match, empty at the end of a line")
4322 (defvar org-verbatim-re nil
4323 "Regular expression for matching verbatim text.")
4325 (defvar org-emphasis-regexp-components) ; defined just below
4326 (defvar org-emphasis-alist) ; defined just below
4327 (defun org-set-emph-re (var val)
4328 "Set variable and compute the emphasis regular expression."
4329 (set var val)
4330 (when (and (boundp 'org-emphasis-alist)
4331 (boundp 'org-emphasis-regexp-components)
4332 org-emphasis-alist org-emphasis-regexp-components)
4333 (pcase-let*
4334 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4335 (body (if (<= nl 0) body
4336 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4337 (template
4338 (format (concat "\\([%s]\\|^\\)" ;before markers
4339 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4340 "\\([%s]\\|$\\)") ;after markers
4341 pre border border body border post)))
4342 (setq org-emph-re (format template "*/_+"))
4343 (setq org-verbatim-re (format template "=~")))))
4345 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4346 ;; set this option proved cumbersome. See this message/thread:
4347 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4348 (defvar org-emphasis-regexp-components
4349 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4350 "Components used to build the regular expression for emphasis.
4351 This is a list with five entries. Terminology: In an emphasis string
4352 like \" *strong word* \", we call the initial space PREMATCH, the final
4353 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4354 and \"trong wor\" is the body. The different components in this variable
4355 specify what is allowed/forbidden in each part:
4357 pre Chars allowed as prematch. Beginning of line will be allowed too.
4358 post Chars allowed as postmatch. End of line will be allowed too.
4359 border The chars *forbidden* as border characters.
4360 body-regexp A regexp like \".\" to match a body character. Don't use
4361 non-shy groups here, and don't allow newline here.
4362 newline The maximum number of newlines allowed in an emphasis exp.
4364 You need to reload Org or to restart Emacs after setting this.")
4366 (defcustom org-emphasis-alist
4367 '(("*" bold)
4368 ("/" italic)
4369 ("_" underline)
4370 ("=" org-verbatim verbatim)
4371 ("~" org-code verbatim)
4372 ("+" (:strike-through t)))
4373 "Alist of characters and faces to emphasize text.
4374 Text starting and ending with a special character will be emphasized,
4375 for example *bold*, _underlined_ and /italic/. This variable sets the
4376 marker characters and the face to be used by font-lock for highlighting
4377 in Org buffers.
4379 You need to reload Org or to restart Emacs after customizing this."
4380 :group 'org-appearance
4381 :set 'org-set-emph-re
4382 :version "24.4"
4383 :package-version '(Org . "8.0")
4384 :type '(repeat
4385 (list
4386 (string :tag "Marker character")
4387 (choice
4388 (face :tag "Font-lock-face")
4389 (plist :tag "Face property list"))
4390 (option (const verbatim)))))
4392 (defvar org-protecting-blocks '("src" "example" "export")
4393 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4394 This is needed for font-lock setup.")
4396 ;;; Functions and variables from their packages
4397 ;; Declared here to avoid compiler warnings
4398 (defvar mark-active)
4400 ;; Various packages
4401 (declare-function calc-eval "calc" (str &optional separator &rest args))
4402 (declare-function calendar-forward-day "cal-move" (arg))
4403 (declare-function calendar-goto-date "cal-move" (date))
4404 (declare-function calendar-goto-today "cal-move" ())
4405 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4406 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4407 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4408 (declare-function cdlatex-tab "ext:cdlatex" ())
4409 (declare-function dired-get-filename
4410 "dired"
4411 (&optional localp no-error-if-not-filep))
4412 (declare-function iswitchb-read-buffer
4413 "iswitchb"
4414 (prompt &optional
4415 default require-match _predicate start matches-set))
4416 (declare-function org-agenda-change-all-lines
4417 "org-agenda"
4418 (newhead hdmarker &optional fixface just-this))
4419 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4420 "org-agenda"
4421 (&optional end))
4422 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4423 (declare-function org-agenda-format-item
4424 "org-agenda"
4425 (extra txt &optional level category tags dotime
4426 remove-re habitp))
4427 (declare-function org-agenda-maybe-redo "org-agenda" ())
4428 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4429 (declare-function org-agenda-save-markers-for-cut-and-paste
4430 "org-agenda"
4431 (beg end))
4432 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4433 (declare-function org-agenda-skip "org-agenda" ())
4434 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4435 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4436 (declare-function org-indent-mode "org-indent" (&optional arg))
4437 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4438 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4439 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4440 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4441 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4442 (declare-function parse-time-string "parse-time" (string))
4443 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4445 (defvar align-mode-rules-list)
4446 (defvar calc-embedded-close-formula)
4447 (defvar calc-embedded-open-formula)
4448 (defvar calc-embedded-open-mode)
4449 (defvar font-lock-unfontify-region-function)
4450 (defvar iswitchb-temp-buflist)
4451 (defvar org-agenda-tags-todo-honor-ignore-options)
4452 (defvar remember-data-file)
4453 (defvar texmathp-why)
4455 ;;;###autoload
4456 (defun turn-on-orgtbl ()
4457 "Unconditionally turn on `orgtbl-mode'."
4458 (require 'org-table)
4459 (orgtbl-mode 1))
4461 (defun org-at-table-p (&optional table-type)
4462 "Non-nil if the cursor is inside an Org table.
4463 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4464 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4465 (or (not (derived-mode-p 'org-mode))
4466 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4467 (and e (or table-type
4468 (eq 'org (org-element-property :type e))))))))
4470 (defun org-at-table.el-p ()
4471 "Non-nil when point is at a table.el table."
4472 (and (org-match-line "[ \t]*[|+]")
4473 (let ((element (org-element-at-point)))
4474 (and (eq (org-element-type element) 'table)
4475 (eq (org-element-property :type element) 'table.el)))))
4477 (defun org-at-table-hline-p ()
4478 "Non-nil when point is inside a hline in a table.
4479 Assume point is already in a table."
4480 (org-match-line org-table-hline-regexp))
4482 (defun org-table-map-tables (function &optional quietly)
4483 "Apply FUNCTION to the start of all tables in the buffer."
4484 (org-with-wide-buffer
4485 (goto-char (point-min))
4486 (while (re-search-forward org-table-any-line-regexp nil t)
4487 (unless quietly
4488 (message "Mapping tables: %d%%"
4489 (floor (* 100.0 (point)) (buffer-size))))
4490 (beginning-of-line 1)
4491 (when (and (looking-at org-table-line-regexp)
4492 ;; Exclude tables in src/example/verbatim/clocktable blocks
4493 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4494 (save-excursion (funcall function))
4495 (or (looking-at org-table-line-regexp)
4496 (forward-char 1)))
4497 (re-search-forward org-table-any-border-regexp nil 1)))
4498 (unless quietly (message "Mapping tables: done")))
4500 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4501 (declare-function org-clock-update-mode-line "org-clock" ())
4502 (declare-function org-resolve-clocks "org-clock"
4503 (&optional also-non-dangling-p prompt last-valid))
4505 (defun org-at-TBLFM-p (&optional pos)
4506 "Non-nil when point (or POS) is in #+TBLFM line."
4507 (save-excursion
4508 (goto-char (or pos (point)))
4509 (beginning-of-line)
4510 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4511 (eq (org-element-type (org-element-at-point)) 'table))))
4513 (defvar org-clock-start-time)
4514 (defvar org-clock-marker (make-marker)
4515 "Marker recording the last clock-in.")
4516 (defvar org-clock-hd-marker (make-marker)
4517 "Marker recording the last clock-in, but the headline position.")
4518 (defvar org-clock-heading ""
4519 "The heading of the current clock entry.")
4520 (defun org-clock-is-active ()
4521 "Return the buffer where the clock is currently running.
4522 Return nil if no clock is running."
4523 (marker-buffer org-clock-marker))
4525 (defun org-check-running-clock ()
4526 "Check if the current buffer contains the running clock.
4527 If yes, offer to stop it and to save the buffer with the changes."
4528 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4529 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4530 (buffer-name))))
4531 (org-clock-out)
4532 (when (y-or-n-p "Save changed buffer?")
4533 (save-buffer))))
4535 (defun org-clocktable-try-shift (dir n)
4536 "Check if this line starts a clock table, if yes, shift the time block."
4537 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4538 (org-clocktable-shift dir n)))
4540 ;;;###autoload
4541 (defun org-clock-persistence-insinuate ()
4542 "Set up hooks for clock persistence."
4543 (require 'org-clock)
4544 (add-hook 'org-mode-hook 'org-clock-load)
4545 (add-hook 'kill-emacs-hook 'org-clock-save))
4547 (defgroup org-archive nil
4548 "Options concerning archiving in Org mode."
4549 :tag "Org Archive"
4550 :group 'org-structure)
4552 (defcustom org-archive-location "%s_archive::"
4553 "The location where subtrees should be archived.
4555 The value of this variable is a string, consisting of two parts,
4556 separated by a double-colon. The first part is a filename and
4557 the second part is a headline.
4559 When the filename is omitted, archiving happens in the same file.
4560 %s in the filename will be replaced by the current file
4561 name (without the directory part). Archiving to a different file
4562 is useful to keep archived entries from contributing to the
4563 Org Agenda.
4565 The archived entries will be filed as subtrees of the specified
4566 headline. When the headline is omitted, the subtrees are simply
4567 filed away at the end of the file, as top-level entries. Also in
4568 the heading you can use %s to represent the file name, this can be
4569 useful when using the same archive for a number of different files.
4571 Here are a few examples:
4572 \"%s_archive::\"
4573 If the current file is Projects.org, archive in file
4574 Projects.org_archive, as top-level trees. This is the default.
4576 \"::* Archived Tasks\"
4577 Archive in the current file, under the top-level headline
4578 \"* Archived Tasks\".
4580 \"~/org/archive.org::\"
4581 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4583 \"~/org/archive.org::* From %s\"
4584 Archive in file ~/org/archive.org (absolute path), under headlines
4585 \"From FILENAME\" where file name is the current file name.
4587 \"~/org/datetree.org::datetree/* Finished Tasks\"
4588 The \"datetree/\" string is special, signifying to archive
4589 items to the datetree. Items are placed in either the CLOSED
4590 date of the item, or the current date if there is no CLOSED date.
4591 The heading will be a subentry to the current date. There doesn't
4592 need to be a heading, but there always needs to be a slash after
4593 datetree. For example, to store archived items directly in the
4594 datetree, use \"~/org/datetree.org::datetree/\".
4596 \"basement::** Finished Tasks\"
4597 Archive in file ./basement (relative path), as level 3 trees
4598 below the level 2 heading \"** Finished Tasks\".
4600 You may set this option on a per-file basis by adding to the buffer a
4601 line like
4603 #+ARCHIVE: basement::** Finished Tasks
4605 You may also define it locally for a subtree by setting an ARCHIVE property
4606 in the entry. If such a property is found in an entry, or anywhere up
4607 the hierarchy, it will be used."
4608 :group 'org-archive
4609 :type 'string)
4611 (defcustom org-agenda-skip-archived-trees t
4612 "Non-nil means the agenda will skip any items located in archived trees.
4613 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4614 variable is no longer recommended, you should leave it at the value t.
4615 Instead, use the key `v' to cycle the archives-mode in the agenda."
4616 :group 'org-archive
4617 :group 'org-agenda-skip
4618 :type 'boolean)
4620 (defcustom org-columns-skip-archived-trees t
4621 "Non-nil means ignore archived trees when creating column view."
4622 :group 'org-archive
4623 :group 'org-properties
4624 :type 'boolean)
4626 (defcustom org-cycle-open-archived-trees nil
4627 "Non-nil means `org-cycle' will open archived trees.
4628 An archived tree is a tree marked with the tag ARCHIVE.
4629 When nil, archived trees will stay folded. You can still open them with
4630 normal outline commands like `show-all', but not with the cycling commands."
4631 :group 'org-archive
4632 :group 'org-cycle
4633 :type 'boolean)
4635 (defcustom org-sparse-tree-open-archived-trees nil
4636 "Non-nil means sparse tree construction shows matches in archived trees.
4637 When nil, matches in these trees are highlighted, but the trees are kept in
4638 collapsed state."
4639 :group 'org-archive
4640 :group 'org-sparse-trees
4641 :type 'boolean)
4643 (defcustom org-sparse-tree-default-date-type nil
4644 "The default date type when building a sparse tree.
4645 When this is nil, a date is a scheduled or a deadline timestamp.
4646 Otherwise, these types are allowed:
4648 all: all timestamps
4649 active: only active timestamps (<...>)
4650 inactive: only inactive timestamps ([...])
4651 scheduled: only scheduled timestamps
4652 deadline: only deadline timestamps"
4653 :type '(choice (const :tag "Scheduled or deadline" nil)
4654 (const :tag "All timestamps" all)
4655 (const :tag "Only active timestamps" active)
4656 (const :tag "Only inactive timestamps" inactive)
4657 (const :tag "Only scheduled timestamps" scheduled)
4658 (const :tag "Only deadline timestamps" deadline)
4659 (const :tag "Only closed timestamps" closed))
4660 :version "26.1"
4661 :package-version '(Org . "8.3")
4662 :group 'org-sparse-trees)
4664 (defun org-cycle-hide-archived-subtrees (state)
4665 "Re-hide all archived subtrees after a visibility state change.
4666 STATE should be one of the symbols listed in the docstring of
4667 `org-cycle-hook'."
4668 (when (and (not org-cycle-open-archived-trees)
4669 (not (memq state '(overview folded))))
4670 (save-excursion
4671 (let* ((globalp (memq state '(contents all)))
4672 (beg (if globalp (point-min) (point)))
4673 (end (if globalp (point-max) (org-end-of-subtree t))))
4674 (org-hide-archived-subtrees beg end)
4675 (goto-char beg)
4676 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4677 (message "%s" (substitute-command-keys
4678 "Subtree is archived and stays closed. Use \
4679 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4681 (defun org-force-cycle-archived ()
4682 "Cycle subtree even if it is archived."
4683 (interactive)
4684 (setq this-command 'org-cycle)
4685 (let ((org-cycle-open-archived-trees t))
4686 (call-interactively 'org-cycle)))
4688 (defun org-hide-archived-subtrees (beg end)
4689 "Re-hide all archived subtrees after a visibility state change."
4690 (org-with-wide-buffer
4691 (let ((case-fold-search nil)
4692 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4693 (goto-char beg)
4694 ;; Include headline point is currently on.
4695 (beginning-of-line)
4696 (while (and (< (point) end) (re-search-forward re end t))
4697 (when (member org-archive-tag (org-get-tags))
4698 (org-flag-subtree t)
4699 (org-end-of-subtree t))))))
4701 (declare-function outline-end-of-heading "outline" ())
4702 (declare-function outline-flag-region "outline" (from to flag))
4703 (defun org-flag-subtree (flag)
4704 (save-excursion
4705 (org-back-to-heading t)
4706 (outline-end-of-heading)
4707 (outline-flag-region (point)
4708 (progn (org-end-of-subtree t) (point))
4709 flag)))
4711 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4713 ;; Declare Column View Code
4715 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4716 (declare-function org-columns-compute "org-colview" (property))
4718 ;; Declare ID code
4720 (declare-function org-id-store-link "org-id")
4721 (declare-function org-id-locations-load "org-id")
4722 (declare-function org-id-locations-save "org-id")
4723 (defvar org-id-track-globally)
4725 ;;; Variables for pre-computed regular expressions, all buffer local
4727 (defvar-local org-todo-regexp nil
4728 "Matches any of the TODO state keywords.
4729 Since TODO keywords are case-sensitive, `case-fold-search' is
4730 expected to be bound to nil when matching against this regexp.")
4732 (defvar-local org-not-done-regexp nil
4733 "Matches any of the TODO state keywords except the last one.
4734 Since TODO keywords are case-sensitive, `case-fold-search' is
4735 expected to be bound to nil when matching against this regexp.")
4737 (defvar-local org-not-done-heading-regexp nil
4738 "Matches a TODO headline that is not done.
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-todo-line-regexp nil
4743 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4748 "Matches a headline and puts everything into groups:
4750 group 1: Stars
4751 group 2: The TODO keyword, maybe
4752 group 3: Priority cookie
4753 group 4: True headline
4754 group 5: Tags
4756 Since TODO keywords are case-sensitive, `case-fold-search' is
4757 expected to be bound to nil when matching against this regexp.")
4759 (defvar-local org-complex-heading-regexp-format nil
4760 "Printf format to make regexp to match an exact headline.
4761 This regexp will match the headline of any node which has the
4762 exact headline text that is put into the format, but may have any
4763 TODO state, priority and tags.")
4765 (defvar-local org-todo-line-tags-regexp nil
4766 "Matches a headline and puts TODO state into group 2 if present.
4767 Also put tags into group 4 if tags are present.")
4769 (defconst org-plain-time-of-day-regexp
4770 (concat
4771 "\\(\\<[012]?[0-9]"
4772 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4773 "\\(--?"
4774 "\\(\\<[012]?[0-9]"
4775 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4776 "\\)?")
4777 "Regular expression to match a plain time or time range.
4778 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4779 groups carry important information:
4780 0 the full match
4781 1 the first time, range or not
4782 8 the second time, if it is a range.")
4784 (defconst org-plain-time-extension-regexp
4785 (concat
4786 "\\(\\<[012]?[0-9]"
4787 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4788 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4789 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4790 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4791 groups carry important information:
4792 0 the full match
4793 7 hours of duration
4794 9 minutes of duration")
4796 (defconst org-stamp-time-of-day-regexp
4797 (concat
4798 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4799 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4800 "\\(--?"
4801 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4802 "Regular expression to match a timestamp time or time range.
4803 After a match, the following groups carry important information:
4804 0 the full match
4805 1 date plus weekday, for back referencing to make sure both times are on the same day
4806 2 the first time, range or not
4807 4 the second time, if it is a range.")
4809 (defconst org-startup-options
4810 '(("fold" org-startup-folded t)
4811 ("overview" org-startup-folded t)
4812 ("nofold" org-startup-folded nil)
4813 ("showall" org-startup-folded nil)
4814 ("showeverything" org-startup-folded showeverything)
4815 ("content" org-startup-folded content)
4816 ("indent" org-startup-indented t)
4817 ("noindent" org-startup-indented nil)
4818 ("hidestars" org-hide-leading-stars t)
4819 ("showstars" org-hide-leading-stars nil)
4820 ("odd" org-odd-levels-only t)
4821 ("oddeven" org-odd-levels-only nil)
4822 ("align" org-startup-align-all-tables t)
4823 ("noalign" org-startup-align-all-tables nil)
4824 ("shrink" org-startup-shrink-all-tables t)
4825 ("inlineimages" org-startup-with-inline-images t)
4826 ("noinlineimages" org-startup-with-inline-images nil)
4827 ("latexpreview" org-startup-with-latex-preview t)
4828 ("nolatexpreview" org-startup-with-latex-preview nil)
4829 ("customtime" org-display-custom-times t)
4830 ("logdone" org-log-done time)
4831 ("lognotedone" org-log-done note)
4832 ("nologdone" org-log-done nil)
4833 ("lognoteclock-out" org-log-note-clock-out t)
4834 ("nolognoteclock-out" org-log-note-clock-out nil)
4835 ("logrepeat" org-log-repeat state)
4836 ("lognoterepeat" org-log-repeat note)
4837 ("logdrawer" org-log-into-drawer t)
4838 ("nologdrawer" org-log-into-drawer nil)
4839 ("logstatesreversed" org-log-states-order-reversed t)
4840 ("nologstatesreversed" org-log-states-order-reversed nil)
4841 ("nologrepeat" org-log-repeat nil)
4842 ("logreschedule" org-log-reschedule time)
4843 ("lognotereschedule" org-log-reschedule note)
4844 ("nologreschedule" org-log-reschedule nil)
4845 ("logredeadline" org-log-redeadline time)
4846 ("lognoteredeadline" org-log-redeadline note)
4847 ("nologredeadline" org-log-redeadline nil)
4848 ("logrefile" org-log-refile time)
4849 ("lognoterefile" org-log-refile note)
4850 ("nologrefile" org-log-refile nil)
4851 ("fninline" org-footnote-define-inline t)
4852 ("nofninline" org-footnote-define-inline nil)
4853 ("fnlocal" org-footnote-section nil)
4854 ("fnauto" org-footnote-auto-label t)
4855 ("fnprompt" org-footnote-auto-label nil)
4856 ("fnconfirm" org-footnote-auto-label confirm)
4857 ("fnplain" org-footnote-auto-label plain)
4858 ("fnadjust" org-footnote-auto-adjust t)
4859 ("nofnadjust" org-footnote-auto-adjust nil)
4860 ("constcgs" constants-unit-system cgs)
4861 ("constSI" constants-unit-system SI)
4862 ("noptag" org-tag-persistent-alist nil)
4863 ("hideblocks" org-hide-block-startup t)
4864 ("nohideblocks" org-hide-block-startup nil)
4865 ("beamer" org-startup-with-beamer-mode t)
4866 ("entitiespretty" org-pretty-entities t)
4867 ("entitiesplain" org-pretty-entities nil))
4868 "Variable associated with STARTUP options for org-mode.
4869 Each element is a list of three items: the startup options (as written
4870 in the #+STARTUP line), the corresponding variable, and the value to set
4871 this variable to if the option is found. An optional forth element PUSH
4872 means to push this value onto the list in the variable.")
4874 (defcustom org-group-tags t
4875 "When non-nil (the default), use group tags.
4876 This can be turned on/off through `org-toggle-tags-groups'."
4877 :group 'org-tags
4878 :group 'org-startup
4879 :type 'boolean)
4881 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4883 (defun org-toggle-tags-groups ()
4884 "Toggle support for group tags.
4885 Support for group tags is controlled by the option
4886 `org-group-tags', which is non-nil by default."
4887 (interactive)
4888 (setq org-group-tags (not org-group-tags))
4889 (cond ((and (derived-mode-p 'org-agenda-mode)
4890 org-group-tags)
4891 (org-agenda-redo))
4892 ((derived-mode-p 'org-mode)
4893 (let ((org-inhibit-startup t)) (org-mode))))
4894 (message "Groups tags support has been turned %s"
4895 (if org-group-tags "on" "off")))
4897 (defun org-set-regexps-and-options (&optional tags-only)
4898 "Precompute regular expressions used in the current buffer.
4899 When optional argument TAGS-ONLY is non-nil, only compute tags
4900 related expressions."
4901 (when (derived-mode-p 'org-mode)
4902 (let ((alist (org--setup-collect-keywords
4903 (org-make-options-regexp
4904 (append '("FILETAGS" "TAGS" "SETUPFILE")
4905 (and (not tags-only)
4906 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4907 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4908 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4909 ;; Startup options. Get this early since it does change
4910 ;; behavior for other options (e.g., tags).
4911 (let ((startup (cdr (assq 'startup alist))))
4912 (dolist (option startup)
4913 (let ((entry (assoc-string option org-startup-options t)))
4914 (when entry
4915 (let ((var (nth 1 entry))
4916 (val (nth 2 entry)))
4917 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4918 (unless (listp (symbol-value var))
4919 (set (make-local-variable var) nil))
4920 (add-to-list var val)))))))
4921 (setq-local org-file-tags
4922 (mapcar #'org-add-prop-inherited
4923 (cdr (assq 'filetags alist))))
4924 (setq org-current-tag-alist
4925 (append org-tag-persistent-alist
4926 (let ((tags (cdr (assq 'tags alist))))
4927 (if tags (org-tag-string-to-alist tags)
4928 org-tag-alist))))
4929 (setq org-tag-groups-alist
4930 (org-tag-alist-to-groups org-current-tag-alist))
4931 (unless tags-only
4932 ;; File properties.
4933 (setq-local org-file-properties (cdr (assq 'property alist)))
4934 ;; Archive location.
4935 (let ((archive (cdr (assq 'archive alist))))
4936 (when archive (setq-local org-archive-location archive)))
4937 ;; Category.
4938 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4939 (when cat
4940 (setq-local org-category (intern cat))
4941 (setq-local org-file-properties
4942 (org--update-property-plist
4943 "CATEGORY" cat org-file-properties))))
4944 ;; Columns.
4945 (let ((column (cdr (assq 'columns alist))))
4946 (when column (setq-local org-columns-default-format column)))
4947 ;; Constants.
4948 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4949 ;; Link abbreviations.
4950 (let ((links (cdr (assq 'link alist))))
4951 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4952 ;; Priorities.
4953 (let ((priorities (cdr (assq 'priorities alist))))
4954 (when priorities
4955 (setq-local org-highest-priority (nth 0 priorities))
4956 (setq-local org-lowest-priority (nth 1 priorities))
4957 (setq-local org-default-priority (nth 2 priorities))))
4958 ;; Scripts.
4959 (let ((scripts (assq 'scripts alist)))
4960 (when scripts
4961 (setq-local org-use-sub-superscripts (cdr scripts))))
4962 ;; TODO keywords.
4963 (setq-local org-todo-kwd-alist nil)
4964 (setq-local org-todo-key-alist nil)
4965 (setq-local org-todo-key-trigger nil)
4966 (setq-local org-todo-keywords-1 nil)
4967 (setq-local org-done-keywords nil)
4968 (setq-local org-todo-heads nil)
4969 (setq-local org-todo-sets nil)
4970 (setq-local org-todo-log-states nil)
4971 (let ((todo-sequences
4972 (or (nreverse (cdr (assq 'todo alist)))
4973 (let ((d (default-value 'org-todo-keywords)))
4974 (if (not (stringp (car d))) d
4975 ;; XXX: Backward compatibility code.
4976 (list (cons org-todo-interpretation d)))))))
4977 (dolist (sequence todo-sequences)
4978 (let* ((sequence (or (run-hook-with-args-until-success
4979 'org-todo-setup-filter-hook sequence)
4980 sequence))
4981 (sequence-type (car sequence))
4982 (keywords (cdr sequence))
4983 (sep (member "|" keywords))
4984 names alist)
4985 (dolist (k (remove "|" keywords))
4986 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4988 (error "Invalid TODO keyword %s" k))
4989 (let ((name (match-string 1 k))
4990 (key (match-string 2 k))
4991 (log (org-extract-log-state-settings k)))
4992 (push name names)
4993 (push (cons name (and key (string-to-char key))) alist)
4994 (when log (push log org-todo-log-states))))
4995 (let* ((names (nreverse names))
4996 (done (if sep (org-remove-keyword-keys (cdr sep))
4997 (last names)))
4998 (head (car names))
4999 (tail (list sequence-type head (car done) (org-last done))))
5000 (add-to-list 'org-todo-heads head 'append)
5001 (push names org-todo-sets)
5002 (setq org-done-keywords (append org-done-keywords done nil))
5003 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5004 (setq org-todo-key-alist
5005 (append org-todo-key-alist
5006 (and alist
5007 (append '((:startgroup))
5008 (nreverse alist)
5009 '((:endgroup))))))
5010 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5011 (setq org-todo-sets (nreverse org-todo-sets)
5012 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5013 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5014 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5015 ;; Compute the regular expressions and other local variables.
5016 ;; Using `org-outline-regexp-bol' would complicate them much,
5017 ;; because of the fixed white space at the end of that string.
5018 (unless org-done-keywords
5019 (setq org-done-keywords
5020 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5021 (setq org-not-done-keywords
5022 (org-delete-all org-done-keywords
5023 (copy-sequence org-todo-keywords-1))
5024 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5025 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5026 org-not-done-heading-regexp
5027 (format org-heading-keyword-regexp-format org-not-done-regexp)
5028 org-todo-line-regexp
5029 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5030 org-complex-heading-regexp
5031 (concat "^\\(\\*+\\)"
5032 "\\(?: +" org-todo-regexp "\\)?"
5033 "\\(?: +\\(\\[#.\\]\\)\\)?"
5034 "\\(?: +\\(.*?\\)\\)??"
5035 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5036 "[ \t]*$")
5037 org-complex-heading-regexp-format
5038 (concat "^\\(\\*+\\)"
5039 "\\(?: +" org-todo-regexp "\\)?"
5040 "\\(?: +\\(\\[#.\\]\\)\\)?"
5041 "\\(?: +"
5042 ;; Stats cookies can be stuck to body.
5043 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5044 "\\(%s\\)"
5045 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5046 "\\)"
5047 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5048 "[ \t]*$")
5049 org-todo-line-tags-regexp
5050 (concat "^\\(\\*+\\)"
5051 "\\(?: +" org-todo-regexp "\\)?"
5052 "\\(?: +\\(.*?\\)\\)??"
5053 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5054 "[ \t]*$"))
5055 (org-compute-latex-and-related-regexp)))))
5057 (defun org--setup-collect-keywords (regexp &optional files alist)
5058 "Return setup keywords values as an alist.
5060 REGEXP matches a subset of setup keywords. FILES is a list of
5061 file names already visited. It is used to avoid circular setup
5062 files. ALIST, when non-nil, is the alist computed so far.
5064 Return value contains the following keys: `archive', `category',
5065 `columns', `constants', `filetags', `link', `priorities',
5066 `property', `scripts', `startup', `tags' and `todo'."
5067 (org-with-wide-buffer
5068 (goto-char (point-min))
5069 (let ((case-fold-search t))
5070 (while (re-search-forward regexp nil t)
5071 (let ((element (org-element-at-point)))
5072 (when (eq (org-element-type element) 'keyword)
5073 (let ((key (org-element-property :key element))
5074 (value (org-element-property :value element)))
5075 (cond
5076 ((equal key "ARCHIVE")
5077 (when (org-string-nw-p value)
5078 (push (cons 'archive value) alist)))
5079 ((equal key "CATEGORY") (push (cons 'category value) alist))
5080 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5081 ((equal key "CONSTANTS")
5082 (let* ((constants (assq 'constants alist))
5083 (store (cdr constants)))
5084 (dolist (pair (split-string value))
5085 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5086 pair)
5087 (let* ((name (match-string 1 pair))
5088 (value (match-string 2 pair))
5089 (old (assoc name store)))
5090 (if old (setcdr old value)
5091 (push (cons name value) store)))))
5092 (if constants (setcdr constants store)
5093 (push (cons 'constants store) alist))))
5094 ((equal key "FILETAGS")
5095 (when (org-string-nw-p value)
5096 (let ((old (assq 'filetags alist))
5097 (new (apply #'nconc
5098 (mapcar (lambda (x) (org-split-string x ":"))
5099 (split-string value)))))
5100 (if old (setcdr old (append new (cdr old)))
5101 (push (cons 'filetags new) alist)))))
5102 ((equal key "LINK")
5103 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5104 (let ((links (assq 'link alist))
5105 (pair (cons (match-string-no-properties 1 value)
5106 (match-string-no-properties 2 value))))
5107 (if links (push pair (cdr links))
5108 (push (list 'link pair) alist)))))
5109 ((equal key "OPTIONS")
5110 (when (and (org-string-nw-p value)
5111 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5112 (push (cons 'scripts (read (match-string 1 value))) alist)))
5113 ((equal key "PRIORITIES")
5114 (push (cons 'priorities
5115 (let ((prio (split-string value)))
5116 (if (< (length prio) 3) '(?A ?C ?B)
5117 (mapcar #'string-to-char prio))))
5118 alist))
5119 ((equal key "PROPERTY")
5120 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5121 (let* ((property (assq 'property alist))
5122 (value (org--update-property-plist
5123 (match-string-no-properties 1 value)
5124 (match-string-no-properties 2 value)
5125 (cdr property))))
5126 (if property (setcdr property value)
5127 (push (cons 'property value) alist)))))
5128 ((equal key "STARTUP")
5129 (let ((startup (assq 'startup alist)))
5130 (if startup
5131 (setcdr startup
5132 (append (cdr startup) (split-string value)))
5133 (push (cons 'startup (split-string value)) alist))))
5134 ((equal key "TAGS")
5135 (let ((tag-cell (assq 'tags alist)))
5136 (if tag-cell
5137 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5138 (push (cons 'tags value) alist))))
5139 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5140 (let ((todo (assq 'todo alist))
5141 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5142 (split-string value))))
5143 (if todo (push value (cdr todo))
5144 (push (list 'todo value) alist))))
5145 ((equal key "SETUPFILE")
5146 (unless buffer-read-only ; Do not check in Gnus messages.
5147 (let ((f (and (org-string-nw-p value)
5148 (expand-file-name
5149 (org-unbracket-string "\"" "\"" value)))))
5150 (when (and f (file-readable-p f) (not (member f files)))
5151 (with-temp-buffer
5152 (setq default-directory (file-name-directory f))
5153 (insert-file-contents f)
5154 (setq alist
5155 ;; Fake Org mode to benefit from cache
5156 ;; without recurring needlessly.
5157 (let ((major-mode 'org-mode))
5158 (org--setup-collect-keywords
5159 regexp (cons f files) alist)))))))))))))))
5160 alist)
5162 (defun org-tag-string-to-alist (s)
5163 "Return tag alist associated to string S.
5164 S is a value for TAGS keyword or produced with
5165 `org-tag-alist-to-string'. Return value is an alist suitable for
5166 `org-tag-alist' or `org-tag-persistent-alist'."
5167 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5168 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5169 "\\|{.+?}\\)" ; regular expression
5170 "\\(?:(\\(.\\))\\)?\\'"))
5171 alist group-flag)
5172 (dolist (tokens lines (cdr (nreverse alist)))
5173 (push '(:newline) alist)
5174 (while tokens
5175 (let ((token (pop tokens)))
5176 (pcase token
5177 ("{"
5178 (push '(:startgroup) alist)
5179 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5180 ("}"
5181 (push '(:endgroup) alist)
5182 (setq group-flag nil))
5183 ("["
5184 (push '(:startgrouptag) alist)
5185 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5186 ("]"
5187 (push '(:endgrouptag) alist)
5188 (setq group-flag nil))
5189 (":"
5190 (push '(:grouptags) alist))
5191 ((guard (string-match tag-re token))
5192 (let ((tag (match-string 1 token))
5193 (key (and (match-beginning 2)
5194 (string-to-char (match-string 2 token)))))
5195 ;; Push all tags in groups, no matter if they already
5196 ;; appear somewhere else in the list.
5197 (when (or group-flag (not (assoc tag alist)))
5198 (push (cons tag key) alist))))))))))
5200 (defun org-tag-alist-to-string (alist &optional skip-key)
5201 "Return tag string associated to ALIST.
5203 ALIST is an alist, as defined in `org-tag-alist' or
5204 `org-tag-persistent-alist', or produced with
5205 `org-tag-string-to-alist'.
5207 Return value is a string suitable as a value for \"TAGS\"
5208 keyword.
5210 When optional argument SKIP-KEY is non-nil, skip selection keys
5211 next to tags."
5212 (mapconcat (lambda (token)
5213 (pcase token
5214 (`(:startgroup) "{")
5215 (`(:endgroup) "}")
5216 (`(:startgrouptag) "[")
5217 (`(:endgrouptag) "]")
5218 (`(:grouptags) ":")
5219 (`(:newline) "\\n")
5220 ((and
5221 (guard (not skip-key))
5222 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5223 (format "%s(%c)" tag key))
5224 (`(,(and tag (pred stringp)) . ,_) tag)
5225 (_ (user-error "Invalid tag token: %S" token))))
5226 alist
5227 " "))
5229 (defun org-tag-alist-to-groups (alist)
5230 "Return group alist from tag ALIST.
5231 ALIST is an alist, as defined in `org-tag-alist' or
5232 `org-tag-persistent-alist', or produced with
5233 `org-tag-string-to-alist'. Return value is an alist following
5234 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5235 a string, summarizing TAGS, as a list of strings."
5236 (let (groups group-status current-group)
5237 (dolist (token alist (nreverse groups))
5238 (pcase token
5239 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5240 (`(,(or :endgroup :endgrouptag))
5241 (when (eq group-status 'append)
5242 (push (nreverse current-group) groups))
5243 (setq group-status nil))
5244 (`(:grouptags) (setq group-status 'append))
5245 ((and `(,tag . ,_) (guard group-status))
5246 (if (eq group-status 'append) (push tag current-group)
5247 (setq current-group (list tag))))
5248 (_ nil)))))
5250 (defvar org--file-cache (make-hash-table :test #'equal)
5251 "Hash table to store contents of files referenced via a URL.
5252 This is the cache of file URLs read using `org-file-contents'.")
5254 (defun org-reset-file-cache ()
5255 "Reset the cache of files downloaded by `org-file-contents'."
5256 (clrhash org--file-cache))
5258 (defun org-file-url-p (file)
5259 "Non-nil if FILE is a URL."
5260 (require 'ffap)
5261 (string-match-p ffap-url-regexp file))
5263 (defun org-file-contents (file &optional noerror nocache)
5264 "Return the contents of FILE, as a string.
5266 FILE can be a file name or URL.
5268 If FILE is a URL, download the contents. If the URL contents are
5269 already cached in the `org--file-cache' hash table, the download step
5270 is skipped.
5272 If NOERROR is non-nil, ignore the error when unable to read the FILE
5273 from file or URL.
5275 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5276 is available. This option applies only if FILE is a URL."
5277 (let* ((is-url (org-file-url-p file))
5278 (cache (and is-url
5279 (not nocache)
5280 (gethash file org--file-cache))))
5281 (cond
5282 (cache)
5283 (is-url
5284 (with-current-buffer (url-retrieve-synchronously file)
5285 (goto-char (point-min))
5286 ;; Move point to after the url-retrieve header.
5287 (search-forward "\n\n" nil :move)
5288 ;; Search for the success code only in the url-retrieve header.
5289 (if (save-excursion
5290 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5291 ;; Update the cache `org--file-cache' and return contents.
5292 (puthash file
5293 (buffer-substring-no-properties (point) (point-max))
5294 org--file-cache)
5295 (funcall (if noerror #'message #'user-error)
5296 "Unable to fetch file from %S"
5297 file))))
5299 (with-temp-buffer
5300 (condition-case nil
5301 (progn
5302 (insert-file-contents file)
5303 (buffer-string))
5304 (file-error
5305 (funcall (if noerror #'message #'user-error)
5306 "Unable to read file %S"
5307 file))))))))
5309 (defun org-extract-log-state-settings (x)
5310 "Extract the log state setting from a TODO keyword string.
5311 This will extract info from a string like \"WAIT(w@/!)\"."
5312 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5313 (let ((kw (match-string 1 x))
5314 (log1 (and (match-end 3) (match-string 3 x)))
5315 (log2 (and (match-end 4) (match-string 4 x))))
5316 (and (or log1 log2)
5317 (list kw
5318 (and log1 (if (equal log1 "!") 'time 'note))
5319 (and log2 (if (equal log2 "!") 'time 'note)))))))
5321 (defun org-remove-keyword-keys (list)
5322 "Remove a pair of parenthesis at the end of each string in LIST."
5323 (mapcar (lambda (x)
5324 (if (string-match "(.*)$" x)
5325 (substring x 0 (match-beginning 0))
5327 list))
5329 (defun org-assign-fast-keys (alist)
5330 "Assign fast keys to a keyword-key alist.
5331 Respect keys that are already there."
5332 (let (new e (alt ?0))
5333 (while (setq e (pop alist))
5334 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5335 (cdr e)) ;; Key already assigned.
5336 (push e new)
5337 (let ((clist (string-to-list (downcase (car e))))
5338 (used (append new alist)))
5339 (when (= (car clist) ?@)
5340 (pop clist))
5341 (while (and clist (rassoc (car clist) used))
5342 (pop clist))
5343 (unless clist
5344 (while (rassoc alt used)
5345 (cl-incf alt)))
5346 (push (cons (car e) (or (car clist) alt)) new))))
5347 (nreverse new)))
5349 ;;; Some variables used in various places
5351 (defvar org-window-configuration nil
5352 "Used in various places to store a window configuration.")
5353 (defvar org-selected-window nil
5354 "Used in various places to store a window configuration.")
5355 (defvar org-finish-function nil
5356 "Function to be called when `C-c C-c' is used.
5357 This is for getting out of special buffers like capture.")
5358 (defvar org-last-state)
5360 ;; Defined somewhere in this file, but used before definition.
5361 (defvar org-entities) ;; defined in org-entities.el
5362 (defvar org-struct-menu)
5363 (defvar org-org-menu)
5364 (defvar org-tbl-menu)
5366 ;;;; Define the Org mode
5368 ;; We use a before-change function to check if a table might need
5369 ;; an update.
5370 (defvar org-table-may-need-update t
5371 "Indicates that a table might need an update.
5372 This variable is set by `org-before-change-function'.
5373 `org-table-align' sets it back to nil.")
5374 (defun org-before-change-function (_beg _end)
5375 "Every change indicates that a table might need an update."
5376 (setq org-table-may-need-update t))
5377 (defvar org-mode-map)
5378 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5379 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5380 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5381 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5382 (defvar org-table-buffer-is-an nil)
5384 (defvar bidi-paragraph-direction)
5385 (defvar buffer-face-mode-face)
5387 (require 'outline)
5389 ;; Other stuff we need.
5390 (require 'time-date)
5391 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5392 (require 'easymenu)
5393 (autoload 'easy-menu-add "easymenu")
5394 (require 'overlay)
5396 ;; (require 'org-macs) moved higher up in the file before it is first used
5397 (require 'org-entities)
5398 ;; (require 'org-compat) moved higher up in the file before it is first used
5399 (require 'org-faces)
5400 (require 'org-list)
5401 (require 'org-pcomplete)
5402 (require 'org-src)
5403 (require 'org-footnote)
5404 (require 'org-macro)
5406 ;; babel
5407 (require 'ob)
5409 ;;;###autoload
5410 (define-derived-mode org-mode outline-mode "Org"
5411 "Outline-based notes management and organizer, alias
5412 \"Carsten's outline-mode for keeping track of everything.\"
5414 Org mode develops organizational tasks around a NOTES file which
5415 contains information about projects as plain text. Org mode is
5416 implemented on top of Outline mode, which is ideal to keep the content
5417 of large files well structured. It supports ToDo items, deadlines and
5418 time stamps, which magically appear in the diary listing of the Emacs
5419 calendar. Tables are easily created with a built-in table editor.
5420 Plain text URL-like links connect to websites, emails (VM), Usenet
5421 messages (Gnus), BBDB entries, and any files related to the project.
5422 For printing and sharing of notes, an Org file (or a part of it)
5423 can be exported as a structured ASCII or HTML file.
5425 The following commands are available:
5427 \\{org-mode-map}"
5429 ;; Get rid of Outline menus, they are not needed
5430 ;; Need to do this here because define-derived-mode sets up
5431 ;; the keymap so late. Still, it is a waste to call this each time
5432 ;; we switch another buffer into Org mode.
5433 (define-key org-mode-map [menu-bar headings] 'undefined)
5434 (define-key org-mode-map [menu-bar hide] 'undefined)
5435 (define-key org-mode-map [menu-bar show] 'undefined)
5437 (org-load-modules-maybe)
5438 (org-install-agenda-files-menu)
5439 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5440 (add-to-invisibility-spec '(org-hide-block . t))
5441 (setq-local outline-regexp org-outline-regexp)
5442 (setq-local outline-level 'org-outline-level)
5443 (setq bidi-paragraph-direction 'left-to-right)
5444 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5445 (unless org-display-table
5446 (setq org-display-table (make-display-table)))
5447 (set-display-table-slot
5448 org-display-table 4
5449 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5450 org-ellipsis)))
5451 (setq buffer-display-table org-display-table))
5452 (org-set-regexps-and-options)
5453 (org-set-font-lock-defaults)
5454 (when (and org-tag-faces (not org-tags-special-faces-re))
5455 ;; tag faces set outside customize.... force initialization.
5456 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5457 ;; Calc embedded
5458 (setq-local calc-embedded-open-mode "# ")
5459 ;; Modify a few syntax entries
5460 (modify-syntax-entry ?@ "w")
5461 (modify-syntax-entry ?\" "\"")
5462 (modify-syntax-entry ?\\ "_")
5463 (modify-syntax-entry ?~ "_")
5464 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5465 ;; Activate before-change-function
5466 (setq-local org-table-may-need-update t)
5467 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5468 ;; Check for running clock before killing a buffer
5469 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5470 ;; Initialize macros templates.
5471 (org-macro-initialize-templates)
5472 ;; Initialize radio targets.
5473 (org-update-radio-target-regexp)
5474 ;; Indentation.
5475 (setq-local indent-line-function 'org-indent-line)
5476 (setq-local indent-region-function 'org-indent-region)
5477 ;; Filling and auto-filling.
5478 (org-setup-filling)
5479 ;; Comments.
5480 (org-setup-comments-handling)
5481 ;; Initialize cache.
5482 (org-element-cache-reset)
5483 ;; Beginning/end of defun
5484 (setq-local beginning-of-defun-function 'org-backward-element)
5485 (setq-local end-of-defun-function
5486 (lambda ()
5487 (if (not (org-at-heading-p))
5488 (org-forward-element)
5489 (org-forward-element)
5490 (forward-char -1))))
5491 ;; Next error for sparse trees
5492 (setq-local next-error-function 'org-occur-next-match)
5493 ;; Make sure dependence stuff works reliably, even for users who set it
5494 ;; too late :-(
5495 (if org-enforce-todo-dependencies
5496 (add-hook 'org-blocker-hook
5497 'org-block-todo-from-children-or-siblings-or-parent)
5498 (remove-hook 'org-blocker-hook
5499 'org-block-todo-from-children-or-siblings-or-parent))
5500 (if org-enforce-todo-checkbox-dependencies
5501 (add-hook 'org-blocker-hook
5502 'org-block-todo-from-checkboxes)
5503 (remove-hook 'org-blocker-hook
5504 'org-block-todo-from-checkboxes))
5506 ;; Align options lines
5507 (setq-local
5508 align-mode-rules-list
5509 '((org-in-buffer-settings
5510 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5511 (modes . '(org-mode)))))
5513 ;; Imenu
5514 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5516 ;; Make isearch reveal context
5517 (setq-local outline-isearch-open-invisible-function
5518 (lambda (&rest _) (org-show-context 'isearch)))
5520 ;; Setup the pcomplete hooks
5521 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5522 (setq-local pcomplete-command-name-function 'org-command-at-point)
5523 (setq-local pcomplete-default-completion-function 'ignore)
5524 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5525 (setq-local pcomplete-termination-string "")
5526 (setq-local buffer-face-mode-face 'org-default)
5528 ;; If empty file that did not turn on Org mode automatically, make
5529 ;; it to.
5530 (when (and org-insert-mode-line-in-empty-file
5531 (called-interactively-p 'any)
5532 (= (point-min) (point-max)))
5533 (insert "# -*- mode: org -*-\n\n"))
5534 (unless org-inhibit-startup
5535 (org-unmodified
5536 (when org-startup-with-beamer-mode (org-beamer-mode))
5537 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5538 (org-table-map-tables
5539 (cond ((and org-startup-align-all-tables
5540 org-startup-shrink-all-tables)
5541 (lambda () (org-table-align) (org-table-shrink)))
5542 (org-startup-align-all-tables #'org-table-align)
5543 (t #'org-table-shrink))
5545 (when org-startup-with-inline-images (org-display-inline-images))
5546 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5547 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5548 (when org-startup-truncated (setq truncate-lines t))
5549 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5550 (org-refresh-effort-properties)))
5551 ;; Try to set `org-hide' face correctly.
5552 (let ((foreground (org-find-invisible-foreground)))
5553 (when foreground
5554 (set-face-foreground 'org-hide foreground))))
5556 ;; Update `customize-package-emacs-version-alist'
5557 (add-to-list 'customize-package-emacs-version-alist
5558 '(Org ("8.0" . "24.4")
5559 ("8.1" . "24.4")
5560 ("8.2" . "24.4")
5561 ("8.2.7" . "24.4")
5562 ("8.3" . "26.1")
5563 ("9.0" . "26.1")
5564 ("9.1" . "26.1")
5565 ("9.2" . "27.1")))
5567 (defvar org-mode-transpose-word-syntax-table
5568 (let ((st (make-syntax-table text-mode-syntax-table)))
5569 (dolist (c org-emphasis-alist st)
5570 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5572 (when (fboundp 'abbrev-table-put)
5573 (abbrev-table-put org-mode-abbrev-table
5574 :parents (list text-mode-abbrev-table)))
5576 (defun org-find-invisible-foreground ()
5577 (let ((candidates (remove
5578 "unspecified-bg"
5579 (nconc
5580 (list (face-background 'default)
5581 (face-background 'org-default))
5582 (mapcar
5583 (lambda (alist)
5584 (when (boundp alist)
5585 (cdr (assq 'background-color (symbol-value alist)))))
5586 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5587 (list (face-foreground 'org-hide))))))
5588 (car (remove nil candidates))))
5590 (defun org-current-time (&optional rounding-minutes past)
5591 "Current time, possibly rounded to ROUNDING-MINUTES.
5592 When ROUNDING-MINUTES is not an integer, fall back on the car of
5593 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5594 the rounding returns a past time."
5595 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5596 (car org-time-stamp-rounding-minutes)))
5597 (time (decode-time)) res)
5598 (if (< r 1)
5599 (current-time)
5600 (setq res
5601 (apply 'encode-time
5602 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5603 (nthcdr 2 time))))
5604 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5605 (seconds-to-time (- (float-time res) (* r 60)))
5606 res))))
5608 (defun org-today ()
5609 "Return today date, considering `org-extend-today-until'."
5610 (time-to-days
5611 (time-subtract (current-time)
5612 (list 0 (* 3600 org-extend-today-until) 0))))
5614 ;;;; Font-Lock stuff, including the activators
5616 (defvar org-mouse-map (make-sparse-keymap))
5617 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5618 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5619 (when org-mouse-1-follows-link
5620 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5621 (when org-tab-follows-link
5622 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5623 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5625 (require 'font-lock)
5627 (defconst org-non-link-chars "]\t\n\r<>")
5628 (defvar org-link-types-re nil
5629 "Matches a link that has a url-like prefix like \"http:\"")
5630 (defvar org-link-re-with-space nil
5631 "Matches a link with spaces, optional angular brackets around it.")
5632 (defvar org-link-re-with-space2 nil
5633 "Matches a link with spaces, optional angular brackets around it.")
5634 (defvar org-link-re-with-space3 nil
5635 "Matches a link with spaces, only for internal part in bracket links.")
5636 (defvar org-angle-link-re nil
5637 "Matches link with angular brackets, spaces are allowed.")
5638 (defvar org-plain-link-re nil
5639 "Matches plain link, without spaces.")
5640 (defvar org-bracket-link-regexp nil
5641 "Matches a link in double brackets.")
5642 (defvar org-bracket-link-analytic-regexp nil
5643 "Regular expression used to analyze links.
5644 Here is what the match groups contain after a match:
5645 1: http:
5646 2: http
5647 3: path
5648 4: [desc]
5649 5: desc")
5650 (defvar org-bracket-link-analytic-regexp++ nil
5651 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5652 (defvar org-any-link-re nil
5653 "Regular expression matching any link.")
5655 (defconst org-match-sexp-depth 3
5656 "Number of stacked braces for sub/superscript matching.")
5658 (defun org-create-multibrace-regexp (left right n)
5659 "Create a regular expression which will match a balanced sexp.
5660 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5661 as single character strings.
5662 The regexp returned will match the entire expression including the
5663 delimiters. It will also define a single group which contains the
5664 match except for the outermost delimiters. The maximum depth of
5665 stacked delimiters is N. Escaping delimiters is not possible."
5666 (let* ((nothing (concat "[^" left right "]*?"))
5667 (or "\\|")
5668 (re nothing)
5669 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5670 (while (> n 1)
5671 (setq n (1- n)
5672 re (concat re or next)
5673 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5674 (concat left "\\(" re "\\)" right)))
5676 (defconst org-match-substring-regexp
5677 (concat
5678 "\\(\\S-\\)\\([_^]\\)\\("
5679 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5680 "\\|"
5681 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5682 "\\|"
5683 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5684 "The regular expression matching a sub- or superscript.")
5686 (defconst org-match-substring-with-braces-regexp
5687 (concat
5688 "\\(\\S-\\)\\([_^]\\)"
5689 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5690 "The regular expression matching a sub- or superscript, forcing braces.")
5692 (defun org-make-link-regexps ()
5693 "Update the link regular expressions.
5694 This should be called after the variable `org-link-parameters' has changed."
5695 (let ((types-re (regexp-opt (org-link-types) t)))
5696 (setq org-link-types-re
5697 (concat "\\`" types-re ":")
5698 org-link-re-with-space
5699 (concat "<?" types-re ":"
5700 "\\([^" org-non-link-chars " ]"
5701 "[^" org-non-link-chars "]*"
5702 "[^" org-non-link-chars " ]\\)>?")
5703 org-link-re-with-space2
5704 (concat "<?" types-re ":"
5705 "\\([^" org-non-link-chars " ]"
5706 "[^\t\n\r]*"
5707 "[^" org-non-link-chars " ]\\)>?")
5708 org-link-re-with-space3
5709 (concat "<?" types-re ":"
5710 "\\([^" org-non-link-chars " ]"
5711 "[^\t\n\r]*\\)")
5712 org-angle-link-re
5713 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5714 types-re)
5715 org-plain-link-re
5716 (concat
5717 "\\<" types-re ":"
5718 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5719 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5720 org-bracket-link-regexp
5721 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5722 org-bracket-link-analytic-regexp
5723 (concat
5724 "\\[\\["
5725 "\\(" types-re ":\\)?"
5726 "\\([^]]+\\)"
5727 "\\]"
5728 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5729 "\\]")
5730 org-bracket-link-analytic-regexp++
5731 (concat
5732 "\\[\\["
5733 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5734 "\\([^]]+\\)"
5735 "\\]"
5736 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5737 "\\]")
5738 org-any-link-re
5739 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5740 org-angle-link-re "\\)\\|\\("
5741 org-plain-link-re "\\)"))))
5743 (org-make-link-regexps)
5745 (defvar org-emph-face nil)
5747 (defun org-do-emphasis-faces (limit)
5748 "Run through the buffer and emphasize strings."
5749 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5750 (car org-emphasis-regexp-components))))
5751 (catch :exit
5752 (while (re-search-forward quick-re limit t)
5753 (let* ((marker (match-string 2))
5754 (verbatim? (member marker '("~" "="))))
5755 (when (save-excursion
5756 (goto-char (match-beginning 0))
5757 ;; Do not match headline stars. Do not consider
5758 ;; stars of a headline as closing marker for bold
5759 ;; markup either. Do not match table hlines.
5760 (and
5761 (not (looking-at-p org-outline-regexp-bol))
5762 (not (and (equal marker "+")
5763 (org-match-line
5764 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5765 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5766 (not (string-match-p
5767 (concat org-outline-regexp-bol "\\'")
5768 (match-string 0)))))
5769 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5770 (font-lock-prepend-text-property
5771 (match-beginning 2) (match-end 2) 'face face)
5772 (when verbatim?
5773 (org-remove-flyspell-overlays-in
5774 (match-beginning 0) (match-end 0)))
5775 (add-text-properties (match-beginning 2) (match-end 2)
5776 '(font-lock-multiline t org-emphasis t))
5777 (when org-hide-emphasis-markers
5778 (add-text-properties (match-end 4) (match-beginning 5)
5779 '(invisible org-link))
5780 (add-text-properties (match-beginning 3) (match-end 3)
5781 '(invisible org-link)))
5782 (throw :exit t))))))))
5784 (defun org-emphasize (&optional char)
5785 "Insert or change an emphasis, i.e. a font like bold or italic.
5786 If there is an active region, change that region to a new emphasis.
5787 If there is no region, just insert the marker characters and position
5788 the cursor between them.
5789 CHAR should be the marker character. If it is a space, it means to
5790 remove the emphasis of the selected region.
5791 If CHAR is not given (for example in an interactive call) it will be
5792 prompted for."
5793 (interactive)
5794 (let ((erc org-emphasis-regexp-components)
5795 (string "") beg end move s)
5796 (if (org-region-active-p)
5797 (setq beg (region-beginning)
5798 end (region-end)
5799 string (buffer-substring beg end))
5800 (setq move t))
5802 (unless char
5803 (message "Emphasis marker or tag: [%s]"
5804 (mapconcat #'car org-emphasis-alist ""))
5805 (setq char (read-char-exclusive)))
5806 (if (equal char ?\s)
5807 (setq s ""
5808 move nil)
5809 (unless (assoc (char-to-string char) org-emphasis-alist)
5810 (user-error "No such emphasis marker: \"%c\"" char))
5811 (setq s (char-to-string char)))
5812 (while (and (> (length string) 1)
5813 (equal (substring string 0 1) (substring string -1))
5814 (assoc (substring string 0 1) org-emphasis-alist))
5815 (setq string (substring string 1 -1)))
5816 (setq string (concat s string s))
5817 (when beg (delete-region beg end))
5818 (unless (or (bolp)
5819 (string-match (concat "[" (nth 0 erc) "\n]")
5820 (char-to-string (char-before (point)))))
5821 (insert " "))
5822 (unless (or (eobp)
5823 (string-match (concat "[" (nth 1 erc) "\n]")
5824 (char-to-string (char-after (point)))))
5825 (insert " ") (backward-char 1))
5826 (insert string)
5827 (and move (backward-char 1))))
5829 (defconst org-nonsticky-props
5830 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5832 (defsubst org-rear-nonsticky-at (pos)
5833 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5835 (defun org-activate-links (limit)
5836 "Add link properties to links.
5837 This includes angle, plain, and bracket links."
5838 (catch :exit
5839 (while (re-search-forward org-any-link-re limit t)
5840 (let* ((start (match-beginning 0))
5841 (end (match-end 0))
5842 (style (cond ((eq ?< (char-after start)) 'angle)
5843 ((eq ?\[ (char-after (1+ start))) 'bracket)
5844 (t 'plain))))
5845 (when (and (memq style org-highlight-links)
5846 ;; Do not confuse plain links with tags.
5847 (not (and (eq style 'plain)
5848 (let ((face (get-text-property
5849 (max (1- start) (point-min)) 'face)))
5850 (if (consp face) (memq 'org-tag face)
5851 (eq 'org-tag face))))))
5852 (let* ((link-object (save-excursion
5853 (goto-char start)
5854 (save-match-data (org-element-link-parser))))
5855 (link (org-element-property :raw-link link-object))
5856 (type (org-element-property :type link-object))
5857 (path (org-element-property :path link-object))
5858 (properties ;for link's visible part
5859 (list
5860 'face (pcase (org-link-get-parameter type :face)
5861 ((and (pred functionp) face) (funcall face path))
5862 ((and (pred facep) face) face)
5863 ((and (pred consp) face) face) ;anonymous
5864 (_ 'org-link))
5865 'mouse-face (or (org-link-get-parameter type :mouse-face)
5866 'highlight)
5867 'keymap (or (org-link-get-parameter type :keymap)
5868 org-mouse-map)
5869 'help-echo (pcase (org-link-get-parameter type :help-echo)
5870 ((and (pred stringp) echo) echo)
5871 ((and (pred functionp) echo) echo)
5872 (_ (concat "LINK: " link)))
5873 'htmlize-link (pcase (org-link-get-parameter type
5874 :htmlize-link)
5875 ((and (pred functionp) f) (funcall f))
5876 (_ `(:uri ,link)))
5877 'font-lock-multiline t)))
5878 (org-remove-flyspell-overlays-in start end)
5879 (org-rear-nonsticky-at end)
5880 (if (not (eq 'bracket style))
5881 (add-text-properties start end properties)
5882 ;; Handle invisible parts in bracket links.
5883 (remove-text-properties start end '(invisible nil))
5884 (let ((hidden
5885 (append `(invisible
5886 ,(or (org-link-get-parameter type :display)
5887 'org-link))
5888 properties))
5889 (visible-start (or (match-beginning 4) (match-beginning 2)))
5890 (visible-end (or (match-end 4) (match-end 2))))
5891 (add-text-properties start visible-start hidden)
5892 (add-text-properties visible-start visible-end properties)
5893 (add-text-properties visible-end end hidden)
5894 (org-rear-nonsticky-at visible-start)
5895 (org-rear-nonsticky-at visible-end)))
5896 (let ((f (org-link-get-parameter type :activate-func)))
5897 (when (functionp f)
5898 (funcall f start end path (eq style 'bracket))))
5899 (throw :exit t))))) ;signal success
5900 nil))
5902 (defun org-activate-code (limit)
5903 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (remove-text-properties (match-beginning 0) (match-end 0)
5906 '(display t invisible t intangible t))
5909 (defcustom org-src-fontify-natively t
5910 "When non-nil, fontify code in code blocks.
5911 See also the `org-block' face."
5912 :type 'boolean
5913 :version "26.1"
5914 :package-version '(Org . "8.3")
5915 :group 'org-appearance
5916 :group 'org-babel)
5918 (defcustom org-allow-promoting-top-level-subtree nil
5919 "When non-nil, allow promoting a top level subtree.
5920 The leading star of the top level headline will be replaced
5921 by a #."
5922 :type 'boolean
5923 :version "24.1"
5924 :group 'org-appearance)
5926 (defun org-fontify-meta-lines-and-blocks (limit)
5927 (condition-case nil
5928 (org-fontify-meta-lines-and-blocks-1 limit)
5929 (error (message "org-mode fontification error in %S at %d"
5930 (current-buffer)
5931 (line-number-at-pos)))))
5933 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5934 "Fontify #+ lines and blocks."
5935 (let ((case-fold-search t))
5936 (when (re-search-forward
5937 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5938 limit t)
5939 (let ((beg (match-beginning 0))
5940 (block-start (match-end 0))
5941 (block-end nil)
5942 (lang (match-string 7))
5943 (beg1 (line-beginning-position 2))
5944 (dc1 (downcase (match-string 2)))
5945 (dc3 (downcase (match-string 3)))
5946 end end1 quoting block-type)
5947 (cond
5948 ((and (match-end 4) (equal dc3 "+begin"))
5949 ;; Truly a block
5950 (setq block-type (downcase (match-string 5))
5951 quoting (member block-type org-protecting-blocks))
5952 (when (re-search-forward
5953 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5954 nil t) ;; on purpose, we look further than LIMIT
5955 (setq end (min (point-max) (match-end 0))
5956 end1 (min (point-max) (1- (match-beginning 0))))
5957 (setq block-end (match-beginning 0))
5958 (when quoting
5959 (org-remove-flyspell-overlays-in beg1 end1)
5960 (remove-text-properties beg end
5961 '(display t invisible t intangible t)))
5962 (add-text-properties
5963 beg end '(font-lock-fontified t font-lock-multiline t))
5964 (add-text-properties beg beg1 '(face org-meta-line))
5965 (org-remove-flyspell-overlays-in beg beg1)
5966 (add-text-properties ; For end_src
5967 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5968 (org-remove-flyspell-overlays-in end1 end)
5969 (cond
5970 ((and lang (not (string= lang "")) org-src-fontify-natively)
5971 (org-src-font-lock-fontify-block lang block-start block-end)
5972 (add-text-properties beg1 block-end '(src-block t)))
5973 (quoting
5974 (add-text-properties beg1 (min (point-max) (1+ end1))
5975 (list 'face
5976 (list :inherit
5977 (let ((face-name
5978 (intern (format "org-block-%s" lang))))
5979 (append (and (facep face-name) (list face-name))
5980 '(org-block))))))) ; end of source block
5981 ((not org-fontify-quote-and-verse-blocks))
5982 ((string= block-type "quote")
5983 (add-face-text-property
5984 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5985 ((string= block-type "verse")
5986 (add-face-text-property
5987 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5988 (add-text-properties beg beg1 '(face org-block-begin-line))
5989 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5990 '(face org-block-end-line))
5992 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5993 (org-remove-flyspell-overlays-in
5994 (match-beginning 0)
5995 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5996 (add-text-properties
5997 beg (match-end 3)
5998 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5999 '(font-lock-fontified t invisible t)
6000 '(font-lock-fontified t face org-document-info-keyword)))
6001 (add-text-properties
6002 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6003 (if (string-equal dc1 "+title:")
6004 '(font-lock-fontified t face org-document-title)
6005 '(font-lock-fontified t face org-document-info))))
6006 ((string-prefix-p "+caption" dc1)
6007 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6008 (remove-text-properties (match-beginning 0) (match-end 0)
6009 '(display t invisible t intangible t))
6010 ;; Handle short captions.
6011 (save-excursion
6012 (beginning-of-line)
6013 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6014 (add-text-properties (line-beginning-position) (match-end 1)
6015 '(font-lock-fontified t face org-meta-line))
6016 (add-text-properties (match-end 0) (line-end-position)
6017 '(font-lock-fontified t face org-block))
6019 ((member dc3 '(" " ""))
6020 (org-remove-flyspell-overlays-in beg (match-end 0))
6021 (add-text-properties
6022 beg (match-end 0)
6023 '(font-lock-fontified t face font-lock-comment-face)))
6024 (t ;; just any other in-buffer setting, but not indented
6025 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6026 (remove-text-properties (match-beginning 0) (match-end 0)
6027 '(display t invisible t intangible t))
6028 (add-text-properties beg (match-end 0)
6029 '(font-lock-fontified t face org-meta-line))
6030 t))))))
6032 (defun org-fontify-drawers (limit)
6033 "Fontify drawers."
6034 (when (re-search-forward org-drawer-regexp limit t)
6035 (add-text-properties
6036 (match-beginning 0) (match-end 0)
6037 '(font-lock-fontified t face org-special-keyword))
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (defun org-fontify-macros (limit)
6042 "Fontify macros."
6043 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6044 (add-text-properties
6045 (match-beginning 0) (match-end 0)
6046 '(font-lock-fontified t face org-macro))
6047 (when org-hide-macro-markers
6048 (add-text-properties (match-end 2) (match-beginning 2)
6049 '(invisible t))
6050 (add-text-properties (match-beginning 1) (match-end 1)
6051 '(invisible t)))
6052 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6055 (defun org-activate-footnote-links (limit)
6056 "Add text properties for footnotes."
6057 (let ((fn (org-footnote-next-reference-or-definition limit)))
6058 (when fn
6059 (let* ((beg (nth 1 fn))
6060 (end (nth 2 fn))
6061 (label (car fn))
6062 (referencep (/= (line-beginning-position) beg)))
6063 (when (and referencep (nth 3 fn))
6064 (save-excursion
6065 (goto-char beg)
6066 (search-forward (or label "fn:"))
6067 (org-remove-flyspell-overlays-in beg (match-end 0))))
6068 (add-text-properties beg end
6069 (list 'mouse-face 'highlight
6070 'keymap org-mouse-map
6071 'help-echo
6072 (if referencep "Footnote reference"
6073 "Footnote definition")
6074 'font-lock-fontified t
6075 'font-lock-multiline t
6076 'face 'org-footnote))))))
6078 (defun org-activate-dates (limit)
6079 "Add text properties for dates."
6080 (when (and (re-search-forward org-tsr-regexp-both limit t)
6081 (not (equal (char-before (match-beginning 0)) 91)))
6082 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6083 (add-text-properties (match-beginning 0) (match-end 0)
6084 (list 'mouse-face 'highlight
6085 'keymap org-mouse-map))
6086 (org-rear-nonsticky-at (match-end 0))
6087 (when org-display-custom-times
6088 ;; If it's a date range, activate custom time for second date.
6089 (when (match-end 3)
6090 (org-display-custom-time (match-beginning 3) (match-end 3)))
6091 (org-display-custom-time (match-beginning 1) (match-end 1)))
6094 (defvar-local org-target-link-regexp nil
6095 "Regular expression matching radio targets in plain text.")
6097 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6098 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6099 border border border))
6100 "Regular expression matching a link target.")
6102 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6103 "Regular expression matching a radio target.")
6105 (defconst org-any-target-regexp
6106 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6107 "Regular expression matching any target.")
6109 (defun org-activate-target-links (limit)
6110 "Add text properties for target matches."
6111 (when org-target-link-regexp
6112 (let ((case-fold-search t))
6113 (when (re-search-forward org-target-link-regexp limit t)
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map
6118 'help-echo "Radio target link"
6119 'org-linked-text t))
6120 (org-rear-nonsticky-at (match-end 1))
6121 t))))
6123 (defun org-update-radio-target-regexp ()
6124 "Find all radio targets in this file and update the regular expression.
6125 Also refresh fontification if needed."
6126 (interactive)
6127 (let ((old-regexp org-target-link-regexp)
6128 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6129 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6130 (targets
6131 (org-with-wide-buffer
6132 (goto-char (point-min))
6133 (let (rtn)
6134 (while (re-search-forward org-radio-target-regexp nil t)
6135 ;; Make sure point is really within the object.
6136 (backward-char)
6137 (let ((obj (org-element-context)))
6138 (when (eq (org-element-type obj) 'radio-target)
6139 (cl-pushnew (org-element-property :value obj) rtn
6140 :test #'equal))))
6141 rtn))))
6142 (setq org-target-link-regexp
6143 (and targets
6144 (concat before-re
6145 (mapconcat
6146 (lambda (x)
6147 (replace-regexp-in-string
6148 " +" "\\s-+" (regexp-quote x) t t))
6149 targets
6150 "\\|")
6151 after-re)))
6152 (unless (equal old-regexp org-target-link-regexp)
6153 ;; Clean-up cache.
6154 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6155 ((not org-target-link-regexp) old-regexp)
6157 (concat before-re
6158 (mapconcat
6159 (lambda (re)
6160 (substring re (length before-re)
6161 (- (length after-re))))
6162 (list old-regexp org-target-link-regexp)
6163 "\\|")
6164 after-re)))))
6165 (org-with-wide-buffer
6166 (goto-char (point-min))
6167 (while (re-search-forward regexp nil t)
6168 (org-element-cache-refresh (match-beginning 1)))))
6169 ;; Re fontify buffer.
6170 (when (memq 'radio org-highlight-links)
6171 (org-restart-font-lock)))))
6173 (defvar org-latex-and-related-regexp nil
6174 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6176 (defun org-compute-latex-and-related-regexp ()
6177 "Compute regular expression for LaTeX, entities and sub/superscript.
6178 Result depends on variable `org-highlight-latex-and-related'."
6179 (setq-local
6180 org-latex-and-related-regexp
6181 (let* ((re-sub
6182 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6183 ((eq org-use-sub-superscripts '{})
6184 (list org-match-substring-with-braces-regexp))
6185 (org-use-sub-superscripts (list org-match-substring-regexp))))
6186 (re-latex
6187 (when (memq 'latex org-highlight-latex-and-related)
6188 (let ((matchers (plist-get org-format-latex-options :matchers)))
6189 (delq nil
6190 (mapcar (lambda (x)
6191 (and (member (car x) matchers) (nth 1 x)))
6192 org-latex-regexps)))))
6193 (re-entities
6194 (when (memq 'entities org-highlight-latex-and-related)
6195 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6196 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6198 (defun org-do-latex-and-related (limit)
6199 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6200 LIMIT bounds the search for syntax to highlight. Stop at first
6201 highlighted object, if any. Return t if some highlighting was
6202 done, nil otherwise."
6203 (when (org-string-nw-p org-latex-and-related-regexp)
6204 (catch 'found
6205 (while (re-search-forward org-latex-and-related-regexp limit t)
6206 (unless
6207 (cl-some
6208 (lambda (f)
6209 (memq f '(org-code org-verbatim underline org-special-keyword)))
6210 (save-excursion
6211 (goto-char (1+ (match-beginning 0)))
6212 (face-at-point nil t)))
6213 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6214 '(?_ ?^))
6216 0)))
6217 (font-lock-prepend-text-property
6218 (+ offset (match-beginning 0)) (match-end 0)
6219 'face 'org-latex-and-related)
6220 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6221 '(font-lock-multiline t)))
6222 (throw 'found t)))
6223 nil)))
6225 (defun org-restart-font-lock ()
6226 "Restart `font-lock-mode', to force refontification."
6227 (when (and (boundp 'font-lock-mode) font-lock-mode)
6228 (font-lock-mode -1)
6229 (font-lock-mode 1)))
6231 (defun org-activate-tags (limit)
6232 (when (re-search-forward
6233 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6234 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6235 (add-text-properties (match-beginning 1) (match-end 1)
6236 (list 'mouse-face 'highlight
6237 'keymap org-mouse-map))
6238 (org-rear-nonsticky-at (match-end 1))
6241 (defun org-outline-level ()
6242 "Compute the outline level of the heading at point.
6244 If this is called at a normal headline, the level is the number
6245 of stars. Use `org-reduced-level' to remove the effect of
6246 `org-odd-levels'. Unlike to `org-current-level', this function
6247 takes into consideration inlinetasks."
6248 (org-with-wide-buffer
6249 (end-of-line)
6250 (if (re-search-backward org-outline-regexp-bol nil t)
6251 (1- (- (match-end 0) (match-beginning 0)))
6252 0)))
6254 (defvar org-font-lock-keywords nil)
6256 (defsubst org-re-property (property &optional literal allow-null value)
6257 "Return a regexp matching a PROPERTY line.
6259 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6260 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6261 non-nil, match properties even without a value.
6263 Match group 3 is set to the value when it exists. If there is no
6264 value and ALLOW-NULL is non-nil, it is set to the empty string.
6266 With optional argument VALUE, match only property lines with
6267 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6268 unless LITERAL is non-nil."
6269 (concat
6270 "^\\(?4:[ \t]*\\)"
6271 (format "\\(?1::\\(?2:%s\\):\\)"
6272 (if literal property (regexp-quote property)))
6273 (cond (value
6274 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6275 (if literal value (regexp-quote value))))
6276 (allow-null
6277 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6279 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6281 (defconst org-property-re
6282 (org-re-property "\\S-+" 'literal t)
6283 "Regular expression matching a property line.
6284 There are four matching groups:
6285 1: :PROPKEY: including the leading and trailing colon,
6286 2: PROPKEY without the leading and trailing colon,
6287 3: PROPVAL without leading or trailing spaces,
6288 4: the indentation of the current line,
6289 5: trailing whitespace.")
6291 (defvar org-font-lock-hook nil
6292 "Functions to be called for special font lock stuff.")
6294 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6296 (defvar org-font-lock-set-keywords-hook nil
6297 "Functions that can manipulate `org-font-lock-extra-keywords'.
6298 This is called after `org-font-lock-extra-keywords' is defined, but before
6299 it is installed to be used by font lock. This can be useful if something
6300 needs to be inserted at a specific position in the font-lock sequence.")
6302 (defun org-font-lock-hook (limit)
6303 "Run `org-font-lock-hook' within LIMIT."
6304 (run-hook-with-args 'org-font-lock-hook limit))
6306 (defun org-set-font-lock-defaults ()
6307 "Set font lock defaults for the current buffer."
6308 (let* ((em org-fontify-emphasized-text)
6309 (lk org-highlight-links)
6310 (org-font-lock-extra-keywords
6311 (list
6312 ;; Call the hook
6313 '(org-font-lock-hook)
6314 ;; Headlines
6315 `(,(if org-fontify-whole-heading-line
6316 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6317 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6318 (1 (org-get-level-face 1))
6319 (2 (org-get-level-face 2))
6320 (3 (org-get-level-face 3)))
6321 ;; Table lines
6322 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6323 (1 'org-table t))
6324 ;; Table internals
6325 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6326 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6327 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6328 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6329 ;; Drawers
6330 '(org-fontify-drawers)
6331 ;; Properties
6332 (list org-property-re
6333 '(1 'org-special-keyword t)
6334 '(3 'org-property-value t))
6335 ;; Link related fontification.
6336 '(org-activate-links)
6337 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6338 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6339 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6340 (when (memq 'footnote lk) '(org-activate-footnote-links))
6341 ;; Targets.
6342 (list org-any-target-regexp '(0 'org-target t))
6343 ;; Diary sexps.
6344 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6345 ;; Macro
6346 '(org-fontify-macros)
6347 ;; TODO keyword
6348 (list (format org-heading-keyword-regexp-format
6349 org-todo-regexp)
6350 '(2 (org-get-todo-face 2) t))
6351 ;; DONE
6352 (if org-fontify-done-headline
6353 (list (format org-heading-keyword-regexp-format
6354 (concat
6355 "\\(?:"
6356 (mapconcat 'regexp-quote org-done-keywords "\\|")
6357 "\\)"))
6358 '(2 'org-headline-done t))
6359 nil)
6360 ;; Priorities
6361 '(org-font-lock-add-priority-faces)
6362 ;; Tags
6363 '(org-font-lock-add-tag-faces)
6364 ;; Tags groups
6365 (when (and org-group-tags org-tag-groups-alist)
6366 (list (concat org-outline-regexp-bol ".+\\(:"
6367 (regexp-opt (mapcar 'car org-tag-groups-alist))
6368 ":\\).*$")
6369 '(1 'org-tag-group prepend)))
6370 ;; Special keywords
6371 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6372 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6373 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6374 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6375 ;; Emphasis
6376 (when em '(org-do-emphasis-faces))
6377 ;; Checkboxes
6378 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6379 1 'org-checkbox prepend)
6380 (when (cdr (assq 'checkbox org-list-automatic-rules))
6381 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6382 (0 (org-get-checkbox-statistics-face) t)))
6383 ;; Description list items
6384 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6385 1 'org-list-dt prepend)
6386 ;; ARCHIVEd headings
6387 (list (concat
6388 org-outline-regexp-bol
6389 "\\(.*:" org-archive-tag ":.*\\)")
6390 '(1 'org-archived prepend))
6391 ;; Specials
6392 '(org-do-latex-and-related)
6393 '(org-fontify-entities)
6394 '(org-raise-scripts)
6395 ;; Code
6396 '(org-activate-code (1 'org-code t))
6397 ;; COMMENT
6398 (list (format
6399 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6400 org-todo-regexp
6401 org-comment-string)
6402 '(9 'org-special-keyword t))
6403 ;; Blocks and meta lines
6404 '(org-fontify-meta-lines-and-blocks))))
6405 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6406 (run-hooks 'org-font-lock-set-keywords-hook)
6407 ;; Now set the full font-lock-keywords
6408 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6409 (setq-local font-lock-defaults
6410 '(org-font-lock-keywords t nil nil backward-paragraph))
6411 (kill-local-variable 'font-lock-keywords)
6412 nil))
6414 (defun org-toggle-pretty-entities ()
6415 "Toggle the composition display of entities as UTF8 characters."
6416 (interactive)
6417 (setq-local org-pretty-entities (not org-pretty-entities))
6418 (org-restart-font-lock)
6419 (if org-pretty-entities
6420 (message "Entities are now displayed as UTF8 characters")
6421 (save-restriction
6422 (widen)
6423 (decompose-region (point-min) (point-max))
6424 (message "Entities are now displayed as plain text"))))
6426 (defvar-local org-custom-properties-overlays nil
6427 "List of overlays used for custom properties.")
6429 (defun org-toggle-custom-properties-visibility ()
6430 "Display or hide properties in `org-custom-properties'."
6431 (interactive)
6432 (if org-custom-properties-overlays
6433 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6434 (setq org-custom-properties-overlays nil))
6435 (when org-custom-properties
6436 (org-with-wide-buffer
6437 (goto-char (point-min))
6438 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6439 (while (re-search-forward regexp nil t)
6440 (let ((end (cdr (save-match-data (org-get-property-block)))))
6441 (when (and end (< (point) end))
6442 ;; Hide first custom property in current drawer.
6443 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6444 (overlay-put o 'invisible t)
6445 (overlay-put o 'org-custom-property t)
6446 (push o org-custom-properties-overlays))
6447 ;; Hide additional custom properties in the same drawer.
6448 (while (re-search-forward regexp end t)
6449 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6450 (overlay-put o 'invisible t)
6451 (overlay-put o 'org-custom-property t)
6452 (push o org-custom-properties-overlays)))))
6453 ;; Each entry is limited to a single property drawer.
6454 (outline-next-heading)))))))
6456 (defun org-fontify-entities (limit)
6457 "Find an entity to fontify."
6458 (let (ee)
6459 (when org-pretty-entities
6460 (catch 'match
6461 ;; "\_ "-family is left out on purpose. Only the first one,
6462 ;; i.e., "\_ ", could be fontified anyway, and it would be
6463 ;; confusing when adding a second white space character.
6464 (while (re-search-forward
6465 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6466 limit t)
6467 (when (and (not (org-at-comment-p))
6468 (setq ee (org-entity-get (match-string 1)))
6469 (= (length (nth 6 ee)) 1))
6470 (let* ((end (if (equal (match-string 2) "{}")
6471 (match-end 2)
6472 (match-end 1))))
6473 (add-text-properties
6474 (match-beginning 0) end
6475 (list 'font-lock-fontified t))
6476 (compose-region (match-beginning 0) end
6477 (nth 6 ee) nil)
6478 (backward-char 1)
6479 (throw 'match t))))
6480 nil))))
6482 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6483 "Fontify string S like in Org mode."
6484 (with-temp-buffer
6485 (insert s)
6486 (let ((org-odd-levels-only odd-levels))
6487 (org-mode)
6488 (org-font-lock-ensure)
6489 (buffer-string))))
6491 (defvar org-m nil)
6492 (defvar org-l nil)
6493 (defvar org-f nil)
6494 (defun org-get-level-face (n)
6495 "Get the right face for match N in font-lock matching of headlines."
6496 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6497 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6498 (if org-cycle-level-faces
6499 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6500 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6501 (cond
6502 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6503 ((eq n 2) org-f)
6504 (t (unless org-level-color-stars-only org-f))))
6506 (defun org-face-from-face-or-color (context inherit face-or-color)
6507 "Create a face list that inherits INHERIT, but sets the foreground color.
6508 When FACE-OR-COLOR is not a string, just return it."
6509 (if (stringp face-or-color)
6510 (list :inherit inherit
6511 (cdr (assoc context org-faces-easy-properties))
6512 face-or-color)
6513 face-or-color))
6515 (defun org-get-todo-face (kwd)
6516 "Get the right face for a TODO keyword KWD.
6517 If KWD is a number, get the corresponding match group."
6518 (when (numberp kwd) (setq kwd (match-string kwd)))
6519 (or (org-face-from-face-or-color
6520 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6521 (and (member kwd org-done-keywords) 'org-done)
6522 'org-todo))
6524 (defun org-get-priority-face (priority)
6525 "Get the right face for PRIORITY.
6526 PRIORITY is a character."
6527 (or (org-face-from-face-or-color
6528 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6529 'org-priority))
6531 (defun org-get-tag-face (tag)
6532 "Get the right face for TAG.
6533 If TAG is a number, get the corresponding match group."
6534 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6535 (or (org-face-from-face-or-color
6536 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6537 'org-tag)))
6539 (defun org-font-lock-add-priority-faces (limit)
6540 "Add the special priority faces."
6541 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6542 (add-text-properties
6543 (match-beginning 1) (match-end 1)
6544 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6545 'font-lock-fontified t))))
6547 (defun org-font-lock-add-tag-faces (limit)
6548 "Add the special tag faces."
6549 (when (and org-tag-faces org-tags-special-faces-re)
6550 (while (re-search-forward org-tags-special-faces-re limit t)
6551 (add-text-properties (match-beginning 1) (match-end 1)
6552 (list 'face (org-get-tag-face 1)
6553 'font-lock-fontified t))
6554 (backward-char 1))))
6556 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6557 "Remove fontification and activation overlays from links."
6558 (font-lock-default-unfontify-region beg end)
6559 (let* ((buffer-undo-list t)
6560 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6561 (inhibit-modification-hooks t)
6562 deactivate-mark buffer-file-name buffer-file-truename)
6563 (decompose-region beg end)
6564 (remove-text-properties beg end
6565 '(mouse-face t keymap t org-linked-text t
6566 invisible t intangible t
6567 org-emphasis t))
6568 (org-remove-font-lock-display-properties beg end)))
6570 (defconst org-script-display '(((raise -0.3) (height 0.7))
6571 ((raise 0.3) (height 0.7))
6572 ((raise -0.5))
6573 ((raise 0.5)))
6574 "Display properties for showing superscripts and subscripts.")
6576 (defun org-remove-font-lock-display-properties (beg end)
6577 "Remove specific display properties that have been added by font lock.
6578 The will remove the raise properties that are used to show superscripts
6579 and subscripts."
6580 (let (next prop)
6581 (while (< beg end)
6582 (setq next (next-single-property-change beg 'display nil end)
6583 prop (get-text-property beg 'display))
6584 (when (member prop org-script-display)
6585 (put-text-property beg next 'display nil))
6586 (setq beg next))))
6588 (defun org-raise-scripts (limit)
6589 "Add raise properties to sub/superscripts."
6590 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6591 (re-search-forward
6592 (if (eq org-use-sub-superscripts t)
6593 org-match-substring-regexp
6594 org-match-substring-with-braces-regexp)
6595 limit t))
6596 (let* ((pos (point)) table-p comment-p
6597 (mpos (match-beginning 3))
6598 (emph-p (get-text-property mpos 'org-emphasis))
6599 (link-p (get-text-property mpos 'mouse-face))
6600 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6601 (goto-char (point-at-bol))
6602 (setq table-p (looking-at-p org-table-dataline-regexp)
6603 comment-p (looking-at-p "^[ \t]*#[ +]"))
6604 (goto-char pos)
6605 ;; Handle a_b^c
6606 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6607 (unless (or comment-p emph-p link-p keyw-p)
6608 (put-text-property (match-beginning 3) (match-end 0)
6609 'display
6610 (if (equal (char-after (match-beginning 2)) ?^)
6611 (nth (if table-p 3 1) org-script-display)
6612 (nth (if table-p 2 0) org-script-display)))
6613 (add-text-properties (match-beginning 2) (match-end 2)
6614 (list 'invisible t))
6615 (when (and (eq (char-after (match-beginning 3)) ?{)
6616 (eq (char-before (match-end 3)) ?}))
6617 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6618 (list 'invisible t))
6619 (add-text-properties (1- (match-end 3)) (match-end 3)
6620 (list 'invisible t))))
6621 t)))
6623 ;;;; Visibility cycling, including org-goto and indirect buffer
6625 ;;; Cycling
6627 (defvar-local org-cycle-global-status nil)
6628 (put 'org-cycle-global-status 'org-state t)
6629 (defvar-local org-cycle-subtree-status nil)
6630 (put 'org-cycle-subtree-status 'org-state t)
6632 (defvar org-inlinetask-min-level)
6634 (defun org-unlogged-message (&rest args)
6635 "Display a message, but avoid logging it in the *Messages* buffer."
6636 (let ((message-log-max nil))
6637 (apply 'message args)))
6639 ;;;###autoload
6640 (defun org-cycle (&optional arg)
6641 "TAB-action and visibility cycling for Org mode.
6643 This is the command invoked in Org mode by the `TAB' key. Its main
6644 purpose is outline visibility cycling, but it also invokes other actions
6645 in special contexts.
6647 When this function is called with a `\\[universal-argument]' prefix, rotate \
6648 the entire
6649 buffer through 3 states (global cycling)
6650 1. OVERVIEW: Show only top-level headlines.
6651 2. CONTENTS: Show all headlines of all levels, but no body text.
6652 3. SHOW ALL: Show everything.
6654 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6655 switch to the startup visibility,
6656 determined by the variable `org-startup-folded', and by any VISIBILITY
6657 properties in the buffer.
6659 With a `\\[universal-argument] \\[universal-argument] \
6660 \\[universal-argument]' prefix argument, show the entire buffer, including
6661 any drawers.
6663 When inside a table, re-align the table and move to the next field.
6665 When point is at the beginning of a headline, rotate the subtree started
6666 by this line through 3 different states (local cycling)
6667 1. FOLDED: Only the main headline is shown.
6668 2. CHILDREN: The main headline and the direct children are shown.
6669 From this state, you can move to one of the children
6670 and zoom in further.
6671 3. SUBTREE: Show the entire subtree, including body text.
6672 If there is no subtree, switch directly from CHILDREN to FOLDED.
6674 When point is at the beginning of an empty headline and the variable
6675 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6676 of the headline by demoting and promoting it to likely levels. This
6677 speeds up creation document structure by pressing `TAB' once or several
6678 times right after creating a new headline.
6680 When there is a numeric prefix, go up to a heading with level ARG, do
6681 a `show-subtree' and return to the previous cursor position. If ARG
6682 is negative, go up that many levels.
6684 When point is not at the beginning of a headline, execute the global
6685 binding for `TAB', which is re-indenting the line. See the option
6686 `org-cycle-emulate-tab' for details.
6688 As a special case, if point is at the beginning of the buffer and there is
6689 no headline in line 1, this function will act as if called with prefix arg
6690 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6691 prefix arg, but only
6692 if the variable `org-cycle-global-at-bob' is t."
6693 (interactive "P")
6694 (org-load-modules-maybe)
6695 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6696 (and org-cycle-level-after-item/entry-creation
6697 (or (org-cycle-level)
6698 (org-cycle-item-indentation))))
6699 (let* ((limit-level
6700 (or org-cycle-max-level
6701 (and (boundp 'org-inlinetask-min-level)
6702 org-inlinetask-min-level
6703 (1- org-inlinetask-min-level))))
6704 (nstars (and limit-level
6705 (if org-odd-levels-only
6706 (and limit-level (1- (* limit-level 2)))
6707 limit-level)))
6708 (org-outline-regexp
6709 (if (not (derived-mode-p 'org-mode))
6710 outline-regexp
6711 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6712 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6713 (not (looking-at org-outline-regexp))))
6714 (org-cycle-hook
6715 (if bob-special
6716 (delq 'org-optimize-window-after-visibility-change
6717 (copy-sequence org-cycle-hook))
6718 org-cycle-hook))
6719 (pos (point)))
6721 (cond
6723 ((equal arg '(16))
6724 (setq last-command 'dummy)
6725 (org-set-startup-visibility)
6726 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6728 ((equal arg '(64))
6729 (outline-show-all)
6730 (org-unlogged-message "Entire buffer visible, including drawers"))
6732 ((equal arg '(4)) (org-cycle-internal-global))
6734 ;; Try hiding block at point.
6735 ((org-hide-block-toggle-maybe))
6737 ;; Try cdlatex TAB completion
6738 ((org-try-cdlatex-tab))
6740 ;; Table: enter it or move to the next field.
6741 ((org-at-table-p 'any)
6742 (if (org-at-table.el-p)
6743 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6744 Use `\\[org-edit-special]' to edit table.el tables"))
6745 (if arg (org-table-edit-field t)
6746 (org-table-justify-field-maybe)
6747 (call-interactively 'org-table-next-field))))
6749 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6751 ;; Global cycling: delegate to `org-cycle-internal-global'.
6752 (bob-special (org-cycle-internal-global))
6754 ;; Drawers: delegate to `org-flag-drawer'.
6755 ((save-excursion
6756 (beginning-of-line 1)
6757 (looking-at org-drawer-regexp))
6758 (org-flag-drawer ; toggle block visibility
6759 (not (get-char-property (match-end 0) 'invisible))))
6761 ;; Show-subtree, ARG levels up from here.
6762 ((integerp arg)
6763 (save-excursion
6764 (org-back-to-heading)
6765 (outline-up-heading (if (< arg 0) (- arg)
6766 (- (funcall outline-level) arg)))
6767 (org-show-subtree)))
6769 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6770 ((and (featurep 'org-inlinetask)
6771 (org-inlinetask-at-task-p)
6772 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6773 (org-inlinetask-toggle-visibility))
6775 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6776 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6777 (save-excursion (move-beginning-of-line 1)
6778 (looking-at org-outline-regexp)))
6779 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6780 (org-cycle-internal-local))
6782 ;; From there: TAB emulation and template completion.
6783 (buffer-read-only (org-back-to-heading))
6785 ((run-hook-with-args-until-success
6786 'org-tab-after-check-for-cycling-hook))
6788 ((org-try-structure-completion))
6790 ((run-hook-with-args-until-success
6791 'org-tab-before-tab-emulation-hook))
6793 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6794 (or (not (bolp))
6795 (not (looking-at org-outline-regexp))))
6796 (call-interactively (global-key-binding "\t")))
6798 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6799 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6800 (or (and (eq org-cycle-emulate-tab 'white)
6801 (= (match-end 0) (point-at-eol)))
6802 (and (eq org-cycle-emulate-tab 'whitestart)
6803 (>= (match-end 0) pos))))
6805 (eq org-cycle-emulate-tab t))
6806 (call-interactively (global-key-binding "\t")))
6808 (t (save-excursion
6809 (org-back-to-heading)
6810 (org-cycle)))))))
6812 (defun org-cycle-internal-global ()
6813 "Do the global cycling action."
6814 ;; Hack to avoid display of messages for .org attachments in Gnus
6815 (let ((ga (string-match "\\*fontification" (buffer-name))))
6816 (cond
6817 ((and (eq last-command this-command)
6818 (eq org-cycle-global-status 'overview))
6819 ;; We just created the overview - now do table of contents
6820 ;; This can be slow in very large buffers, so indicate action
6821 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6822 (unless ga (org-unlogged-message "CONTENTS..."))
6823 (org-content)
6824 (unless ga (org-unlogged-message "CONTENTS...done"))
6825 (setq org-cycle-global-status 'contents)
6826 (run-hook-with-args 'org-cycle-hook 'contents))
6828 ((and (eq last-command this-command)
6829 (eq org-cycle-global-status 'contents))
6830 ;; We just showed the table of contents - now show everything
6831 (run-hook-with-args 'org-pre-cycle-hook 'all)
6832 (outline-show-all)
6833 (unless ga (org-unlogged-message "SHOW ALL"))
6834 (setq org-cycle-global-status 'all)
6835 (run-hook-with-args 'org-cycle-hook 'all))
6838 ;; Default action: go to overview
6839 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6840 (org-overview)
6841 (unless ga (org-unlogged-message "OVERVIEW"))
6842 (setq org-cycle-global-status 'overview)
6843 (run-hook-with-args 'org-cycle-hook 'overview)))))
6845 (defvar org-called-with-limited-levels nil
6846 "Non-nil when `org-with-limited-levels' is currently active.")
6848 (defun org-invisible-p (&optional pos)
6849 "Non-nil if the character after POS is invisible.
6850 If POS is nil, use `point' instead."
6851 (get-char-property (or pos (point)) 'invisible))
6853 (defun org-cycle-internal-local ()
6854 "Do the local cycling action."
6855 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6856 ;; First, determine end of headline (EOH), end of subtree or item
6857 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6858 (save-excursion
6859 (if (org-at-item-p)
6860 (progn
6861 (beginning-of-line)
6862 (setq struct (org-list-struct))
6863 (setq eoh (point-at-eol))
6864 (setq eos (org-list-get-item-end-before-blank (point) struct))
6865 (setq has-children (org-list-has-child-p (point) struct)))
6866 (org-back-to-heading)
6867 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6868 (setq eos (save-excursion (org-end-of-subtree t t)
6869 (when (bolp) (backward-char)) (point)))
6870 (setq has-children
6871 (or (save-excursion
6872 (let ((level (funcall outline-level)))
6873 (outline-next-heading)
6874 (and (org-at-heading-p t)
6875 (> (funcall outline-level) level))))
6876 (save-excursion
6877 (org-list-search-forward (org-item-beginning-re) eos t)))))
6878 ;; Determine end invisible part of buffer (EOL)
6879 (beginning-of-line 2)
6880 (while (and (not (eobp)) ;This is like `next-line'.
6881 (get-char-property (1- (point)) 'invisible))
6882 (goto-char (next-single-char-property-change (point) 'invisible))
6883 (and (eolp) (beginning-of-line 2)))
6884 (setq eol (point)))
6885 ;; Find out what to do next and set `this-command'
6886 (cond
6887 ((= eos eoh)
6888 ;; Nothing is hidden behind this heading
6889 (unless (org-before-first-heading-p)
6890 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6891 (org-unlogged-message "EMPTY ENTRY")
6892 (setq org-cycle-subtree-status nil)
6893 (save-excursion
6894 (goto-char eos)
6895 (outline-next-heading)
6896 (when (org-invisible-p) (org-flag-heading nil))))
6897 ((and (or (>= eol eos)
6898 (not (string-match "\\S-" (buffer-substring eol eos))))
6899 (or has-children
6900 (not (setq children-skipped
6901 org-cycle-skip-children-state-if-no-children))))
6902 ;; Entire subtree is hidden in one line: children view
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-pre-cycle-hook 'children))
6905 (if (org-at-item-p)
6906 (org-list-set-item-visibility (point-at-bol) struct 'children)
6907 (org-show-entry)
6908 (org-with-limited-levels (org-show-children))
6909 ;; FIXME: This slows down the func way too much.
6910 ;; How keep drawers hidden in subtree anyway?
6911 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6912 ;; (org-cycle-hide-drawers 'subtree))
6914 ;; Fold every list in subtree to top-level items.
6915 (when (eq org-cycle-include-plain-lists 'integrate)
6916 (save-excursion
6917 (org-back-to-heading)
6918 (while (org-list-search-forward (org-item-beginning-re) eos t)
6919 (beginning-of-line 1)
6920 (let* ((struct (org-list-struct))
6921 (prevs (org-list-prevs-alist struct))
6922 (end (org-list-get-bottom-point struct)))
6923 (dolist (e (org-list-get-all-items (point) struct prevs))
6924 (org-list-set-item-visibility e struct 'folded))
6925 (goto-char (if (< end eos) end eos)))))))
6926 (org-unlogged-message "CHILDREN")
6927 (save-excursion
6928 (goto-char eos)
6929 (outline-next-heading)
6930 (when (org-invisible-p) (org-flag-heading nil)))
6931 (setq org-cycle-subtree-status 'children)
6932 (unless (org-before-first-heading-p)
6933 (run-hook-with-args 'org-cycle-hook 'children)))
6934 ((or children-skipped
6935 (and (eq last-command this-command)
6936 (eq org-cycle-subtree-status 'children)))
6937 ;; We just showed the children, or no children are there,
6938 ;; now show everything.
6939 (unless (org-before-first-heading-p)
6940 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6941 (outline-flag-region eoh eos nil)
6942 (org-unlogged-message
6943 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6944 (setq org-cycle-subtree-status 'subtree)
6945 (unless (org-before-first-heading-p)
6946 (run-hook-with-args 'org-cycle-hook 'subtree)))
6948 ;; Default action: hide the subtree.
6949 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6950 (outline-flag-region eoh eos t)
6951 (org-unlogged-message "FOLDED")
6952 (setq org-cycle-subtree-status 'folded)
6953 (unless (org-before-first-heading-p)
6954 (run-hook-with-args 'org-cycle-hook 'folded))))))
6956 ;;;###autoload
6957 (defun org-global-cycle (&optional arg)
6958 "Cycle the global visibility. For details see `org-cycle'.
6959 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6960 With a numeric prefix, show all headlines up to that level."
6961 (interactive "P")
6962 (let ((org-cycle-include-plain-lists
6963 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6964 (cond
6965 ((integerp arg)
6966 (outline-show-all)
6967 (outline-hide-sublevels arg)
6968 (setq org-cycle-global-status 'contents))
6969 ((equal arg '(4))
6970 (org-set-startup-visibility)
6971 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6973 (org-cycle '(4))))))
6975 (defun org-set-startup-visibility ()
6976 "Set the visibility required by startup options and properties."
6977 (cond
6978 ((eq org-startup-folded t)
6979 (org-overview))
6980 ((eq org-startup-folded 'content)
6981 (org-content))
6982 ((or (eq org-startup-folded 'showeverything)
6983 (eq org-startup-folded nil))
6984 (outline-show-all)))
6985 (unless (eq org-startup-folded 'showeverything)
6986 (when org-hide-block-startup (org-hide-block-all))
6987 (org-set-visibility-according-to-property 'no-cleanup)
6988 (org-cycle-hide-archived-subtrees 'all)
6989 (org-cycle-hide-drawers 'all)
6990 (org-cycle-show-empty-lines t)))
6992 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6993 "Switch subtree visibilities according to :VISIBILITY: property."
6994 (interactive)
6995 (org-with-wide-buffer
6996 (goto-char (point-min))
6997 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6998 (if (not (org-at-property-p)) (outline-next-heading)
6999 (let ((state (match-string 3)))
7000 (save-excursion
7001 (org-back-to-heading t)
7002 (outline-hide-subtree)
7003 (org-reveal)
7004 (cond
7005 ((equal state "folded")
7006 (outline-hide-subtree))
7007 ((equal state "children")
7008 (org-show-hidden-entry)
7009 (org-show-children))
7010 ((equal state "content")
7011 (save-excursion
7012 (save-restriction
7013 (org-narrow-to-subtree)
7014 (org-content))))
7015 ((member state '("all" "showall"))
7016 (outline-show-subtree)))))))
7017 (unless no-cleanup
7018 (org-cycle-hide-archived-subtrees 'all)
7019 (org-cycle-hide-drawers 'all)
7020 (org-cycle-show-empty-lines 'all))))
7022 ;; This function uses outline-regexp instead of the more fundamental
7023 ;; org-outline-regexp so that org-cycle-global works outside of Org
7024 ;; buffers, where outline-regexp is needed.
7025 (defun org-overview ()
7026 "Switch to overview mode, showing only top-level headlines.
7027 This shows all headlines with a level equal or greater than the level
7028 of the first headline in the buffer. This is important, because if the
7029 first headline is not level one, then (hide-sublevels 1) gives confusing
7030 results."
7031 (interactive)
7032 (save-excursion
7033 (let ((level
7034 (save-excursion
7035 (goto-char (point-min))
7036 (when (re-search-forward (concat "^" outline-regexp) nil t)
7037 (goto-char (match-beginning 0))
7038 (funcall outline-level)))))
7039 (and level (outline-hide-sublevels level)))))
7041 (defun org-content (&optional arg)
7042 "Show all headlines in the buffer, like a table of contents.
7043 With numerical argument N, show content up to level N."
7044 (interactive "P")
7045 (org-overview)
7046 (save-excursion
7047 ;; Visit all headings and show their offspring
7048 (and (integerp arg) (org-overview))
7049 (goto-char (point-max))
7050 (catch 'exit
7051 (while (and (progn (condition-case nil
7052 (outline-previous-visible-heading 1)
7053 (error (goto-char (point-min))))
7055 (looking-at org-outline-regexp))
7056 (if (integerp arg)
7057 (org-show-children (1- arg))
7058 (outline-show-branches))
7059 (when (bobp) (throw 'exit nil))))))
7061 (defun org-optimize-window-after-visibility-change (state)
7062 "Adjust the window after a change in outline visibility.
7063 This function is the default value of the hook `org-cycle-hook'."
7064 (when (get-buffer-window (current-buffer))
7065 (cond
7066 ((eq state 'content) nil)
7067 ((eq state 'all) nil)
7068 ((eq state 'folded) nil)
7069 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7070 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7072 (defun org-remove-empty-overlays-at (pos)
7073 "Remove outline overlays that do not contain non-white stuff."
7074 (dolist (o (overlays-at pos))
7075 (and (eq 'outline (overlay-get o 'invisible))
7076 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7077 (overlay-end o))))
7078 (delete-overlay o))))
7080 (defun org-clean-visibility-after-subtree-move ()
7081 "Fix visibility issues after moving a subtree."
7082 ;; First, find a reasonable region to look at:
7083 ;; Start two siblings above, end three below
7084 (let* ((beg (save-excursion
7085 (and (org-get-last-sibling)
7086 (org-get-last-sibling))
7087 (point)))
7088 (end (save-excursion
7089 (and (org-get-next-sibling)
7090 (org-get-next-sibling)
7091 (org-get-next-sibling))
7092 (if (org-at-heading-p)
7093 (point-at-eol)
7094 (point))))
7095 (level (looking-at "\\*+"))
7096 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7097 (save-excursion
7098 (save-restriction
7099 (narrow-to-region beg end)
7100 (when re
7101 ;; Properly fold already folded siblings
7102 (goto-char (point-min))
7103 (while (re-search-forward re nil t)
7104 (when (and (not (org-invisible-p))
7105 (save-excursion
7106 (goto-char (point-at-eol)) (org-invisible-p)))
7107 (outline-hide-entry))))
7108 (org-cycle-show-empty-lines 'overview)
7109 (org-cycle-hide-drawers 'overview)))))
7111 (defun org-cycle-show-empty-lines (state)
7112 "Show empty lines above all visible headlines.
7113 The region to be covered depends on STATE when called through
7114 `org-cycle-hook'. Lisp program can use t for STATE to get the
7115 entire buffer covered. Note that an empty line is only shown if there
7116 are at least `org-cycle-separator-lines' empty lines before the headline."
7117 (when (/= org-cycle-separator-lines 0)
7118 (save-excursion
7119 (let* ((n (abs org-cycle-separator-lines))
7120 (re (cond
7121 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7122 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7123 (t (let ((ns (number-to-string (- n 2))))
7124 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7125 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7126 beg end)
7127 (cond
7128 ((memq state '(overview contents t))
7129 (setq beg (point-min) end (point-max)))
7130 ((memq state '(children folded))
7131 (setq beg (point)
7132 end (progn (org-end-of-subtree t t)
7133 (line-beginning-position 2)))))
7134 (when beg
7135 (goto-char beg)
7136 (while (re-search-forward re end t)
7137 (unless (get-char-property (match-end 1) 'invisible)
7138 (let ((e (match-end 1))
7139 (b (if (>= org-cycle-separator-lines 0)
7140 (match-beginning 1)
7141 (save-excursion
7142 (goto-char (match-beginning 0))
7143 (skip-chars-backward " \t\n")
7144 (line-end-position)))))
7145 (outline-flag-region b e nil))))))))
7146 ;; Never hide empty lines at the end of the file.
7147 (save-excursion
7148 (goto-char (point-max))
7149 (outline-previous-heading)
7150 (outline-end-of-heading)
7151 (when (and (looking-at "[ \t\n]+")
7152 (= (match-end 0) (point-max)))
7153 (outline-flag-region (point) (match-end 0) nil))))
7155 (defun org-show-empty-lines-in-parent ()
7156 "Move to the parent and re-show empty lines before visible headlines."
7157 (save-excursion
7158 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7159 (org-cycle-show-empty-lines context))))
7161 (defun org-files-list ()
7162 "Return `org-agenda-files' list, plus all open Org files.
7163 This is useful for operations that need to scan all of a user's
7164 open and agenda-wise Org files."
7165 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7166 (dolist (buf (buffer-list))
7167 (with-current-buffer buf
7168 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7169 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7170 files))
7172 (defsubst org-entry-beginning-position ()
7173 "Return the beginning position of the current entry."
7174 (save-excursion (org-back-to-heading t) (point)))
7176 (defsubst org-entry-end-position ()
7177 "Return the end position of the current entry."
7178 (save-excursion (outline-next-heading) (point)))
7180 (defun org-cycle-hide-drawers (state &optional exceptions)
7181 "Re-hide all drawers after a visibility state change.
7182 STATE should be one of the symbols listed in the docstring of
7183 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7184 a list of strings specifying which drawers should not be hidden."
7185 (when (and (derived-mode-p 'org-mode)
7186 (not (memq state '(overview folded contents))))
7187 (save-excursion
7188 (let* ((globalp (eq state 'all))
7189 (beg (if globalp (point-min) (point)))
7190 (end (if globalp (point-max)
7191 (if (eq state 'children)
7192 (save-excursion (outline-next-heading) (point))
7193 (org-end-of-subtree t)))))
7194 (goto-char beg)
7195 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7196 (unless (member-ignore-case (match-string 1) exceptions)
7197 (let ((drawer (org-element-at-point)))
7198 (when (memq (org-element-type drawer) '(drawer property-drawer))
7199 (org-flag-drawer t drawer)
7200 ;; Make sure to skip drawer entirely or we might flag
7201 ;; it another time when matching its ending line with
7202 ;; `org-drawer-regexp'.
7203 (goto-char (org-element-property :end drawer))))))))))
7205 (defun org-flag-drawer (flag &optional element)
7206 "When FLAG is non-nil, hide the drawer we are at.
7207 Otherwise make it visible. When optional argument ELEMENT is
7208 a parsed drawer, as returned by `org-element-at-point', hide or
7209 show that drawer instead."
7210 (let ((drawer (or element
7211 (and (save-excursion
7212 (beginning-of-line)
7213 (looking-at-p org-drawer-regexp))
7214 (org-element-at-point)))))
7215 (when (memq (org-element-type drawer) '(drawer property-drawer))
7216 (let ((post (org-element-property :post-affiliated drawer)))
7217 (save-excursion
7218 (outline-flag-region
7219 (progn (goto-char post) (line-end-position))
7220 (progn (goto-char (org-element-property :end drawer))
7221 (skip-chars-backward " \r\t\n")
7222 (line-end-position))
7223 flag))
7224 ;; When the drawer is hidden away, make sure point lies in
7225 ;; a visible part of the buffer.
7226 (when (and flag (> (line-beginning-position) post))
7227 (goto-char post))))))
7229 (defun org-subtree-end-visible-p ()
7230 "Is the end of the current subtree visible?"
7231 (pos-visible-in-window-p
7232 (save-excursion (org-end-of-subtree t) (point))))
7234 (defun org-first-headline-recenter ()
7235 "Move cursor to the first headline and recenter the headline."
7236 (let ((window (get-buffer-window)))
7237 (when window
7238 (goto-char (point-min))
7239 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7240 (set-window-start window (line-beginning-position))))))
7242 ;;; Saving and restoring visibility
7244 (defun org-outline-overlay-data (&optional use-markers)
7245 "Return a list of the locations of all outline overlays.
7246 These are overlays with the `invisible' property value `outline'.
7247 The return value is a list of cons cells, with start and stop
7248 positions for each overlay.
7249 If USE-MARKERS is set, return the positions as markers."
7250 (let (beg end)
7251 (org-with-wide-buffer
7252 (delq nil
7253 (mapcar (lambda (o)
7254 (when (eq (overlay-get o 'invisible) 'outline)
7255 (setq beg (overlay-start o)
7256 end (overlay-end o))
7257 (and beg end (> end beg)
7258 (if use-markers
7259 (cons (copy-marker beg)
7260 (copy-marker end t))
7261 (cons beg end)))))
7262 (overlays-in (point-min) (point-max)))))))
7264 (defun org-set-outline-overlay-data (data)
7265 "Create visibility overlays for all positions in DATA.
7266 DATA should have been made by `org-outline-overlay-data'."
7267 (org-with-wide-buffer
7268 (outline-show-all)
7269 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7271 ;;; Folding of blocks
7273 (defvar-local org-hide-block-overlays nil
7274 "Overlays hiding blocks.")
7276 (defun org-block-map (function &optional start end)
7277 "Call FUNCTION at the head of all source blocks in the current buffer.
7278 Optional arguments START and END can be used to limit the range."
7279 (let ((start (or start (point-min)))
7280 (end (or end (point-max))))
7281 (save-excursion
7282 (goto-char start)
7283 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7284 (save-excursion
7285 (save-match-data
7286 (goto-char (match-beginning 0))
7287 (funcall function)))))))
7289 (defun org-hide-block-toggle-all ()
7290 "Toggle the visibility of all blocks in the current buffer."
7291 (org-block-map 'org-hide-block-toggle))
7293 (defun org-hide-block-all ()
7294 "Fold all blocks in the current buffer."
7295 (interactive)
7296 (org-show-block-all)
7297 (org-block-map 'org-hide-block-toggle-maybe))
7299 (defun org-show-block-all ()
7300 "Unfold all blocks in the current buffer."
7301 (interactive)
7302 (mapc #'delete-overlay org-hide-block-overlays)
7303 (setq org-hide-block-overlays nil))
7305 (defun org-hide-block-toggle-maybe ()
7306 "Toggle visibility of block at point.
7307 Unlike to `org-hide-block-toggle', this function does not throw
7308 an error. Return a non-nil value when toggling is successful."
7309 (interactive)
7310 (ignore-errors (org-hide-block-toggle)))
7312 (defun org-hide-block-toggle (&optional force)
7313 "Toggle the visibility of the current block.
7314 When optional argument FORCE is `off', make block visible. If it
7315 is non-nil, hide it unconditionally. Throw an error when not at
7316 a block. Return a non-nil value when toggling is successful."
7317 (interactive)
7318 (let ((element (org-element-at-point)))
7319 (unless (memq (org-element-type element)
7320 '(center-block comment-block dynamic-block example-block
7321 export-block quote-block special-block
7322 src-block verse-block))
7323 (user-error "Not at a block"))
7324 (let* ((start (save-excursion
7325 (goto-char (org-element-property :post-affiliated element))
7326 (line-end-position)))
7327 (end (save-excursion
7328 (goto-char (org-element-property :end element))
7329 (skip-chars-backward " \r\t\n")
7330 (line-end-position)))
7331 (overlays (overlays-at start)))
7332 (cond
7333 ;; Do nothing when not before or at the block opening line or
7334 ;; at the block closing line.
7335 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7336 ((and (not (eq force 'off))
7337 (not (memq t (mapcar
7338 (lambda (o)
7339 (eq (overlay-get o 'invisible) 'org-hide-block))
7340 overlays))))
7341 (let ((ov (make-overlay start end)))
7342 (overlay-put ov 'invisible 'org-hide-block)
7343 ;; Make the block accessible to `isearch'.
7344 (overlay-put
7345 ov 'isearch-open-invisible
7346 (lambda (ov)
7347 (when (memq ov org-hide-block-overlays)
7348 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7349 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7350 (delete-overlay ov))))
7351 (push ov org-hide-block-overlays)
7352 ;; When the block is hidden away, make sure point is left in
7353 ;; a visible part of the buffer.
7354 (when (> (line-beginning-position) start)
7355 (goto-char start)
7356 (beginning-of-line))
7357 ;; Signal successful toggling.
7359 ((or (not force) (eq force 'off))
7360 (dolist (ov overlays t)
7361 (when (memq ov org-hide-block-overlays)
7362 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7363 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7364 (delete-overlay ov))))))))
7366 ;; Remove overlays when changing major mode
7367 (add-hook 'org-mode-hook
7368 (lambda () (add-hook 'change-major-mode-hook
7369 'org-show-block-all 'append 'local)))
7371 ;;; Org-goto
7373 (defvar org-goto-window-configuration nil)
7374 (defvar org-goto-marker nil)
7375 (defvar org-goto-map)
7376 (defun org-goto-map ()
7377 "Set the keymap `org-goto'."
7378 (setq org-goto-map
7379 (let ((map (make-sparse-keymap)))
7380 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7381 mouse-drag-region universal-argument org-occur)))
7382 (dolist (cmd cmds)
7383 (substitute-key-definition cmd cmd map global-map)))
7384 (suppress-keymap map)
7385 (org-defkey map "\C-m" 'org-goto-ret)
7386 (org-defkey map [(return)] 'org-goto-ret)
7387 (org-defkey map [(left)] 'org-goto-left)
7388 (org-defkey map [(right)] 'org-goto-right)
7389 (org-defkey map [(control ?g)] 'org-goto-quit)
7390 (org-defkey map "\C-i" 'org-cycle)
7391 (org-defkey map [(tab)] 'org-cycle)
7392 (org-defkey map [(down)] 'outline-next-visible-heading)
7393 (org-defkey map [(up)] 'outline-previous-visible-heading)
7394 (if org-goto-auto-isearch
7395 (if (fboundp 'define-key-after)
7396 (define-key-after map [t] 'org-goto-local-auto-isearch)
7397 nil)
7398 (org-defkey map "q" 'org-goto-quit)
7399 (org-defkey map "n" 'outline-next-visible-heading)
7400 (org-defkey map "p" 'outline-previous-visible-heading)
7401 (org-defkey map "f" 'outline-forward-same-level)
7402 (org-defkey map "b" 'outline-backward-same-level)
7403 (org-defkey map "u" 'outline-up-heading))
7404 (org-defkey map "/" 'org-occur)
7405 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7406 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7407 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7408 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7409 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7410 map)))
7412 (defconst org-goto-help
7413 "Browse buffer copy, to find location or copy text.%s
7414 RET=jump to location C-g=quit and return to previous location
7415 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7417 (defvar org-goto-start-pos) ; dynamically scoped parameter
7419 (defun org-goto (&optional alternative-interface)
7420 "Look up a different location in the current file, keeping current visibility.
7422 When you want look-up or go to a different location in a
7423 document, the fastest way is often to fold the entire buffer and
7424 then dive into the tree. This method has the disadvantage, that
7425 the previous location will be folded, which may not be what you
7426 want.
7428 This command works around this by showing a copy of the current
7429 buffer in an indirect buffer, in overview mode. You can dive
7430 into the tree in that copy, use org-occur and incremental search
7431 to find a location. When pressing RET or `Q', the command
7432 returns to the original buffer in which the visibility is still
7433 unchanged. After RET it will also jump to the location selected
7434 in the indirect buffer and expose the headline hierarchy above.
7436 With a prefix argument, use the alternative interface: e.g., if
7437 `org-goto-interface' is `outline' use `outline-path-completion'."
7438 (interactive "P")
7439 (org-goto-map)
7440 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7441 (org-refile-use-outline-path t)
7442 (org-refile-target-verify-function nil)
7443 (interface
7444 (if (not alternative-interface)
7445 org-goto-interface
7446 (if (eq org-goto-interface 'outline)
7447 'outline-path-completion
7448 'outline)))
7449 (org-goto-start-pos (point))
7450 (selected-point
7451 (if (eq interface 'outline)
7452 (car (org-get-location (current-buffer) org-goto-help))
7453 (let ((pa (org-refile-get-location "Goto")))
7454 (org-refile-check-position pa)
7455 (nth 3 pa)))))
7456 (if selected-point
7457 (progn
7458 (org-mark-ring-push org-goto-start-pos)
7459 (goto-char selected-point)
7460 (when (or (org-invisible-p) (org-invisible-p2))
7461 (org-show-context 'org-goto)))
7462 (message "Quit"))))
7464 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7465 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7466 (defvar org-goto-local-auto-isearch-map) ; defined below
7468 (defun org-get-location (_buf help)
7469 "Let the user select a location in current buffer.
7470 This function uses a recursive edit. It returns the selected position
7471 or nil."
7472 (org-no-popups
7473 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7474 (isearch-hide-immediately nil)
7475 (isearch-search-fun-function
7476 (lambda () 'org-goto-local-search-headings))
7477 (org-goto-selected-point org-goto-exit-command))
7478 (save-excursion
7479 (save-window-excursion
7480 (delete-other-windows)
7481 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7482 (pop-to-buffer-same-window
7483 (condition-case nil
7484 (make-indirect-buffer (current-buffer) "*org-goto*")
7485 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7486 (with-output-to-temp-buffer "*Org Help*"
7487 (princ (format help (if org-goto-auto-isearch
7488 " Just type for auto-isearch."
7489 " n/p/f/b/u to navigate, q to quit."))))
7490 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7491 (setq buffer-read-only nil)
7492 (let ((org-startup-truncated t)
7493 (org-startup-folded nil)
7494 (org-startup-align-all-tables nil))
7495 (org-mode)
7496 (org-overview))
7497 (setq buffer-read-only t)
7498 (if (and (boundp 'org-goto-start-pos)
7499 (integer-or-marker-p org-goto-start-pos))
7500 (progn (goto-char org-goto-start-pos)
7501 (when (org-invisible-p)
7502 (org-show-set-visibility 'lineage)))
7503 (goto-char (point-min)))
7504 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7505 (message "Select location and press RET")
7506 (use-local-map org-goto-map)
7507 (recursive-edit)))
7508 (kill-buffer "*org-goto*")
7509 (cons org-goto-selected-point org-goto-exit-command))))
7511 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7512 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7513 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7514 (if (fboundp 'isearch-other-control-char)
7515 (progn
7516 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7517 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7518 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7519 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7520 (define-key org-goto-local-auto-isearch-map [return] nil))
7522 (defun org-goto-local-search-headings (string bound noerror)
7523 "Search and make sure that any matches are in headlines."
7524 (catch 'return
7525 (while (if isearch-forward
7526 (search-forward string bound noerror)
7527 (search-backward string bound noerror))
7528 (when (save-match-data
7529 (and (save-excursion
7530 (beginning-of-line)
7531 (looking-at org-complex-heading-regexp))
7532 (or (not (match-beginning 5))
7533 (< (point) (match-beginning 5)))))
7534 (throw 'return (point))))))
7536 (defun org-goto-local-auto-isearch ()
7537 "Start isearch."
7538 (interactive)
7539 (goto-char (point-min))
7540 (let ((keys (this-command-keys)))
7541 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7542 (isearch-mode t)
7543 (isearch-process-search-char (string-to-char keys)))))
7545 (defun org-goto-ret (&optional _arg)
7546 "Finish `org-goto' by going to the new location."
7547 (interactive "P")
7548 (setq org-goto-selected-point (point))
7549 (setq org-goto-exit-command 'return)
7550 (throw 'exit nil))
7552 (defun org-goto-left ()
7553 "Finish `org-goto' by going to the new location."
7554 (interactive)
7555 (if (org-at-heading-p)
7556 (progn
7557 (beginning-of-line 1)
7558 (setq org-goto-selected-point (point)
7559 org-goto-exit-command 'left)
7560 (throw 'exit nil))
7561 (user-error "Not on a heading")))
7563 (defun org-goto-right ()
7564 "Finish `org-goto' by going to the new location."
7565 (interactive)
7566 (if (org-at-heading-p)
7567 (progn
7568 (setq org-goto-selected-point (point)
7569 org-goto-exit-command 'right)
7570 (throw 'exit nil))
7571 (user-error "Not on a heading")))
7573 (defun org-goto-quit ()
7574 "Finish `org-goto' without cursor motion."
7575 (interactive)
7576 (setq org-goto-selected-point nil)
7577 (setq org-goto-exit-command 'quit)
7578 (throw 'exit nil))
7580 ;;; Indirect buffer display of subtrees
7582 (defvar org-indirect-dedicated-frame nil
7583 "This is the frame being used for indirect tree display.")
7584 (defvar org-last-indirect-buffer nil)
7586 (defun org-tree-to-indirect-buffer (&optional arg)
7587 "Create indirect buffer and narrow it to current subtree.
7589 With a numerical prefix ARG, go up to this level and then take that tree.
7590 If ARG is negative, go up that many levels.
7592 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7593 indirect buffer previously made with this command, to avoid proliferation of
7594 indirect buffers. However, when you call the command with a \
7595 `\\[universal-argument]' prefix, or
7596 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7597 so that you can work with several indirect buffers at the same time. If
7598 `org-indirect-buffer-display' is `dedicated-frame', the \
7599 `\\[universal-argument]' prefix also
7600 requests that a new frame be made for the new buffer, so that the dedicated
7601 frame is not changed."
7602 (interactive "P")
7603 (let ((cbuf (current-buffer))
7604 (cwin (selected-window))
7605 (pos (point))
7606 beg end level heading ibuf)
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (when (numberp arg)
7610 (setq level (org-outline-level))
7611 (when (< arg 0) (setq arg (+ level arg)))
7612 (while (> (setq level (org-outline-level)) arg)
7613 (org-up-heading-safe)))
7614 (setq beg (point)
7615 heading (org-get-heading 'no-tags))
7616 (org-end-of-subtree t t)
7617 (when (org-at-heading-p) (backward-char 1))
7618 (setq end (point)))
7619 (when (and (buffer-live-p org-last-indirect-buffer)
7620 (not (eq org-indirect-buffer-display 'new-frame))
7621 (not arg))
7622 (kill-buffer org-last-indirect-buffer))
7623 (setq ibuf (org-get-indirect-buffer cbuf heading)
7624 org-last-indirect-buffer ibuf)
7625 (cond
7626 ((or (eq org-indirect-buffer-display 'new-frame)
7627 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7628 (select-frame (make-frame))
7629 (delete-other-windows)
7630 (pop-to-buffer-same-window ibuf)
7631 (org-set-frame-title heading))
7632 ((eq org-indirect-buffer-display 'dedicated-frame)
7633 (raise-frame
7634 (select-frame (or (and org-indirect-dedicated-frame
7635 (frame-live-p org-indirect-dedicated-frame)
7636 org-indirect-dedicated-frame)
7637 (setq org-indirect-dedicated-frame (make-frame)))))
7638 (delete-other-windows)
7639 (pop-to-buffer-same-window ibuf)
7640 (org-set-frame-title (concat "Indirect: " heading)))
7641 ((eq org-indirect-buffer-display 'current-window)
7642 (pop-to-buffer-same-window ibuf))
7643 ((eq org-indirect-buffer-display 'other-window)
7644 (pop-to-buffer ibuf))
7645 (t (error "Invalid value")))
7646 (narrow-to-region beg end)
7647 (outline-show-all)
7648 (goto-char pos)
7649 (run-hook-with-args 'org-cycle-hook 'all)
7650 (and (window-live-p cwin) (select-window cwin))))
7652 (defun org-get-indirect-buffer (&optional buffer heading)
7653 (setq buffer (or buffer (current-buffer)))
7654 (let ((n 1) (base (buffer-name buffer)) bname)
7655 (while (buffer-live-p
7656 (get-buffer
7657 (setq bname
7658 (concat base "-"
7659 (if heading (concat heading "-" (number-to-string n))
7660 (number-to-string n))))))
7661 (setq n (1+ n)))
7662 (condition-case nil
7663 (make-indirect-buffer buffer bname 'clone)
7664 (error (make-indirect-buffer buffer bname)))))
7666 (defun org-set-frame-title (title)
7667 "Set the title of the current frame to the string TITLE."
7668 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7670 ;;;; Structure editing
7672 ;;; Inserting headlines
7674 (defun org--line-empty-p (n)
7675 "Is the Nth next line empty?
7677 Counts the current line as N = 1 and the previous line as N = 0;
7678 see `beginning-of-line'."
7679 (save-excursion
7680 (and (not (bobp))
7681 (or (beginning-of-line n) t)
7682 (save-match-data
7683 (looking-at "[ \t]*$")))))
7685 (defun org-previous-line-empty-p ()
7686 "Is the previous line a blank line?
7687 When NEXT is non-nil, check the next line instead."
7688 (org--line-empty-p 0))
7690 (defun org-next-line-empty-p ()
7691 "Is the previous line a blank line?
7692 When NEXT is non-nil, check the next line instead."
7693 (org--line-empty-p 2))
7695 (defun org--blank-before-heading-p (&optional parent)
7696 "Non-nil when an empty line should precede a new heading here.
7697 When optional argument PARENT is non-nil, consider parent
7698 headline instead of current one."
7699 (pcase (assq 'heading org-blank-before-new-entry)
7700 (`(heading . auto)
7701 (save-excursion
7702 (org-with-limited-levels
7703 (unless (and (org-before-first-heading-p)
7704 (not (outline-next-heading)))
7705 (org-back-to-heading t)
7706 (when parent (org-up-heading-safe))
7707 (cond ((not (bobp))
7708 (org-previous-line-empty-p))
7709 ((outline-next-heading)
7710 (org-previous-line-empty-p))
7711 ;; Ignore trailing spaces on last buffer line.
7712 ((progn (skip-chars-backward " \t") (bolp))
7713 (org-previous-line-empty-p))
7714 (t nil))))))
7715 (`(heading . ,value) value)
7716 (_ nil)))
7718 (defun org-insert-heading (&optional arg invisible-ok top)
7719 "Insert a new heading or an item with the same depth at point.
7721 If point is at the beginning of a heading, insert a new heading
7722 or a new headline above the current one. When at the beginning
7723 of a regular line of text, turn it into a heading.
7725 If point is in the middle of a line, split it and create a new
7726 headline with the text in the current line after point (see
7727 `org-M-RET-may-split-line' on how to modify this behavior). As
7728 a special case, on a headline, splitting can only happen on the
7729 title itself. E.g., this excludes breaking stars or tags.
7731 With a `\\[universal-argument]' prefix, set \
7732 `org-insert-heading-respect-content' to
7733 a non-nil value for the duration of the command. This forces the
7734 insertion of a heading after the current subtree, independently
7735 on the location of point.
7737 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7738 insert the heading at the end of the tree
7739 above the current heading. For example, if point is within a
7740 2nd-level heading, then it will insert a 2nd-level heading at
7741 the end of the 1st-level parent subtree.
7743 When INVISIBLE-OK is set, stop at invisible headlines when going
7744 back. This is important for non-interactive uses of the
7745 command.
7747 When optional argument TOP is non-nil, insert a level 1 heading,
7748 unconditionally."
7749 (interactive "P")
7750 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7751 (level (org-current-level))
7752 (stars (make-string (if (and level (not top)) level 1) ?*)))
7753 (cond
7754 ((or org-insert-heading-respect-content
7755 (member arg '((4) (16)))
7756 (and (not invisible-ok)
7757 (invisible-p (max (1- (point)) (point-min)))))
7758 ;; Position point at the location of insertion.
7759 (if (not level) ;before first headline
7760 (org-with-limited-levels (outline-next-heading))
7761 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7762 ;; is nil.
7763 (org-with-limited-levels (org-back-to-heading invisible-ok))
7764 (cond ((equal arg '(16))
7765 (org-up-heading-safe)
7766 (org-end-of-subtree t t))
7768 (org-end-of-subtree t t))))
7769 (unless (bolp) (insert "\n")) ;ensure final newline
7770 (unless (and blank? (org-previous-line-empty-p))
7771 (org-N-empty-lines-before-current (if blank? 1 0)))
7772 (insert stars " \n")
7773 (forward-char -1))
7774 ;; At a headline...
7775 ((org-at-heading-p)
7776 (cond ((bolp)
7777 (when blank? (save-excursion (insert "\n")))
7778 (save-excursion (insert stars " \n"))
7779 (unless (and blank? (org-previous-line-empty-p))
7780 (org-N-empty-lines-before-current (if blank? 1 0)))
7781 (end-of-line))
7782 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7783 (org-match-line org-complex-heading-regexp)
7784 (org-pos-in-match-range (point) 4))
7785 ;; Grab the text that should moved to the new headline.
7786 ;; Preserve tags.
7787 (let ((split (delete-and-extract-region (point) (match-end 4))))
7788 (if (looking-at "[ \t]*$") (replace-match "")
7789 (org-set-tags nil t))
7790 (end-of-line)
7791 (when blank? (insert "\n"))
7792 (insert "\n" stars " ")
7793 (when (org-string-nw-p split) (insert split))
7794 (when (eobp) (save-excursion (insert "\n")))))
7796 (end-of-line)
7797 (when blank? (insert "\n"))
7798 (insert "\n" stars " ")
7799 (when (eobp) (save-excursion (insert "\n"))))))
7800 ;; On regular text, turn line into a headline or split, if
7801 ;; appropriate.
7802 ((bolp)
7803 (insert stars " ")
7804 (unless (and blank? (org-previous-line-empty-p))
7805 (org-N-empty-lines-before-current (if blank? 1 0))))
7807 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7808 (end-of-line))
7809 (insert "\n" stars " ")
7810 (unless (and blank? (org-previous-line-empty-p))
7811 (org-N-empty-lines-before-current (if blank? 1 0))))))
7812 (run-hooks 'org-insert-heading-hook))
7814 (defun org-N-empty-lines-before-current (n)
7815 "Make the number of empty lines before current exactly N.
7816 So this will delete or add empty lines."
7817 (let ((column (current-column)))
7818 (beginning-of-line)
7819 (unless (bobp)
7820 (let ((start (save-excursion
7821 (skip-chars-backward " \r\t\n")
7822 (line-end-position))))
7823 (delete-region start (line-end-position 0))))
7824 (insert (make-string n ?\n))
7825 (move-to-column column)))
7827 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7828 "Return the heading of the current entry, without the stars.
7829 When NO-TAGS is non-nil, don't include tags.
7830 When NO-TODO is non-nil, don't include TODO keywords.
7831 When NO-PRIORITY is non-nil, don't include priority cookie.
7832 When NO-COMMENT is non-nil, don't include COMMENT string."
7833 (save-excursion
7834 (org-back-to-heading t)
7835 (let ((case-fold-search nil))
7836 (looking-at org-complex-heading-regexp)
7837 (let ((todo (and (not no-todo) (match-string 2)))
7838 (priority (and (not no-priority) (match-string 3)))
7839 (headline (pcase (match-string 4)
7840 (`nil "")
7841 ((and (guard no-comment) h)
7842 (replace-regexp-in-string
7843 (eval-when-compile
7844 (format "\\`%s[ \t]+" org-comment-string))
7845 "" h))
7846 (h h)))
7847 (tags (and (not no-tags) (match-string 5))))
7848 (mapconcat #'identity
7849 (delq nil (list todo priority headline tags))
7850 " ")))))
7852 (defvar orgstruct-mode) ; defined below
7854 (defun org-heading-components ()
7855 "Return the components of the current heading.
7856 This is a list with the following elements:
7857 - the level as an integer
7858 - the reduced level, different if `org-odd-levels-only' is set.
7859 - the TODO keyword, or nil
7860 - the priority character, like ?A, or nil if no priority is given
7861 - the headline text itself, or the tags string if no headline text
7862 - the tags string, or nil."
7863 (save-excursion
7864 (org-back-to-heading t)
7865 (when (let (case-fold-search)
7866 (looking-at
7867 (if orgstruct-mode
7868 org-heading-regexp
7869 org-complex-heading-regexp)))
7870 (if orgstruct-mode
7871 (list (length (match-string 1))
7872 (org-reduced-level (length (match-string 1)))
7875 (match-string 2)
7876 nil)
7877 (list (length (match-string 1))
7878 (org-reduced-level (length (match-string 1)))
7879 (match-string-no-properties 2)
7880 (and (match-end 3) (aref (match-string 3) 2))
7881 (match-string-no-properties 4)
7882 (match-string-no-properties 5))))))
7884 (defun org-get-entry ()
7885 "Get the entry text, after heading, entire subtree."
7886 (save-excursion
7887 (org-back-to-heading t)
7888 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7890 (defun org-edit-headline (&optional heading)
7891 "Edit the current headline.
7892 Set it to HEADING when provided."
7893 (interactive)
7894 (org-with-wide-buffer
7895 (org-back-to-heading t)
7896 (let ((case-fold-search nil))
7897 (when (looking-at org-complex-heading-regexp)
7898 (let* ((old (match-string-no-properties 4))
7899 (new (save-match-data
7900 (org-trim (or heading (read-string "Edit: " old))))))
7901 (unless (equal old new)
7902 (if old (replace-match new t t nil 4)
7903 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7904 (insert " " new))
7905 (org-set-tags nil t)
7906 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7908 (defun org-insert-heading-after-current ()
7909 "Insert a new heading with same level as current, after current subtree."
7910 (interactive)
7911 (org-back-to-heading)
7912 (org-insert-heading)
7913 (org-move-subtree-down)
7914 (end-of-line 1))
7916 (defun org-insert-heading-respect-content (&optional invisible-ok)
7917 "Insert heading with `org-insert-heading-respect-content' set to t."
7918 (interactive)
7919 (org-insert-heading '(4) invisible-ok))
7921 (defun org-insert-todo-heading-respect-content (&optional force-state)
7922 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7923 (interactive)
7924 (org-insert-todo-heading force-state '(4)))
7926 (defun org-insert-todo-heading (arg &optional force-heading)
7927 "Insert a new heading with the same level and TODO state as current heading.
7929 If the heading has no TODO state, or if the state is DONE, use
7930 the first state (TODO by default). Also with one prefix arg,
7931 force first state. With two prefix args, force inserting at the
7932 end of the parent subtree.
7934 When called at a plain list item, insert a new item with an
7935 unchecked check box."
7936 (interactive "P")
7937 (when (or force-heading (not (org-insert-item 'checkbox)))
7938 (org-insert-heading (or (and (equal arg '(16)) '(16))
7939 force-heading))
7940 (save-excursion
7941 (org-back-to-heading)
7942 (outline-previous-heading)
7943 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7944 (let* ((new-mark-x
7945 (if (or (equal arg '(4))
7946 (not (match-beginning 2))
7947 (member (match-string 2) org-done-keywords))
7948 (car org-todo-keywords-1)
7949 (match-string 2)))
7950 (new-mark
7952 (run-hook-with-args-until-success
7953 'org-todo-get-default-hook new-mark-x nil)
7954 new-mark-x)))
7955 (beginning-of-line 1)
7956 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7957 (if org-treat-insert-todo-heading-as-state-change
7958 (org-todo new-mark)
7959 (insert new-mark " "))))
7960 (when org-provide-todo-statistics
7961 (org-update-parent-todo-statistics))))
7963 (defun org-insert-subheading (arg)
7964 "Insert a new subheading and demote it.
7965 Works for outline headings and for plain lists alike."
7966 (interactive "P")
7967 (org-insert-heading arg)
7968 (cond
7969 ((org-at-heading-p) (org-do-demote))
7970 ((org-at-item-p) (org-indent-item))))
7972 (defun org-insert-todo-subheading (arg)
7973 "Insert a new subheading with TODO keyword or checkbox and demote it.
7974 Works for outline headings and for plain lists alike."
7975 (interactive "P")
7976 (org-insert-todo-heading arg)
7977 (cond
7978 ((org-at-heading-p) (org-do-demote))
7979 ((org-at-item-p) (org-indent-item))))
7981 ;;; Promotion and Demotion
7983 (defvar org-after-demote-entry-hook nil
7984 "Hook run after an entry has been demoted.
7985 The cursor will be at the beginning of the entry.
7986 When a subtree is being demoted, the hook will be called for each node.")
7988 (defvar org-after-promote-entry-hook nil
7989 "Hook run after an entry has been promoted.
7990 The cursor will be at the beginning of the entry.
7991 When a subtree is being promoted, the hook will be called for each node.")
7993 (defun org-promote-subtree ()
7994 "Promote the entire subtree.
7995 See also `org-promote'."
7996 (interactive)
7997 (save-excursion
7998 (org-with-limited-levels (org-map-tree 'org-promote)))
7999 (org-fix-position-after-promote))
8001 (defun org-demote-subtree ()
8002 "Demote the entire subtree.
8003 See `org-demote' and `org-promote'."
8004 (interactive)
8005 (save-excursion
8006 (org-with-limited-levels (org-map-tree 'org-demote)))
8007 (org-fix-position-after-promote))
8009 (defun org-do-promote ()
8010 "Promote the current heading higher up the tree.
8011 If the region is active in `transient-mark-mode', promote all
8012 headings in the region."
8013 (interactive)
8014 (save-excursion
8015 (if (org-region-active-p)
8016 (org-map-region 'org-promote (region-beginning) (region-end))
8017 (org-promote)))
8018 (org-fix-position-after-promote))
8020 (defun org-do-demote ()
8021 "Demote the current heading lower down the tree.
8022 If the region is active in `transient-mark-mode', demote all
8023 headings in the region."
8024 (interactive)
8025 (save-excursion
8026 (if (org-region-active-p)
8027 (org-map-region 'org-demote (region-beginning) (region-end))
8028 (org-demote)))
8029 (org-fix-position-after-promote))
8031 (defun org-fix-position-after-promote ()
8032 "Fix cursor position and indentation after demoting/promoting."
8033 (let ((pos (point)))
8034 (when (save-excursion
8035 (beginning-of-line)
8036 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8037 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8038 (cond ((eobp) (insert " "))
8039 ((eolp) (insert " "))
8040 ((equal (char-after) ?\s) (forward-char 1))))))
8042 (defun org-current-level ()
8043 "Return the level of the current entry, or nil if before the first headline.
8044 The level is the number of stars at the beginning of the
8045 headline. Use `org-reduced-level' to remove the effect of
8046 `org-odd-levels'. Unlike to `org-outline-level', this function
8047 ignores inlinetasks."
8048 (let ((level (org-with-limited-levels (org-outline-level))))
8049 (and (> level 0) level)))
8051 (defun org-get-previous-line-level ()
8052 "Return the outline depth of the last headline before the current line.
8053 Returns 0 for the first headline in the buffer, and nil if before the
8054 first headline."
8055 (and (org-current-level)
8056 (or (and (/= (line-beginning-position) (point-min))
8057 (save-excursion (beginning-of-line 0) (org-current-level)))
8058 0)))
8060 (defun org-reduced-level (l)
8061 "Compute the effective level of a heading.
8062 This takes into account the setting of `org-odd-levels-only'."
8063 (cond
8064 ((zerop l) 0)
8065 (org-odd-levels-only (1+ (floor (/ l 2))))
8066 (t l)))
8068 (defun org-level-increment ()
8069 "Return the number of stars that will be added or removed at a
8070 time to headlines when structure editing, based on the value of
8071 `org-odd-levels-only'."
8072 (if org-odd-levels-only 2 1))
8074 (defun org-get-valid-level (level &optional change)
8075 "Rectify a level change under the influence of `org-odd-levels-only'.
8076 LEVEL is a current level, CHANGE is by how much the level should
8077 be modified. Even if CHANGE is nil, LEVEL may be returned
8078 modified because even level numbers will become the next higher
8079 odd number. Returns values greater than 0."
8080 (if org-odd-levels-only
8081 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8082 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8083 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8084 (max 1 (+ level (or change 0)))))
8086 (defun org-promote ()
8087 "Promote the current heading higher up the tree."
8088 (org-with-wide-buffer
8089 (org-back-to-heading t)
8090 (let* ((after-change-functions (remq 'flyspell-after-change-function
8091 after-change-functions))
8092 (level (save-match-data (funcall outline-level)))
8093 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8094 (diff (abs (- level (length up-head) -1))))
8095 (cond
8096 ((and (= level 1) org-allow-promoting-top-level-subtree)
8097 (replace-match "# " nil t))
8098 ((= level 1)
8099 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8100 (t (replace-match up-head nil t)))
8101 (unless (= level 1)
8102 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8103 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8104 (run-hooks 'org-after-promote-entry-hook))))
8106 (defun org-demote ()
8107 "Demote the current heading lower down the tree."
8108 (org-with-wide-buffer
8109 (org-back-to-heading t)
8110 (let* ((after-change-functions (remq 'flyspell-after-change-function
8111 after-change-functions))
8112 (level (save-match-data (funcall outline-level)))
8113 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8114 (diff (abs (- level (length down-head) -1))))
8115 (replace-match down-head nil t)
8116 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8117 (when org-adapt-indentation (org-fixup-indentation diff))
8118 (run-hooks 'org-after-demote-entry-hook))))
8120 (defun org-cycle-level ()
8121 "Cycle the level of an empty headline through possible states.
8122 This goes first to child, then to parent, level, then up the hierarchy.
8123 After top level, it switches back to sibling level."
8124 (interactive)
8125 (let ((org-adapt-indentation nil))
8126 (when (org-point-at-end-of-empty-headline)
8127 (setq this-command 'org-cycle-level) ; Only needed for caching
8128 (let ((cur-level (org-current-level))
8129 (prev-level (org-get-previous-line-level)))
8130 (cond
8131 ;; If first headline in file, promote to top-level.
8132 ((= prev-level 0)
8133 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8134 do (org-do-promote)))
8135 ;; If same level as prev, demote one.
8136 ((= prev-level cur-level)
8137 (org-do-demote))
8138 ;; If parent is top-level, promote to top level if not already.
8139 ((= prev-level 1)
8140 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8141 do (org-do-promote)))
8142 ;; If top-level, return to prev-level.
8143 ((= cur-level 1)
8144 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8145 do (org-do-demote)))
8146 ;; If less than prev-level, promote one.
8147 ((< cur-level prev-level)
8148 (org-do-promote))
8149 ;; If deeper than prev-level, promote until higher than
8150 ;; prev-level.
8151 ((> cur-level prev-level)
8152 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8153 do (org-do-promote))))
8154 t))))
8156 (defun org-map-tree (fun)
8157 "Call FUN for every heading underneath the current one."
8158 (org-back-to-heading t)
8159 (let ((level (funcall outline-level)))
8160 (save-excursion
8161 (funcall fun)
8162 (while (and (progn
8163 (outline-next-heading)
8164 (> (funcall outline-level) level))
8165 (not (eobp)))
8166 (funcall fun)))))
8168 (defun org-map-region (fun beg end)
8169 "Call FUN for every heading between BEG and END."
8170 (let ((org-ignore-region t))
8171 (save-excursion
8172 (setq end (copy-marker end))
8173 (goto-char beg)
8174 (when (and (re-search-forward org-outline-regexp-bol nil t)
8175 (< (point) end))
8176 (funcall fun))
8177 (while (and (progn
8178 (outline-next-heading)
8179 (< (point) end))
8180 (not (eobp)))
8181 (funcall fun)))))
8183 (defun org-fixup-indentation (diff)
8184 "Change the indentation in the current entry by DIFF.
8186 DIFF is an integer. Indentation is done according to the
8187 following rules:
8189 - Planning information and property drawers are always indented
8190 according to the new level of the headline;
8192 - Footnote definitions and their contents are ignored;
8194 - Inlinetasks' boundaries are not shifted;
8196 - Empty lines are ignored;
8198 - Other lines' indentation are shifted by DIFF columns, unless
8199 it would introduce a structural change in the document, in
8200 which case no shifting is done at all.
8202 Assume point is at a heading or an inlinetask beginning."
8203 (org-with-wide-buffer
8204 (narrow-to-region (line-beginning-position)
8205 (save-excursion
8206 (if (org-with-limited-levels (org-at-heading-p))
8207 (org-with-limited-levels (outline-next-heading))
8208 (org-inlinetask-goto-end))
8209 (point)))
8210 (forward-line)
8211 ;; Indent properly planning info and property drawer.
8212 (when (looking-at-p org-planning-line-re)
8213 (org-indent-line)
8214 (forward-line))
8215 (when (looking-at org-property-drawer-re)
8216 (goto-char (match-end 0))
8217 (forward-line)
8218 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8219 (catch 'no-shift
8220 (when (zerop diff) (throw 'no-shift nil))
8221 ;; If DIFF is negative, first check if a shift is possible at all
8222 ;; (e.g., it doesn't break structure). This can only happen if
8223 ;; some contents are not properly indented.
8224 (let ((case-fold-search t))
8225 (when (< diff 0)
8226 (let ((diff (- diff))
8227 (forbidden-re (concat org-outline-regexp
8228 "\\|"
8229 (substring org-footnote-definition-re 1))))
8230 (save-excursion
8231 (while (not (eobp))
8232 (cond
8233 ((looking-at-p "[ \t]*$") (forward-line))
8234 ((and (looking-at-p org-footnote-definition-re)
8235 (let ((e (org-element-at-point)))
8236 (and (eq (org-element-type e) 'footnote-definition)
8237 (goto-char (org-element-property :end e))))))
8238 ((looking-at-p org-outline-regexp) (forward-line))
8239 ;; Give up if shifting would move before column 0 or
8240 ;; if it would introduce a headline or a footnote
8241 ;; definition.
8243 (skip-chars-forward " \t")
8244 (let ((ind (current-column)))
8245 (when (or (< ind diff)
8246 (and (= ind diff) (looking-at-p forbidden-re)))
8247 (throw 'no-shift nil)))
8248 ;; Ignore contents of example blocks and source
8249 ;; blocks if their indentation is meant to be
8250 ;; preserved. Jump to block's closing line.
8251 (beginning-of-line)
8252 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8253 (let ((e (org-element-at-point)))
8254 (and (memq (org-element-type e)
8255 '(example-block src-block))
8256 (or org-src-preserve-indentation
8257 (org-element-property :preserve-indent e))
8258 (goto-char (org-element-property :end e))
8259 (progn (skip-chars-backward " \r\t\n")
8260 (beginning-of-line)
8261 t))))
8262 (forward-line))))))))
8263 ;; Shift lines but footnote definitions, inlinetasks boundaries
8264 ;; by DIFF. Also skip contents of source or example blocks
8265 ;; when indentation is meant to be preserved.
8266 (while (not (eobp))
8267 (cond
8268 ((and (looking-at-p org-footnote-definition-re)
8269 (let ((e (org-element-at-point)))
8270 (and (eq (org-element-type e) 'footnote-definition)
8271 (goto-char (org-element-property :end e))))))
8272 ((looking-at-p org-outline-regexp) (forward-line))
8273 ((looking-at-p "[ \t]*$") (forward-line))
8275 (indent-line-to (+ (org-get-indentation) diff))
8276 (beginning-of-line)
8277 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8278 (let ((e (org-element-at-point)))
8279 (and (memq (org-element-type e)
8280 '(example-block src-block))
8281 (or org-src-preserve-indentation
8282 (org-element-property :preserve-indent e))
8283 (goto-char (org-element-property :end e))
8284 (progn (skip-chars-backward " \r\t\n")
8285 (beginning-of-line)
8286 t))))
8287 (forward-line)))))))))
8289 (defun org-convert-to-odd-levels ()
8290 "Convert an Org file with all levels allowed to one with odd levels.
8291 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8292 level 5 etc."
8293 (interactive)
8294 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8295 (let ((outline-level 'org-outline-level)
8296 (org-odd-levels-only nil) n)
8297 (save-excursion
8298 (goto-char (point-min))
8299 (while (re-search-forward "^\\*\\*+ " nil t)
8300 (setq n (- (length (match-string 0)) 2))
8301 (while (>= (setq n (1- n)) 0)
8302 (org-demote))
8303 (end-of-line 1))))))
8305 (defun org-convert-to-oddeven-levels ()
8306 "Convert an Org file with only odd levels to one with odd/even levels.
8307 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8308 file contains a section with an even level, conversion would
8309 destroy the structure of the file. An error is signaled in this
8310 case."
8311 (interactive)
8312 (goto-char (point-min))
8313 ;; First check if there are no even levels
8314 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8315 (org-show-set-visibility 'canonical)
8316 (error "Not all levels are odd in this file. Conversion not possible"))
8317 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8318 (let ((outline-regexp org-outline-regexp)
8319 (outline-level 'org-outline-level)
8320 (org-odd-levels-only nil) n)
8321 (save-excursion
8322 (goto-char (point-min))
8323 (while (re-search-forward "^\\*\\*+ " nil t)
8324 (setq n (/ (1- (length (match-string 0))) 2))
8325 (while (>= (setq n (1- n)) 0)
8326 (org-promote))
8327 (end-of-line 1))))))
8329 (defun org-tr-level (n)
8330 "Make N odd if required."
8331 (if org-odd-levels-only (1+ (/ n 2)) n))
8333 ;;; Vertical tree motion, cutting and pasting of subtrees
8335 (defun org-move-subtree-up (&optional arg)
8336 "Move the current subtree up past ARG headlines of the same level."
8337 (interactive "p")
8338 (org-move-subtree-down (- (prefix-numeric-value arg))))
8340 (defun org-move-subtree-down (&optional arg)
8341 "Move the current subtree down past ARG headlines of the same level."
8342 (interactive "p")
8343 (setq arg (prefix-numeric-value arg))
8344 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8345 'org-get-last-sibling))
8346 (ins-point (make-marker))
8347 (cnt (abs arg))
8348 (col (current-column))
8349 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8350 ;; Select the tree
8351 (org-back-to-heading)
8352 (setq beg0 (point))
8353 (save-excursion
8354 (setq ne-beg (org-back-over-empty-lines))
8355 (setq beg (point)))
8356 (save-match-data
8357 (save-excursion (outline-end-of-heading)
8358 (setq folded (org-invisible-p)))
8359 (progn (org-end-of-subtree nil t)
8360 (unless (eobp) (backward-char))))
8361 (outline-next-heading)
8362 (setq ne-end (org-back-over-empty-lines))
8363 (setq end (point))
8364 (goto-char beg0)
8365 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8366 ;; include less whitespace
8367 (save-excursion
8368 (goto-char beg)
8369 (forward-line (- ne-beg ne-end))
8370 (setq beg (point))))
8371 ;; Find insertion point, with error handling
8372 (while (> cnt 0)
8373 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8374 (progn (goto-char beg0)
8375 (user-error "Cannot move past superior level or buffer limit")))
8376 (setq cnt (1- cnt)))
8377 (when (> arg 0)
8378 ;; Moving forward - still need to move over subtree
8379 (org-end-of-subtree t t)
8380 (save-excursion
8381 (org-back-over-empty-lines)
8382 (or (bolp) (newline))))
8383 (setq ne-ins (org-back-over-empty-lines))
8384 (move-marker ins-point (point))
8385 (setq txt (buffer-substring beg end))
8386 (org-save-markers-in-region beg end)
8387 (delete-region beg end)
8388 (org-remove-empty-overlays-at beg)
8389 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8390 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8391 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8392 (let ((bbb (point)))
8393 (insert-before-markers txt)
8394 (org-reinstall-markers-in-region bbb)
8395 (move-marker ins-point bbb))
8396 (or (bolp) (insert "\n"))
8397 (setq ins-end (point))
8398 (goto-char ins-point)
8399 (org-skip-whitespace)
8400 (when (and (< arg 0)
8401 (org-first-sibling-p)
8402 (> ne-ins ne-beg))
8403 ;; Move whitespace back to beginning
8404 (save-excursion
8405 (goto-char ins-end)
8406 (let ((kill-whole-line t))
8407 (kill-line (- ne-ins ne-beg)) (point)))
8408 (insert (make-string (- ne-ins ne-beg) ?\n)))
8409 (move-marker ins-point nil)
8410 (if folded
8411 (outline-hide-subtree)
8412 (org-show-entry)
8413 (org-show-children)
8414 (org-cycle-hide-drawers 'children))
8415 (org-clean-visibility-after-subtree-move)
8416 ;; move back to the initial column we were at
8417 (move-to-column col)))
8419 (defvar org-subtree-clip ""
8420 "Clipboard for cut and paste of subtrees.
8421 This is actually only a copy of the kill, because we use the normal kill
8422 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8424 (defvar org-subtree-clip-folded nil
8425 "Was the last copied subtree folded?
8426 This is used to fold the tree back after pasting.")
8428 (defun org-cut-subtree (&optional n)
8429 "Cut the current subtree into the clipboard.
8430 With prefix arg N, cut this many sequential subtrees.
8431 This is a short-hand for marking the subtree and then cutting it."
8432 (interactive "p")
8433 (org-copy-subtree n 'cut))
8435 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8436 "Copy the current subtree it in the clipboard.
8437 With prefix arg N, copy this many sequential subtrees.
8438 This is a short-hand for marking the subtree and then copying it.
8439 If CUT is non-nil, actually cut the subtree.
8440 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8441 of some markers in the region, even if CUT is non-nil. This is
8442 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8443 (interactive "p")
8444 (let (beg end folded (beg0 (point)))
8445 (if (called-interactively-p 'any)
8446 (org-back-to-heading nil) ; take what looks like a subtree
8447 (org-back-to-heading t)) ; take what is really there
8448 (setq beg (point))
8449 (skip-chars-forward " \t\r\n")
8450 (save-match-data
8451 (if nosubtrees
8452 (outline-next-heading)
8453 (save-excursion (outline-end-of-heading)
8454 (setq folded (org-invisible-p)))
8455 (ignore-errors (org-forward-heading-same-level (1- n) t))
8456 (org-end-of-subtree t t)))
8457 ;; Include the end of an inlinetask
8458 (when (and (featurep 'org-inlinetask)
8459 (looking-at-p (concat (org-inlinetask-outline-regexp)
8460 "END[ \t]*$")))
8461 (end-of-line))
8462 (setq end (point))
8463 (goto-char beg0)
8464 (when (> end beg)
8465 (setq org-subtree-clip-folded folded)
8466 (when (or cut force-store-markers)
8467 (org-save-markers-in-region beg end))
8468 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8469 (setq org-subtree-clip (current-kill 0))
8470 (message "%s: Subtree(s) with %d characters"
8471 (if cut "Cut" "Copied")
8472 (length org-subtree-clip)))))
8474 (defun org-paste-subtree (&optional level tree for-yank remove)
8475 "Paste the clipboard as a subtree, with modification of headline level.
8476 The entire subtree is promoted or demoted in order to match a new headline
8477 level.
8479 If the cursor is at the beginning of a headline, the same level as
8480 that headline is used to paste the tree.
8482 If not, the new level is derived from the *visible* headings
8483 before and after the insertion point, and taken to be the inferior headline
8484 level of the two. So if the previous visible heading is level 3 and the
8485 next is level 4 (or vice versa), level 4 will be used for insertion.
8486 This makes sure that the subtree remains an independent subtree and does
8487 not swallow low level entries.
8489 You can also force a different level, either by using a numeric prefix
8490 argument, or by inserting the heading marker by hand. For example, if the
8491 cursor is after \"*****\", then the tree will be shifted to level 5.
8493 If optional TREE is given, use this text instead of the kill ring.
8495 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8496 move back over whitespace before inserting, and move point to the end of
8497 the inserted text when done.
8499 When REMOVE is non-nil, remove the subtree from the clipboard."
8500 (interactive "P")
8501 (setq tree (or tree (and kill-ring (current-kill 0))))
8502 (unless (org-kill-is-subtree-p tree)
8503 (user-error "%s"
8504 (substitute-command-keys
8505 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8506 (org-with-limited-levels
8507 (let* ((visp (not (org-invisible-p)))
8508 (txt tree)
8509 (^re_ "\\(\\*+\\)[ \t]*")
8510 (old-level (if (string-match org-outline-regexp-bol txt)
8511 (- (match-end 0) (match-beginning 0) 1)
8512 -1))
8513 (force-level (cond (level (prefix-numeric-value level))
8514 ((and (looking-at "[ \t]*$")
8515 (string-match
8516 "^\\*+$" (buffer-substring
8517 (point-at-bol) (point))))
8518 (- (match-end 0) (match-beginning 0)))
8519 ((and (bolp)
8520 (looking-at org-outline-regexp))
8521 (- (match-end 0) (point) 1))))
8522 (previous-level (save-excursion
8523 (condition-case nil
8524 (progn
8525 (outline-previous-visible-heading 1)
8526 (if (looking-at ^re_)
8527 (- (match-end 0) (match-beginning 0) 1)
8529 (error 1))))
8530 (next-level (save-excursion
8531 (condition-case nil
8532 (progn
8533 (or (looking-at org-outline-regexp)
8534 (outline-next-visible-heading 1))
8535 (if (looking-at ^re_)
8536 (- (match-end 0) (match-beginning 0) 1)
8538 (error 1))))
8539 (new-level (or force-level (max previous-level next-level)))
8540 (shift (if (or (= old-level -1)
8541 (= new-level -1)
8542 (= old-level new-level))
8544 (- new-level old-level)))
8545 (delta (if (> shift 0) -1 1))
8546 (func (if (> shift 0) 'org-demote 'org-promote))
8547 (org-odd-levels-only nil)
8548 beg end newend)
8549 ;; Remove the forced level indicator
8550 (when force-level
8551 (delete-region (point-at-bol) (point)))
8552 ;; Paste
8553 (beginning-of-line (if (bolp) 1 2))
8554 (setq beg (point))
8555 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8556 (insert-before-markers txt)
8557 (unless (string-suffix-p "\n" txt) (insert "\n"))
8558 (setq newend (point))
8559 (org-reinstall-markers-in-region beg)
8560 (setq end (point))
8561 (goto-char beg)
8562 (skip-chars-forward " \t\n\r")
8563 (setq beg (point))
8564 (when (and (org-invisible-p) visp)
8565 (save-excursion (outline-show-heading)))
8566 ;; Shift if necessary
8567 (unless (= shift 0)
8568 (save-restriction
8569 (narrow-to-region beg end)
8570 (while (not (= shift 0))
8571 (org-map-region func (point-min) (point-max))
8572 (setq shift (+ delta shift)))
8573 (goto-char (point-min))
8574 (setq newend (point-max))))
8575 (when (or (called-interactively-p 'interactive) for-yank)
8576 (message "Clipboard pasted as level %d subtree" new-level))
8577 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8578 kill-ring
8579 (eq org-subtree-clip (current-kill 0))
8580 org-subtree-clip-folded)
8581 ;; The tree was folded before it was killed/copied
8582 (outline-hide-subtree))
8583 (and for-yank (goto-char newend))
8584 (and remove (setq kill-ring (cdr kill-ring))))))
8586 (defun org-kill-is-subtree-p (&optional txt)
8587 "Check if the current kill is an outline subtree, or a set of trees.
8588 Returns nil if kill does not start with a headline, or if the first
8589 headline level is not the largest headline level in the tree.
8590 So this will actually accept several entries of equal levels as well,
8591 which is OK for `org-paste-subtree'.
8592 If optional TXT is given, check this string instead of the current kill."
8593 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8594 (re (org-get-limited-outline-regexp))
8595 (^re (concat "^" re))
8596 (start-level (and kill
8597 (string-match
8598 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8599 kill)
8600 (- (match-end 2) (match-beginning 2) 1)))
8601 (start (1+ (or (match-beginning 2) -1))))
8602 (if (not start-level)
8603 (progn
8604 nil) ;; does not even start with a heading
8605 (catch 'exit
8606 (while (setq start (string-match ^re kill (1+ start)))
8607 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8608 (throw 'exit nil)))
8609 t))))
8611 (defvar org-markers-to-move nil
8612 "Markers that should be moved with a cut-and-paste operation.
8613 Those markers are stored together with their positions relative to
8614 the start of the region.")
8616 (defun org-save-markers-in-region (beg end)
8617 "Check markers in region.
8618 If these markers are between BEG and END, record their position relative
8619 to BEG, so that after moving the block of text, we can put the markers back
8620 into place.
8621 This function gets called just before an entry or tree gets cut from the
8622 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8623 called immediately, to move the markers with the entries."
8624 (setq org-markers-to-move nil)
8625 (when (featurep 'org-clock)
8626 (org-clock-save-markers-for-cut-and-paste beg end))
8627 (when (featurep 'org-agenda)
8628 (org-agenda-save-markers-for-cut-and-paste beg end)))
8630 (defun org-check-and-save-marker (marker beg end)
8631 "Check if MARKER is between BEG and END.
8632 If yes, remember the marker and the distance to BEG."
8633 (when (and (marker-buffer marker)
8634 (equal (marker-buffer marker) (current-buffer))
8635 (>= marker beg) (< marker end))
8636 (push (cons marker (- marker beg)) org-markers-to-move)))
8638 (defun org-reinstall-markers-in-region (beg)
8639 "Move all remembered markers to their position relative to BEG."
8640 (dolist (x org-markers-to-move)
8641 (move-marker (car x) (+ beg (cdr x))))
8642 (setq org-markers-to-move nil))
8644 (defun org-narrow-to-subtree ()
8645 "Narrow buffer to the current subtree."
8646 (interactive)
8647 (save-excursion
8648 (save-match-data
8649 (org-with-limited-levels
8650 (narrow-to-region
8651 (progn (org-back-to-heading t) (point))
8652 (progn (org-end-of-subtree t t)
8653 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8654 (point)))))))
8656 (defun org-narrow-to-block ()
8657 "Narrow buffer to the current block."
8658 (interactive)
8659 (let* ((case-fold-search t)
8660 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8661 "^[ \t]*#\\+end_.*")))
8662 (if blockp
8663 (narrow-to-region (car blockp) (cdr blockp))
8664 (user-error "Not in a block"))))
8666 (defun org-clone-subtree-with-time-shift (n &optional shift)
8667 "Clone the task (subtree) at point N times.
8668 The clones will be inserted as siblings.
8670 In interactive use, the user will be prompted for the number of
8671 clones to be produced. If the entry has a timestamp, the user
8672 will also be prompted for a time shift, which may be a repeater
8673 as used in time stamps, for example `+3d'. To disable this,
8674 you can call the function with a universal prefix argument.
8676 When a valid repeater is given and the entry contains any time
8677 stamps, the clones will become a sequence in time, with time
8678 stamps in the subtree shifted for each clone produced. If SHIFT
8679 is nil or the empty string, time stamps will be left alone. The
8680 ID property of the original subtree is removed.
8682 In each clone, all the CLOCK entries will be removed. This
8683 prevents Org from considering that the clocked times overlap.
8685 If the original subtree did contain time stamps with a repeater,
8686 the following will happen:
8687 - the repeater will be removed in each clone
8688 - an additional clone will be produced, with the current, unshifted
8689 date(s) in the entry.
8690 - the original entry will be placed *after* all the clones, with
8691 repeater intact.
8692 - the start days in the repeater in the original entry will be shifted
8693 to past the last clone.
8694 In this way you can spell out a number of instances of a repeating task,
8695 and still retain the repeater to cover future instances of the task.
8697 As described above, N+1 clones are produced when the original
8698 subtree has a repeater. Setting N to 0, then, can be used to
8699 remove the repeater from a subtree and create a shifted clone
8700 with the original repeater."
8701 (interactive "nNumber of clones to produce: ")
8702 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8703 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8704 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8705 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8706 (shift
8707 (or shift
8708 (if (and (not (equal current-prefix-arg '(4)))
8709 (save-excursion
8710 (goto-char beg)
8711 (re-search-forward org-ts-regexp-both end-of-tree t)))
8712 (read-from-minibuffer
8713 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8714 ""))) ;No time shift
8715 (doshift
8716 (and (org-string-nw-p shift)
8717 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8718 shift)
8719 (user-error "Invalid shift specification %s" shift)))))
8720 (goto-char end-of-tree)
8721 (unless (bolp) (insert "\n"))
8722 (let* ((end (point))
8723 (template (buffer-substring beg end))
8724 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8725 (shift-what (pcase (and doshift (match-string 2 shift))
8726 (`nil nil)
8727 ("d" 'day)
8728 ("w" (setq shift-n (* 7 shift-n)) 'day)
8729 ("m" 'month)
8730 ("y" 'year)
8731 (_ (error "Unsupported time unit"))))
8732 (nmin 1)
8733 (nmax n)
8734 (n-no-remove -1)
8735 (idprop (org-entry-get nil "ID")))
8736 (when (and doshift
8737 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8738 template))
8739 (delete-region beg end)
8740 (setq end beg)
8741 (setq nmin 0)
8742 (setq nmax (1+ nmax))
8743 (setq n-no-remove nmax))
8744 (goto-char end)
8745 (cl-loop for n from nmin to nmax do
8746 (insert
8747 ;; Prepare clone.
8748 (with-temp-buffer
8749 (insert template)
8750 (org-mode)
8751 (goto-char (point-min))
8752 (org-show-subtree)
8753 (and idprop (if org-clone-delete-id
8754 (org-entry-delete nil "ID")
8755 (org-id-get-create t)))
8756 (unless (= n 0)
8757 (while (re-search-forward org-clock-line-re nil t)
8758 (delete-region (line-beginning-position)
8759 (line-beginning-position 2)))
8760 (goto-char (point-min))
8761 (while (re-search-forward org-drawer-regexp nil t)
8762 (org-remove-empty-drawer-at (point))))
8763 (goto-char (point-min))
8764 (when doshift
8765 (while (re-search-forward org-ts-regexp-both nil t)
8766 (org-timestamp-change (* n shift-n) shift-what))
8767 (unless (= n n-no-remove)
8768 (goto-char (point-min))
8769 (while (re-search-forward org-ts-regexp nil t)
8770 (save-excursion
8771 (goto-char (match-beginning 0))
8772 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8773 (delete-region (match-beginning 1) (match-end 1)))))))
8774 (buffer-string)))))
8775 (goto-char beg)))
8777 ;;; Outline Sorting
8779 (defun org-sort (&optional with-case)
8780 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8781 Optional argument WITH-CASE means sort case-sensitively."
8782 (interactive "P")
8783 (org-call-with-arg
8784 (cond ((org-at-table-p) #'org-table-sort-lines)
8785 ((org-at-item-p) #'org-sort-list)
8786 (t #'org-sort-entries))
8787 with-case))
8789 (defun org-sort-remove-invisible (s)
8790 "Remove invisible part of links and emphasis markers from string S."
8791 (remove-text-properties 0 (length s) org-rm-props s)
8792 (replace-regexp-in-string
8793 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8794 (replace-regexp-in-string
8795 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8796 (org-link-display-format s)
8797 t t) t t))
8799 (defvar org-priority-regexp) ; defined later in the file
8801 (defvar org-after-sorting-entries-or-items-hook nil
8802 "Hook that is run after a bunch of entries or items have been sorted.
8803 When children are sorted, the cursor is in the parent line when this
8804 hook gets called. When a region or a plain list is sorted, the cursor
8805 will be in the first entry of the sorted region/list.")
8807 (defun org-sort-entries
8808 (&optional with-case sorting-type getkey-func compare-func property
8809 interactive?)
8810 "Sort entries on a certain level of an outline tree.
8811 If there is an active region, the entries in the region are sorted.
8812 Else, if the cursor is before the first entry, sort the top-level items.
8813 Else, the children of the entry at point are sorted.
8815 Sorting can be alphabetically, numerically, by date/time as given by
8816 a time stamp, by a property, by priority order, or by a custom function.
8818 The command prompts for the sorting type unless it has been given to the
8819 function through the SORTING-TYPE argument, which needs to be a character,
8820 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8821 the precise meaning of each character:
8823 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8824 c By creation time, which is assumed to be the first inactive time stamp
8825 at the beginning of a line.
8826 d By deadline date/time.
8827 k By clocking time.
8828 n Numerically, by converting the beginning of the entry/item to a number.
8829 o By order of TODO keywords.
8830 p By priority according to the cookie.
8831 r By the value of a property.
8832 s By scheduled date/time.
8833 t By date/time, either the first active time stamp in the entry, or, if
8834 none exist, by the first inactive one.
8836 Capital letters will reverse the sort order.
8838 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8839 called with point at the beginning of the record. It must return a
8840 value that is compatible with COMPARE-FUNC, the function used to
8841 compare entries.
8843 Comparing entries ignores case by default. However, with an optional argument
8844 WITH-CASE, the sorting considers case as well.
8846 Sorting is done against the visible part of the headlines, it ignores hidden
8847 links.
8849 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8851 A non-nil value for INTERACTIVE? is used to signal that this
8852 function is being called interactively."
8853 (interactive (list current-prefix-arg nil nil nil nil t))
8854 (let ((case-func (if with-case 'identity 'downcase))
8855 start beg end stars re re2
8856 txt what tmp)
8857 ;; Find beginning and end of region to sort
8858 (cond
8859 ((org-region-active-p)
8860 ;; we will sort the region
8861 (setq end (region-end)
8862 what "region")
8863 (goto-char (region-beginning))
8864 (unless (org-at-heading-p) (outline-next-heading))
8865 (setq start (point)))
8866 ((or (org-at-heading-p)
8867 (ignore-errors (progn (org-back-to-heading) t)))
8868 ;; we will sort the children of the current headline
8869 (org-back-to-heading)
8870 (setq start (point)
8871 end (progn (org-end-of-subtree t t)
8872 (or (bolp) (insert "\n"))
8873 (when (>= (org-back-over-empty-lines) 1)
8874 (forward-line 1))
8875 (point))
8876 what "children")
8877 (goto-char start)
8878 (outline-show-subtree)
8879 (outline-next-heading))
8881 ;; we will sort the top-level entries in this file
8882 (goto-char (point-min))
8883 (or (org-at-heading-p) (outline-next-heading))
8884 (setq start (point))
8885 (goto-char (point-max))
8886 (beginning-of-line 1)
8887 (when (looking-at ".*?\\S-")
8888 ;; File ends in a non-white line
8889 (end-of-line 1)
8890 (insert "\n"))
8891 (setq end (point-max))
8892 (setq what "top-level")
8893 (goto-char start)
8894 (outline-show-all)))
8896 (setq beg (point))
8897 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8899 (looking-at "\\(\\*+\\)")
8900 (setq stars (match-string 1)
8901 re (concat "^" (regexp-quote stars) " +")
8902 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8903 txt (buffer-substring beg end))
8904 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8905 (when (and (not (equal stars "*")) (string-match re2 txt))
8906 (user-error "Region to sort contains a level above the first entry"))
8908 (unless sorting-type
8909 (message
8910 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8911 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8912 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8913 what)
8914 (setq sorting-type (read-char-exclusive)))
8916 (unless getkey-func
8917 (and (= (downcase sorting-type) ?f)
8918 (setq getkey-func
8919 (or (and interactive?
8920 (org-read-function
8921 "Function for extracting keys: "))
8922 (error "Missing key extractor")))))
8924 (and (= (downcase sorting-type) ?r)
8925 (not property)
8926 (setq property
8927 (completing-read "Property: "
8928 (mapcar #'list (org-buffer-property-keys t))
8929 nil t)))
8931 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8932 (message "Sorting entries...")
8934 (save-restriction
8935 (narrow-to-region start end)
8936 (let ((restore-clock?
8937 ;; The clock marker is lost when using `sort-subr'; mark
8938 ;; the clock with temporary `:org-clock-marker-backup'
8939 ;; text property.
8940 (when (and (eq (org-clock-is-active) (current-buffer))
8941 (<= start (marker-position org-clock-marker))
8942 (>= end (marker-position org-clock-marker)))
8943 (org-with-silent-modifications
8944 (put-text-property (1- org-clock-marker) org-clock-marker
8945 :org-clock-marker-backup t))
8947 (dcst (downcase sorting-type))
8948 (case-fold-search nil)
8949 (now (current-time)))
8950 (sort-subr
8951 (/= dcst sorting-type)
8952 ;; This function moves to the beginning character of the "record" to
8953 ;; be sorted.
8954 (lambda nil
8955 (if (re-search-forward re nil t)
8956 (goto-char (match-beginning 0))
8957 (goto-char (point-max))))
8958 ;; This function moves to the last character of the "record" being
8959 ;; sorted.
8960 (lambda nil
8961 (save-match-data
8962 (condition-case nil
8963 (outline-forward-same-level 1)
8964 (error
8965 (goto-char (point-max))))))
8966 ;; This function returns the value that gets sorted against.
8967 (lambda nil
8968 (cond
8969 ((= dcst ?n)
8970 (if (looking-at org-complex-heading-regexp)
8971 (string-to-number (org-sort-remove-invisible (match-string 4)))
8972 nil))
8973 ((= dcst ?a)
8974 (if (looking-at org-complex-heading-regexp)
8975 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8976 nil))
8977 ((= dcst ?k)
8978 (or (get-text-property (point) :org-clock-minutes) 0))
8979 ((= dcst ?t)
8980 (let ((end (save-excursion (outline-next-heading) (point))))
8981 (if (or (re-search-forward org-ts-regexp end t)
8982 (re-search-forward org-ts-regexp-both end t))
8983 (org-time-string-to-seconds (match-string 0))
8984 (float-time now))))
8985 ((= dcst ?c)
8986 (let ((end (save-excursion (outline-next-heading) (point))))
8987 (if (re-search-forward
8988 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8989 end t)
8990 (org-time-string-to-seconds (match-string 0))
8991 (float-time now))))
8992 ((= dcst ?s)
8993 (let ((end (save-excursion (outline-next-heading) (point))))
8994 (if (re-search-forward org-scheduled-time-regexp end t)
8995 (org-time-string-to-seconds (match-string 1))
8996 (float-time now))))
8997 ((= dcst ?d)
8998 (let ((end (save-excursion (outline-next-heading) (point))))
8999 (if (re-search-forward org-deadline-time-regexp end t)
9000 (org-time-string-to-seconds (match-string 1))
9001 (float-time now))))
9002 ((= dcst ?p)
9003 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9004 (string-to-char (match-string 2))
9005 org-default-priority))
9006 ((= dcst ?r)
9007 (or (org-entry-get nil property) ""))
9008 ((= dcst ?o)
9009 (when (looking-at org-complex-heading-regexp)
9010 (let* ((m (match-string 2))
9011 (s (if (member m org-done-keywords) '- '+)))
9012 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9013 ((= dcst ?f)
9014 (if getkey-func
9015 (progn
9016 (setq tmp (funcall getkey-func))
9017 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9018 tmp)
9019 (error "Invalid key function `%s'" getkey-func)))
9020 (t (error "Invalid sorting type `%c'" sorting-type))))
9022 (cond
9023 ((= dcst ?a) 'string<)
9024 ((= dcst ?f)
9025 (or compare-func
9026 (and interactive?
9027 (org-read-function
9028 (concat "Function for comparing keys "
9029 "(empty for default `sort-subr' predicate): ")
9030 'allow-empty))))
9031 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9032 (when restore-clock?
9033 (move-marker org-clock-marker
9034 (1+ (next-single-property-change
9035 start :org-clock-marker-backup)))
9036 (remove-text-properties (1- org-clock-marker) org-clock-marker
9037 '(:org-clock-marker-backup t)))))
9038 (run-hooks 'org-after-sorting-entries-or-items-hook)
9039 (message "Sorting entries...done")))
9041 ;;; The orgstruct minor mode
9043 ;; Define a minor mode which can be used in other modes in order to
9044 ;; integrate the Org mode structure editing commands.
9046 ;; This is really a hack, because the Org mode structure commands use
9047 ;; keys which normally belong to the major mode. Here is how it
9048 ;; works: The minor mode defines all the keys necessary to operate the
9049 ;; structure commands, but wraps the commands into a function which
9050 ;; tests if the cursor is currently at a headline or a plain list
9051 ;; item. If that is the case, the structure command is used,
9052 ;; temporarily setting many Org mode variables like regular
9053 ;; expressions for filling etc. However, when any of those keys is
9054 ;; used at a different location, function uses `key-binding' to look
9055 ;; up if the key has an associated command in another currently active
9056 ;; keymap (minor modes, major mode, global), and executes that
9057 ;; command. There might be problems if any of the keys is otherwise
9058 ;; used as a prefix key.
9060 (defcustom orgstruct-heading-prefix-regexp ""
9061 "Regexp that matches the custom prefix of Org headlines in
9062 orgstruct(++)-mode."
9063 :group 'org
9064 :version "26.1"
9065 :package-version '(Org . "8.3")
9066 :type 'regexp)
9067 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9069 (defcustom orgstruct-setup-hook nil
9070 "Hook run after orgstruct-mode-map is filled."
9071 :group 'org
9072 :version "24.4"
9073 :package-version '(Org . "8.0")
9074 :type 'hook)
9076 (defvar orgstruct-initialized nil)
9078 (defvar org-local-vars nil
9079 "List of local variables, for use by `orgstruct-mode'.")
9081 ;;;###autoload
9082 (define-minor-mode orgstruct-mode
9083 "Toggle the minor mode `orgstruct-mode'.
9084 This mode is for using Org mode structure commands in other
9085 modes. The following keys behave as if Org mode were active, if
9086 the cursor is on a headline, or on a plain list item (both as
9087 defined by Org mode)."
9088 nil " OrgStruct" (make-sparse-keymap)
9089 (funcall (if orgstruct-mode
9090 'add-to-invisibility-spec
9091 'remove-from-invisibility-spec)
9092 '(outline . t))
9093 (when orgstruct-mode
9094 (org-load-modules-maybe)
9095 (unless orgstruct-initialized
9096 (orgstruct-setup)
9097 (setq orgstruct-initialized t))))
9099 ;;;###autoload
9100 (defun turn-on-orgstruct ()
9101 "Unconditionally turn on `orgstruct-mode'."
9102 (orgstruct-mode 1))
9104 (defvar-local orgstruct-is-++ nil
9105 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9106 (defvar-local org-fb-vars nil)
9107 (defun orgstruct++-mode (&optional arg)
9108 "Toggle `orgstruct-mode', the enhanced version of it.
9109 In addition to setting orgstruct-mode, this also exports all
9110 indentation and autofilling variables from Org mode into the
9111 buffer. It will also recognize item context in multiline items."
9112 (interactive "P")
9113 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9114 (if (< arg 1)
9115 (progn (orgstruct-mode -1)
9116 (dolist (v org-fb-vars)
9117 (set (make-local-variable (car v))
9118 (if (eq (car-safe (cadr v)) 'quote)
9119 (cl-cadadr v)
9120 (nth 1 v)))))
9121 (orgstruct-mode 1)
9122 (setq org-fb-vars nil)
9123 (unless org-local-vars
9124 (setq org-local-vars (org-get-local-variables)))
9125 (let (var val)
9126 (dolist (x org-local-vars)
9127 (when (string-match
9128 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9129 \\|fill-prefix\\|indent-\\)"
9130 (symbol-name (car x)))
9131 (setq var (car x) val (nth 1 x))
9132 (push (list var `(quote ,(eval var))) org-fb-vars)
9133 (set (make-local-variable var)
9134 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9135 (setq-local orgstruct-is-++ t))))
9137 ;;;###autoload
9138 (defun turn-on-orgstruct++ ()
9139 "Unconditionally turn on `orgstruct++-mode'."
9140 (orgstruct++-mode 1))
9142 (defun orgstruct-error ()
9143 "Error when there is no default binding for a structure key."
9144 (interactive)
9145 (funcall (if (fboundp 'user-error)
9146 'user-error
9147 'error)
9148 "This key has no function outside structure elements"))
9150 (defun orgstruct-setup ()
9151 "Setup orgstruct keymap."
9152 (dolist (cell '((org-demote . t)
9153 (org-metaleft . t)
9154 (org-metaright . t)
9155 (org-promote . t)
9156 (org-shiftmetaleft . t)
9157 (org-shiftmetaright . t)
9158 org-backward-element
9159 org-backward-heading-same-level
9160 org-ctrl-c-ret
9161 org-ctrl-c-minus
9162 org-ctrl-c-star
9163 org-cycle
9164 org-force-cycle-archived
9165 org-forward-heading-same-level
9166 org-insert-heading
9167 org-insert-heading-respect-content
9168 org-kill-note-or-show-branches
9169 org-mark-subtree
9170 org-meta-return
9171 org-metadown
9172 org-metaup
9173 org-narrow-to-subtree
9174 org-promote-subtree
9175 org-reveal
9176 org-shiftdown
9177 org-shiftleft
9178 org-shiftmetadown
9179 org-shiftmetaup
9180 org-shiftright
9181 org-shifttab
9182 org-shifttab
9183 org-shiftup
9184 org-show-children
9185 org-show-subtree
9186 org-sort
9187 org-up-element
9188 outline-demote
9189 outline-next-visible-heading
9190 outline-previous-visible-heading
9191 outline-promote
9192 outline-up-heading))
9193 (let ((f (or (car-safe cell) cell))
9194 (disable-when-heading-prefix (cdr-safe cell)))
9195 (when (fboundp f)
9196 (let ((new-bindings))
9197 (dolist (binding (nconc (where-is-internal f org-mode-map)
9198 (where-is-internal f outline-mode-map)))
9199 (push binding new-bindings)
9200 ;; TODO use local-function-key-map
9201 (dolist (rep '(("<tab>" . "TAB")
9202 ("<return>" . "RET")
9203 ("<escape>" . "ESC")
9204 ("<delete>" . "DEL")))
9205 (setq binding (read-kbd-macro
9206 (let ((case-fold-search))
9207 (replace-regexp-in-string
9208 (regexp-quote (cdr rep))
9209 (car rep)
9210 (key-description binding)))))
9211 (cl-pushnew binding new-bindings :test 'equal)))
9212 (dolist (binding new-bindings)
9213 (let ((key (lookup-key orgstruct-mode-map binding)))
9214 (when (or (not key) (numberp key))
9215 (ignore-errors
9216 (org-defkey orgstruct-mode-map
9217 binding
9218 (orgstruct-make-binding
9219 f binding disable-when-heading-prefix))))))))))
9220 (run-hooks 'orgstruct-setup-hook))
9222 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9223 "Create a function for binding in the structure minor mode.
9224 FUN is the command to call inside a table. KEY is the key that
9225 should be checked in for a command to execute outside of tables.
9226 Non-nil `disable-when-heading-prefix' means to disable the command
9227 if `orgstruct-heading-prefix-regexp' is not empty."
9228 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9229 (let ((nname name)
9230 (i 0))
9231 (while (fboundp (intern nname))
9232 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9233 (setq name (intern nname)))
9234 (eval
9235 (let ((bindings '((org-heading-regexp
9236 (concat "^"
9237 orgstruct-heading-prefix-regexp
9238 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9239 (org-outline-regexp
9240 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9241 (org-outline-regexp-bol
9242 (concat "^" org-outline-regexp))
9243 (outline-regexp org-outline-regexp)
9244 (outline-heading-end-regexp "\n")
9245 (outline-level 'org-outline-level)
9246 (outline-heading-alist))))
9247 `(defun ,name (arg)
9248 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9249 "Outside of structure, run the binding of `"
9250 (key-description key) "'."
9251 (when disable-when-heading-prefix
9252 (concat
9253 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9254 "back to the default binding due to limitations of Org's implementation of\n"
9255 "`" (symbol-name fun) "'.")))
9256 (interactive "p")
9257 (let* ((disable
9258 ,(and disable-when-heading-prefix
9259 '(not (string= orgstruct-heading-prefix-regexp ""))))
9260 (fallback
9261 (or disable
9262 (not
9263 (let* ,bindings
9264 (org-context-p 'headline 'item
9265 ,(when (memq fun
9266 '(org-insert-heading
9267 org-insert-heading-respect-content
9268 org-meta-return))
9269 '(when orgstruct-is-++
9270 'item-body))))))))
9271 (if fallback
9272 (let* ((orgstruct-mode)
9273 (binding
9274 (let ((key ,key))
9275 (catch 'exit
9276 (dolist
9277 (rep
9278 '(nil
9279 ("<\\([^>]*\\)tab>" . "\\1TAB")
9280 ("<\\([^>]*\\)return>" . "\\1RET")
9281 ("<\\([^>]*\\)escape>" . "\\1ESC")
9282 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9283 nil)
9284 (when rep
9285 (setq key (read-kbd-macro
9286 (let ((case-fold-search))
9287 (replace-regexp-in-string
9288 (car rep)
9289 (cdr rep)
9290 (key-description key))))))
9291 (when (key-binding key)
9292 (throw 'exit (key-binding key))))))))
9293 (if (keymapp binding)
9294 (org-set-transient-map binding)
9295 (let ((func (or binding
9296 (unless disable
9297 'orgstruct-error))))
9298 (when func
9299 (call-interactively func)))))
9300 (org-run-like-in-org-mode
9301 (lambda ()
9302 (interactive)
9303 (let* ,bindings
9304 (call-interactively ',fun)))))))))
9305 name))
9307 (defun org-contextualize-keys (alist contexts)
9308 "Return valid elements in ALIST depending on CONTEXTS.
9310 `org-agenda-custom-commands' or `org-capture-templates' are the
9311 values used for ALIST, and `org-agenda-custom-commands-contexts'
9312 or `org-capture-templates-contexts' are the associated contexts
9313 definitions."
9314 (let ((contexts
9315 ;; normalize contexts
9316 (mapcar
9317 (lambda(c) (cond ((listp (cadr c))
9318 (list (car c) (car c) (nth 1 c)))
9319 ((string= "" (cadr c))
9320 (list (car c) (car c) (nth 2 c)))
9321 (t c)))
9322 contexts))
9323 (a alist) r s)
9324 ;; loop over all commands or templates
9325 (dolist (c a)
9326 (let (vrules repl)
9327 (cond
9328 ((not (assoc (car c) contexts))
9329 (push c r))
9330 ((and (assoc (car c) contexts)
9331 (setq vrules (org-contextualize-validate-key
9332 (car c) contexts)))
9333 (mapc (lambda (vr)
9334 (unless (equal (car vr) (cadr vr))
9335 (setq repl vr)))
9336 vrules)
9337 (if (not repl) (push c r)
9338 (push (cadr repl) s)
9339 (push
9340 (cons (car c)
9341 (cdr (or (assoc (cadr repl) alist)
9342 (error "Undefined key `%s' as contextual replacement for `%s'"
9343 (cadr repl) (car c)))))
9344 r))))))
9345 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9346 (delq
9348 (delete-dups
9349 (mapcar (lambda (x)
9350 (let ((tpl (car x)))
9351 (unless (delq
9353 (mapcar (lambda (y)
9354 (equal y tpl))
9356 x)))
9357 (reverse r))))))
9359 (defun org-contextualize-validate-key (key contexts)
9360 "Check CONTEXTS for agenda or capture KEY."
9361 (let (res)
9362 (dolist (r contexts)
9363 (dolist (rr (car (last r)))
9364 (when
9365 (and (equal key (car r))
9366 (if (functionp rr) (funcall rr)
9367 (or (and (eq (car rr) 'in-file)
9368 (buffer-file-name)
9369 (string-match (cdr rr) (buffer-file-name)))
9370 (and (eq (car rr) 'in-mode)
9371 (string-match (cdr rr) (symbol-name major-mode)))
9372 (and (eq (car rr) 'in-buffer)
9373 (string-match (cdr rr) (buffer-name)))
9374 (when (and (eq (car rr) 'not-in-file)
9375 (buffer-file-name))
9376 (not (string-match (cdr rr) (buffer-file-name))))
9377 (when (eq (car rr) 'not-in-mode)
9378 (not (string-match (cdr rr) (symbol-name major-mode))))
9379 (when (eq (car rr) 'not-in-buffer)
9380 (not (string-match (cdr rr) (buffer-name)))))))
9381 (push r res))))
9382 (delete-dups (delq nil res))))
9384 (defun org-context-p (&rest contexts)
9385 "Check if local context is any of CONTEXTS.
9386 Possible values in the list of contexts are `table', `headline', and `item'."
9387 (let ((pos (point)))
9388 (goto-char (point-at-bol))
9389 (prog1 (or (and (memq 'table contexts)
9390 (looking-at "[ \t]*|"))
9391 (and (memq 'headline contexts)
9392 (looking-at org-outline-regexp))
9393 (and (memq 'item contexts)
9394 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9395 (and (memq 'item-body contexts)
9396 (org-in-item-p)))
9397 (goto-char pos))))
9399 ;;;###autoload
9400 (defun org-run-like-in-org-mode (cmd)
9401 "Run a command, pretending that the current buffer is in Org mode.
9402 This will temporarily bind local variables that are typically bound in
9403 Org mode to the values they have in Org mode, and then interactively
9404 call CMD."
9405 (org-load-modules-maybe)
9406 (unless org-local-vars
9407 (setq org-local-vars (org-get-local-variables)))
9408 (let (binds)
9409 (dolist (var org-local-vars)
9410 (when (or (not (boundp (car var)))
9411 (eq (symbol-value (car var))
9412 (default-value (car var))))
9413 (push (list (car var) `(quote ,(cadr var))) binds)))
9414 (eval `(let ,binds
9415 (call-interactively (quote ,cmd))))))
9417 (defun org-get-category (&optional pos force-refresh)
9418 "Get the category applying to position POS."
9419 (save-match-data
9420 (when force-refresh (org-refresh-category-properties))
9421 (let ((pos (or pos (point))))
9422 (or (get-text-property pos 'org-category)
9423 (progn (org-refresh-category-properties)
9424 (get-text-property pos 'org-category))))))
9426 ;;; Refresh properties
9428 (defun org-refresh-properties (dprop tprop)
9429 "Refresh buffer text properties.
9430 DPROP is the drawer property and TPROP is either the
9431 corresponding text property to set, or an alist with each element
9432 being a text property (as a symbol) and a function to apply to
9433 the value of the drawer property."
9434 (let* ((case-fold-search t)
9435 (inhibit-read-only t)
9436 (inherit? (org-property-inherit-p dprop))
9437 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9438 (global (and inherit? (org--property-global-value dprop nil))))
9439 (org-with-silent-modifications
9440 (org-with-point-at 1
9441 ;; Set global values (e.g., values defined through
9442 ;; "#+PROPERTY:" keywords) to the whole buffer.
9443 (when global (put-text-property (point-min) (point-max) tprop global))
9444 ;; Set local values.
9445 (while (re-search-forward property-re nil t)
9446 (when (org-at-property-p)
9447 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9448 (outline-next-heading))))))
9450 (defun org-refresh-property (tprop p &optional inherit)
9451 "Refresh the buffer text property TPROP from the drawer property P.
9452 The refresh happens only for the current headline, or the whole
9453 sub-tree if optional argument INHERIT is non-nil."
9454 (unless (org-before-first-heading-p)
9455 (save-excursion
9456 (org-back-to-heading t)
9457 (let ((start (point))
9458 (end (save-excursion
9459 (if inherit (org-end-of-subtree t t)
9460 (or (outline-next-heading) (point-max))))))
9461 (if (symbolp tprop)
9462 ;; TPROP is a text property symbol.
9463 (put-text-property start end tprop p)
9464 ;; TPROP is an alist with (property . function) elements.
9465 (pcase-dolist (`(,prop . ,f) tprop)
9466 (put-text-property start end prop (funcall f p))))))))
9468 (defun org-refresh-category-properties ()
9469 "Refresh category text properties in the buffer."
9470 (let ((case-fold-search t)
9471 (inhibit-read-only t)
9472 (default-category
9473 (cond ((null org-category)
9474 (if buffer-file-name
9475 (file-name-sans-extension
9476 (file-name-nondirectory buffer-file-name))
9477 "???"))
9478 ((symbolp org-category) (symbol-name org-category))
9479 (t org-category))))
9480 (org-with-silent-modifications
9481 (org-with-wide-buffer
9482 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9483 ;; This is the default category for the buffer. If none is
9484 ;; found, fall-back to `org-category' or buffer file name.
9485 (put-text-property
9486 (point-min) (point-max)
9487 'org-category
9488 (catch 'buffer-category
9489 (goto-char (point-max))
9490 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9491 (let ((element (org-element-at-point)))
9492 (when (eq (org-element-type element) 'keyword)
9493 (throw 'buffer-category
9494 (org-element-property :value element)))))
9495 default-category))
9496 ;; Set sub-tree specific categories.
9497 (goto-char (point-min))
9498 (let ((regexp (org-re-property "CATEGORY")))
9499 (while (re-search-forward regexp nil t)
9500 (let ((value (match-string-no-properties 3)))
9501 (when (org-at-property-p)
9502 (put-text-property
9503 (save-excursion (org-back-to-heading t) (point))
9504 (save-excursion (org-end-of-subtree t t) (point))
9505 'org-category
9506 value)))))))))
9508 (defun org-refresh-stats-properties ()
9509 "Refresh stats text properties in the buffer."
9510 (org-with-silent-modifications
9511 (org-with-point-at 1
9512 (let ((regexp (concat org-outline-regexp-bol
9513 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9514 (while (re-search-forward regexp nil t)
9515 (let* ((numerator (string-to-number (match-string 1)))
9516 (denominator (and (match-end 2)
9517 (string-to-number (match-string 2))))
9518 (stats (cond ((not denominator) numerator) ;percent
9519 ((= denominator 0) 0)
9520 (t (/ (* numerator 100) denominator)))))
9521 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9522 'org-stats stats)))))))
9524 (defun org-refresh-effort-properties ()
9525 "Refresh effort properties"
9526 (org-refresh-properties
9527 org-effort-property
9528 '((effort . identity)
9529 (effort-minutes . org-duration-to-minutes))))
9531 ;;;; Link Stuff
9533 ;;; Link abbreviations
9535 (defun org-link-expand-abbrev (link)
9536 "Apply replacements as defined in `org-link-abbrev-alist'."
9537 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9538 (let* ((key (match-string 1 link))
9539 (as (or (assoc key org-link-abbrev-alist-local)
9540 (assoc key org-link-abbrev-alist)))
9541 (tag (and (match-end 2) (match-string 3 link)))
9542 rpl)
9543 (if (not as)
9544 link
9545 (setq rpl (cdr as))
9546 (cond
9547 ((symbolp rpl) (funcall rpl tag))
9548 ((string-match "%(\\([^)]+\\))" rpl)
9549 (replace-match
9550 (save-match-data
9551 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9552 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9553 ((string-match "%h" rpl)
9554 (replace-match (url-hexify-string (or tag "")) t t rpl))
9555 (t (concat rpl tag)))))
9556 link))
9558 ;;; Storing and inserting links
9560 (defvar org-insert-link-history nil
9561 "Minibuffer history for links inserted with `org-insert-link'.")
9563 (defvar org-stored-links nil
9564 "Contains the links stored with `org-store-link'.")
9566 (defvar org-store-link-plist nil
9567 "Plist with info about the most recently link created with `org-store-link'.")
9569 (defun org-store-link-functions ()
9570 "Return a list of functions that are called to create and store a link.
9571 The functions defined in the :store property of
9572 `org-link-parameters'.
9574 Each function will be called in turn until one returns a non-nil
9575 value. Each function should check if it is responsible for
9576 creating this link (for example by looking at the major mode).
9577 If not, it must exit and return nil. If yes, it should return
9578 a non-nil value after calling `org-store-link-props' with a list
9579 of properties and values. Special properties are:
9581 :type The link prefix, like \"http\". This must be given.
9582 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9583 This is obligatory as well.
9584 :description Optional default description for the second pair
9585 of brackets in an Org mode link. The user can still change
9586 this when inserting this link into an Org mode buffer.
9588 In addition to these, any additional properties can be specified
9589 and then used in capture templates."
9590 (cl-loop for link in org-link-parameters
9591 with store-func
9592 do (setq store-func (org-link-get-parameter (car link) :store))
9593 if store-func
9594 collect store-func))
9596 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9597 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9599 ;;;###autoload
9600 (defun org-store-link (arg)
9601 "Store an org-link to the current location.
9602 \\<org-mode-map>
9603 This link is added to `org-stored-links' and can later be inserted
9604 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9606 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9607 A single
9608 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9609 `org-gnus-prefer-web-links' for links to Usenet articles.
9611 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9612 skipping storing functions that are not
9613 part of Org core.
9615 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9616 prefix ARG forces storing a link for each line in the
9617 active region."
9618 (interactive "P")
9619 (org-load-modules-maybe)
9620 (if (and (equal arg '(64)) (org-region-active-p))
9621 (save-excursion
9622 (let ((end (region-end)))
9623 (goto-char (region-beginning))
9624 (set-mark (point))
9625 (while (< (point-at-eol) end)
9626 (move-end-of-line 1) (activate-mark)
9627 (let (current-prefix-arg)
9628 (call-interactively 'org-store-link))
9629 (move-beginning-of-line 2)
9630 (set-mark (point)))))
9631 (setq org-store-link-plist nil)
9632 (let (link cpltxt desc description search
9633 txt custom-id agenda-link sfuns sfunsn)
9634 (cond
9636 ;; Store a link using an external link type
9637 ((and (not (equal arg '(16)))
9638 (setq sfuns
9639 (delq
9640 nil (mapcar (lambda (f)
9641 (let (fs) (if (funcall f) (push f fs))))
9642 (org-store-link-functions)))
9643 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9644 (or (and (cdr sfuns)
9645 (funcall (intern
9646 (completing-read
9647 "Which function for creating the link? "
9648 sfunsn nil t (car sfunsn)))))
9649 (funcall (caar sfuns)))
9650 (setq link (plist-get org-store-link-plist :link)
9651 desc (or (plist-get org-store-link-plist
9652 :description)
9653 link))))
9655 ;; Store a link from a source code buffer.
9656 ((org-src-edit-buffer-p)
9657 (let ((coderef-format (org-src-coderef-format)))
9658 (cond ((save-excursion
9659 (beginning-of-line)
9660 (looking-at (org-src-coderef-regexp coderef-format)))
9661 (setq link (format "(%s)" (match-string-no-properties 3))))
9662 ((called-interactively-p 'any)
9663 (let ((label (read-string "Code line label: ")))
9664 (end-of-line)
9665 (setq link (format coderef-format label))
9666 (let ((gc (- 79 (length link))))
9667 (if (< (current-column) gc)
9668 (org-move-to-column gc t)
9669 (insert " ")))
9670 (insert link)
9671 (setq link (concat "(" label ")"))
9672 (setq desc nil)))
9673 (t (setq link nil)))))
9675 ;; We are in the agenda, link to referenced location
9676 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9677 (let ((m (or (get-text-property (point) 'org-hd-marker)
9678 (get-text-property (point) 'org-marker))))
9679 (when m
9680 (org-with-point-at m
9681 (setq agenda-link
9682 (if (called-interactively-p 'any)
9683 (call-interactively 'org-store-link)
9684 (org-store-link nil)))))))
9686 ((eq major-mode 'calendar-mode)
9687 (let ((cd (calendar-cursor-to-date)))
9688 (setq link
9689 (format-time-string
9690 (car org-time-stamp-formats)
9691 (apply 'encode-time
9692 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9693 nil nil nil))))
9694 (org-store-link-props :type "calendar" :date cd)))
9696 ((eq major-mode 'help-mode)
9697 (setq link (concat "help:" (save-excursion
9698 (goto-char (point-min))
9699 (looking-at "^[^ ]+")
9700 (match-string 0))))
9701 (org-store-link-props :type "help"))
9703 ((eq major-mode 'w3-mode)
9704 (setq cpltxt (if (and (buffer-name)
9705 (not (string-match "Untitled" (buffer-name))))
9706 (buffer-name)
9707 (url-view-url t))
9708 link (url-view-url t))
9709 (org-store-link-props :type "w3" :url (url-view-url t)))
9711 ((eq major-mode 'image-mode)
9712 (setq cpltxt (concat "file:"
9713 (abbreviate-file-name buffer-file-name))
9714 link cpltxt)
9715 (org-store-link-props :type "image" :file buffer-file-name))
9717 ;; In dired, store a link to the file of the current line
9718 ((derived-mode-p 'dired-mode)
9719 (let ((file (dired-get-filename nil t)))
9720 (setq file (if file
9721 (abbreviate-file-name
9722 (expand-file-name (dired-get-filename nil t)))
9723 ;; otherwise, no file so use current directory.
9724 default-directory))
9725 (setq cpltxt (concat "file:" file)
9726 link cpltxt)))
9728 ((setq search (run-hook-with-args-until-success
9729 'org-create-file-search-functions))
9730 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9731 "::" search))
9732 (setq cpltxt (or description link)))
9734 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9735 (org-with-limited-levels
9736 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9737 (cond
9738 ;; Store a link using the target at point
9739 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9740 (setq cpltxt
9741 (concat "file:"
9742 (abbreviate-file-name
9743 (buffer-file-name (buffer-base-buffer)))
9744 "::" (match-string 1))
9745 link cpltxt))
9746 ((and (featurep 'org-id)
9747 (or (eq org-id-link-to-org-use-id t)
9748 (and (called-interactively-p 'any)
9749 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9750 (and (eq org-id-link-to-org-use-id
9751 'create-if-interactive-and-no-custom-id)
9752 (not custom-id))))
9753 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9754 ;; Store a link using the ID at point
9755 (setq link (condition-case nil
9756 (prog1 (org-id-store-link)
9757 (setq desc (or (plist-get org-store-link-plist
9758 :description)
9759 "")))
9760 (error
9761 ;; Probably before first headline, link only to file
9762 (concat "file:"
9763 (abbreviate-file-name
9764 (buffer-file-name (buffer-base-buffer))))))))
9766 ;; Just link to current headline
9767 (setq cpltxt (concat "file:"
9768 (abbreviate-file-name
9769 (buffer-file-name (buffer-base-buffer)))))
9770 ;; Add a context search string
9771 (when (org-xor org-context-in-file-links
9772 (equal arg '(4)))
9773 (let* ((element (org-element-at-point))
9774 (name (org-element-property :name element)))
9775 (setq txt (cond
9776 ((org-at-heading-p) nil)
9777 (name)
9778 ((org-region-active-p)
9779 (buffer-substring (region-beginning) (region-end)))))
9780 (when (or (null txt) (string-match "\\S-" txt))
9781 (setq cpltxt
9782 (concat cpltxt "::"
9783 (condition-case nil
9784 (org-make-org-heading-search-string txt)
9785 (error "")))
9786 desc (or name
9787 (nth 4 (ignore-errors (org-heading-components)))
9788 "NONE")))))
9789 (when (string-match "::\\'" cpltxt)
9790 (setq cpltxt (substring cpltxt 0 -2)))
9791 (setq link cpltxt)))))
9793 ((buffer-file-name (buffer-base-buffer))
9794 ;; Just link to this file here.
9795 (setq cpltxt (concat "file:"
9796 (abbreviate-file-name
9797 (buffer-file-name (buffer-base-buffer)))))
9798 ;; Add a context string.
9799 (when (org-xor org-context-in-file-links
9800 (equal arg '(4)))
9801 (setq txt (if (org-region-active-p)
9802 (buffer-substring (region-beginning) (region-end))
9803 (buffer-substring (point-at-bol) (point-at-eol))))
9804 ;; Only use search option if there is some text.
9805 (when (string-match "\\S-" txt)
9806 (setq cpltxt
9807 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9808 desc "NONE")))
9809 (setq link cpltxt))
9811 ((called-interactively-p 'interactive)
9812 (user-error "No method for storing a link from this buffer"))
9814 (t (setq link nil)))
9816 ;; We're done setting link and desc, clean up
9817 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9818 (setq link (or link cpltxt)
9819 desc (or desc cpltxt))
9820 (cond ((not desc))
9821 ((equal desc "NONE") (setq desc nil))
9822 (t (setq desc
9823 (replace-regexp-in-string
9824 org-bracket-link-analytic-regexp
9825 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9826 desc))))
9827 ;; Return the link
9828 (if (not (and (or (called-interactively-p 'any)
9829 executing-kbd-macro)
9830 link))
9831 (or agenda-link (and link (org-make-link-string link desc)))
9832 (push (list link desc) org-stored-links)
9833 (message "Stored: %s" (or desc link))
9834 (when custom-id
9835 (setq link (concat "file:" (abbreviate-file-name
9836 (buffer-file-name)) "::#" custom-id))
9837 (push (list link desc) org-stored-links))
9838 (car org-stored-links)))))
9840 (defun org-store-link-props (&rest plist)
9841 "Store link properties, extract names, addresses and dates."
9842 (let ((x (plist-get plist :from)))
9843 (when x
9844 (let ((adr (mail-extract-address-components x)))
9845 (setq plist (plist-put plist :fromname (car adr)))
9846 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9847 (let ((x (plist-get plist :to)))
9848 (when x
9849 (let ((adr (mail-extract-address-components x)))
9850 (setq plist (plist-put plist :toname (car adr)))
9851 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9852 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9853 (when x
9854 (setq plist (plist-put plist :date-timestamp
9855 (format-time-string
9856 (org-time-stamp-format t) x)))
9857 (setq plist (plist-put plist :date-timestamp-inactive
9858 (format-time-string
9859 (org-time-stamp-format t t) x)))))
9860 (let ((from (plist-get plist :from))
9861 (to (plist-get plist :to)))
9862 (when (and from to org-from-is-user-regexp)
9863 (setq plist
9864 (plist-put plist :fromto
9865 (if (string-match org-from-is-user-regexp from)
9866 (concat "to %t")
9867 (concat "from %f"))))))
9868 (setq org-store-link-plist plist))
9870 (defun org-add-link-props (&rest plist)
9871 "Add these properties to the link property list."
9872 (let (key value)
9873 (while plist
9874 (setq key (pop plist) value (pop plist))
9875 (setq org-store-link-plist
9876 (plist-put org-store-link-plist key value)))))
9878 (defun org-email-link-description (&optional fmt)
9879 "Return the description part of an email link.
9880 This takes information from `org-store-link-plist' and formats it
9881 according to FMT (default from `org-email-link-description-format')."
9882 (setq fmt (or fmt org-email-link-description-format))
9883 (let* ((p org-store-link-plist)
9884 (to (plist-get p :toaddress))
9885 (from (plist-get p :fromaddress))
9886 (table
9887 (list
9888 (cons "%c" (plist-get p :fromto))
9889 (cons "%F" (plist-get p :from))
9890 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9891 (cons "%T" (plist-get p :to))
9892 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9893 (cons "%s" (plist-get p :subject))
9894 (cons "%d" (plist-get p :date))
9895 (cons "%m" (plist-get p :message-id)))))
9896 (when (string-match "%c" fmt)
9897 ;; Check if the user wrote this message
9898 (if (and org-from-is-user-regexp from to
9899 (save-match-data (string-match org-from-is-user-regexp from)))
9900 (setq fmt (replace-match "to %t" t t fmt))
9901 (setq fmt (replace-match "from %f" t t fmt))))
9902 (org-replace-escapes fmt table)))
9904 (defun org-make-org-heading-search-string (&optional string)
9905 "Make search string for the current headline or STRING."
9906 (let ((s (or string
9907 (and (derived-mode-p 'org-mode)
9908 (save-excursion
9909 (org-back-to-heading t)
9910 (org-element-property :raw-value (org-element-at-point))))))
9911 (lines org-context-in-file-links))
9912 (unless string (setq s (concat "*" s))) ;Add * for headlines
9913 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9914 (when (and string (integerp lines) (> lines 0))
9915 (let ((slines (org-split-string s "\n")))
9916 (when (< lines (length slines))
9917 (setq s (mapconcat
9918 'identity
9919 (reverse (nthcdr (- (length slines) lines)
9920 (reverse slines))) "\n")))))
9921 (mapconcat #'identity (split-string s) " ")))
9923 (defun org-make-link-string (link &optional description)
9924 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9925 (unless (org-string-nw-p link) (error "Empty link"))
9926 (let ((uri (cond ((string-match org-link-types-re link)
9927 (concat (match-string 1 link)
9928 (org-link-escape (substring link (match-end 1)))))
9929 ;; For readability, url-encode internal links only
9930 ;; when absolutely needed (i.e, when they contain
9931 ;; square brackets). File links however, are
9932 ;; encoded since, e.g., spaces are significant.
9933 ((or (file-name-absolute-p link)
9934 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9935 (org-link-escape link))
9936 (t link)))
9937 (description
9938 (and (org-string-nw-p description)
9939 ;; Remove brackets from description, as they are fatal.
9940 (replace-regexp-in-string
9941 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9942 (org-trim description)))))
9943 (format "[[%s]%s]"
9945 (if description (format "[%s]" description) ""))))
9947 (defconst org-link-escape-chars
9948 ;;%20 %5B %5D %25
9949 '(?\s ?\[ ?\] ?%)
9950 "List of characters that should be escaped in a link when stored to Org.
9951 This is the list that is used for internal purposes.")
9953 (defun org-link-escape (text &optional table merge)
9954 "Return percent escaped representation of TEXT.
9955 TEXT is a string with the text to escape.
9956 Optional argument TABLE is a list with characters that should be
9957 escaped. When nil, `org-link-escape-chars' is used.
9958 If optional argument MERGE is set, merge TABLE into
9959 `org-link-escape-chars'."
9960 (let ((characters-to-encode
9961 (cond ((null table) org-link-escape-chars)
9962 (merge (append org-link-escape-chars table))
9963 (t table))))
9964 (mapconcat
9965 (lambda (c)
9966 (if (or (memq c characters-to-encode)
9967 (and org-url-hexify-p (or (< c 32) (> c 126))))
9968 (mapconcat (lambda (e) (format "%%%.2X" e))
9969 (or (encode-coding-char c 'utf-8)
9970 (error "Unable to percent escape character: %c" c))
9972 (char-to-string c)))
9973 text "")))
9975 (defun org-link-unescape (str)
9976 "Unhex hexified Unicode parts in string STR.
9977 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9978 reciprocal of `org-link-escape', which see."
9979 (if (org-string-nw-p str)
9980 (replace-regexp-in-string
9981 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9982 str))
9984 (defun org-link-unescape-compound (hex)
9985 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9986 Note: this function also decodes single byte encodings like
9987 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9988 (save-match-data
9989 (let* ((bytes (cdr (split-string hex "%")))
9990 (ret "")
9991 (eat 0)
9992 (sum 0))
9993 (while bytes
9994 (let* ((val (string-to-number (pop bytes) 16))
9995 (shift-xor
9996 (if (= 0 eat)
9997 (cond
9998 ((>= val 252) (cons 6 252))
9999 ((>= val 248) (cons 5 248))
10000 ((>= val 240) (cons 4 240))
10001 ((>= val 224) (cons 3 224))
10002 ((>= val 192) (cons 2 192))
10003 (t (cons 0 0)))
10004 (cons 6 128))))
10005 (when (>= val 192) (setq eat (car shift-xor)))
10006 (setq val (logxor val (cdr shift-xor)))
10007 (setq sum (+ (lsh sum (car shift-xor)) val))
10008 (when (> eat 0) (setq eat (- eat 1)))
10009 (cond
10010 ((= 0 eat) ;multi byte
10011 (setq ret (concat ret (char-to-string sum)))
10012 (setq sum 0))
10013 ((not bytes) ; single byte(s)
10014 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10015 ret)))
10017 (defun org-link-unescape-single-byte-sequence (hex)
10018 "Unhexify hex-encoded single byte character sequences."
10019 (mapconcat (lambda (byte)
10020 (char-to-string (string-to-number byte 16)))
10021 (cdr (split-string hex "%")) ""))
10023 (defun org-fixup-message-id-for-http (s)
10024 "Replace special characters in a message id, so it can be used in an http query."
10025 (when (string-match "%" s)
10026 (setq s (mapconcat (lambda (c)
10027 (if (eq c ?%)
10028 "%25"
10029 (char-to-string c)))
10030 s "")))
10031 (while (string-match "<" s)
10032 (setq s (replace-match "%3C" t t s)))
10033 (while (string-match ">" s)
10034 (setq s (replace-match "%3E" t t s)))
10035 (while (string-match "@" s)
10036 (setq s (replace-match "%40" t t s)))
10039 (defun org-link-prettify (link)
10040 "Return a human-readable representation of LINK.
10041 The car of LINK must be a raw link.
10042 The cdr of LINK must be either a link description or nil."
10043 (let ((desc (or (cadr link) "<no description>")))
10044 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10045 "<" (car link) ">")))
10047 ;;;###autoload
10048 (defun org-insert-link-global ()
10049 "Insert a link like Org mode does.
10050 This command can be called in any mode to insert a link in Org syntax."
10051 (interactive)
10052 (org-load-modules-maybe)
10053 (org-run-like-in-org-mode 'org-insert-link))
10055 (defun org-insert-all-links (arg &optional pre post)
10056 "Insert all links in `org-stored-links'.
10057 When a universal prefix, do not delete the links from `org-stored-links'.
10058 When `ARG' is a number, insert the last N link(s).
10059 `PRE' and `POST' are optional arguments to define a string to
10060 prepend or to append."
10061 (interactive "P")
10062 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10063 (links (copy-sequence org-stored-links))
10064 (pr (or pre "- "))
10065 (po (or post "\n"))
10066 (cnt 1) l)
10067 (if (null org-stored-links)
10068 (message "No link to insert")
10069 (while (and (or (listp arg) (>= arg cnt))
10070 (setq l (if (listp arg)
10071 (pop links)
10072 (pop org-stored-links))))
10073 (setq cnt (1+ cnt))
10074 (insert pr)
10075 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10076 (insert po)))))
10078 (defun org-insert-last-stored-link (arg)
10079 "Insert the last link stored in `org-stored-links'."
10080 (interactive "p")
10081 (org-insert-all-links arg "" "\n"))
10083 (defun org-link-fontify-links-to-this-file ()
10084 "Fontify links to the current file in `org-stored-links'."
10085 (let ((f (buffer-file-name)) a b)
10086 (setq a (mapcar (lambda(l)
10087 (let ((ll (car l)))
10088 (when (and (string-match "^file:\\(.+\\)::" ll)
10089 (equal f (expand-file-name (match-string 1 ll))))
10090 ll)))
10091 org-stored-links))
10092 (when (featurep 'org-id)
10093 (setq b (mapcar (lambda(l)
10094 (let ((ll (car l)))
10095 (when (and (string-match "^id:\\(.+\\)$" ll)
10096 (equal f (expand-file-name
10097 (or (org-id-find-id-file
10098 (match-string 1 ll)) ""))))
10099 ll)))
10100 org-stored-links)))
10101 (mapcar (lambda(l)
10102 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10103 (delq nil (append a b)))))
10105 (defvar org--links-history nil)
10106 (defun org-insert-link (&optional complete-file link-location default-description)
10107 "Insert a link. At the prompt, enter the link.
10109 Completion can be used to insert any of the link protocol prefixes in use.
10111 The history can be used to select a link previously stored with
10112 `org-store-link'. When the empty string is entered (i.e. if you just
10113 press `RET' at the prompt), the link defaults to the most recently
10114 stored link. As `SPC' triggers completion in the minibuffer, you need to
10115 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10117 You will also be prompted for a description, and if one is given, it will
10118 be displayed in the buffer instead of the link.
10120 If there is already a link at point, this command will allow you to edit
10121 link and description parts.
10123 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10124 file name can be
10125 selected using completion. The path to the file will be relative to the
10126 current directory if the file is in the current directory or a subdirectory.
10127 Otherwise, the link will be the absolute path as completed in the minibuffer
10128 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10129 option `org-link-file-path-type'.
10131 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10132 absolute path even if the file is in
10133 the current directory or below.
10135 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10136 prefix negates `org-keep-stored-link-after-insertion'.
10138 If the LINK-LOCATION parameter is non-nil, this value will be used as
10139 the link location instead of reading one interactively.
10141 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10142 be used as the default description. Otherwise, if
10143 `org-make-link-description-function' is non-nil, this function
10144 will be called with the link target, and the result will be the
10145 default link description."
10146 (interactive "P")
10147 (let* ((wcf (current-window-configuration))
10148 (origbuf (current-buffer))
10149 (region (when (org-region-active-p)
10150 (buffer-substring (region-beginning) (region-end))))
10151 (remove (and region (list (region-beginning) (region-end))))
10152 (desc region)
10153 (link link-location)
10154 (abbrevs org-link-abbrev-alist-local)
10155 entry all-prefixes auto-desc)
10156 (cond
10157 (link-location) ; specified by arg, just use it.
10158 ((org-in-regexp org-bracket-link-regexp 1)
10159 ;; We do have a link at point, and we are going to edit it.
10160 (setq remove (list (match-beginning 0) (match-end 0)))
10161 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10162 (setq link (read-string "Link: "
10163 (org-link-unescape
10164 (match-string-no-properties 1)))))
10165 ((or (org-in-regexp org-angle-link-re)
10166 (org-in-regexp org-plain-link-re))
10167 ;; Convert to bracket link
10168 (setq remove (list (match-beginning 0) (match-end 0))
10169 link (read-string "Link: "
10170 (org-unbracket-string "<" ">" (match-string 0)))))
10171 ((member complete-file '((4) (16)))
10172 ;; Completing read for file names.
10173 (setq link (org-file-complete-link complete-file)))
10175 ;; Read link, with completion for stored links.
10176 (org-link-fontify-links-to-this-file)
10177 (org-switch-to-buffer-other-window "*Org Links*")
10178 (with-current-buffer "*Org Links*"
10179 (erase-buffer)
10180 (insert "Insert a link.
10181 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10182 (when org-stored-links
10183 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10184 (insert (mapconcat 'org-link-prettify
10185 (reverse org-stored-links) "\n")))
10186 (goto-char (point-min)))
10187 (let ((cw (selected-window)))
10188 (select-window (get-buffer-window "*Org Links*" 'visible))
10189 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10190 (unless (pos-visible-in-window-p (point-max))
10191 (org-fit-window-to-buffer))
10192 (and (window-live-p cw) (select-window cw)))
10193 (setq all-prefixes (append (mapcar 'car abbrevs)
10194 (mapcar 'car org-link-abbrev-alist)
10195 (org-link-types)))
10196 (unwind-protect
10197 ;; Fake a link history, containing the stored links.
10198 (let ((org--links-history
10199 (append (mapcar #'car org-stored-links)
10200 org-insert-link-history)))
10201 (setq link
10202 (org-completing-read
10203 "Link: "
10204 (append
10205 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10206 (mapcar #'car org-stored-links))
10207 nil nil nil
10208 'org--links-history
10209 (caar org-stored-links)))
10210 (unless (org-string-nw-p link) (user-error "No link selected"))
10211 (dolist (l org-stored-links)
10212 (when (equal link (cadr l))
10213 (setq link (car l))
10214 (setq auto-desc t)))
10215 (when (or (member link all-prefixes)
10216 (and (equal ":" (substring link -1))
10217 (member (substring link 0 -1) all-prefixes)
10218 (setq link (substring link 0 -1))))
10219 (setq link (with-current-buffer origbuf
10220 (org-link-try-special-completion link)))))
10221 (set-window-configuration wcf)
10222 (kill-buffer "*Org Links*"))
10223 (setq entry (assoc link org-stored-links))
10224 (or entry (push link org-insert-link-history))
10225 (setq desc (or desc (nth 1 entry)))))
10227 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10228 (not org-keep-stored-link-after-insertion))
10229 (setq org-stored-links (delq (assoc link org-stored-links)
10230 org-stored-links)))
10232 (when (and (string-match org-plain-link-re link)
10233 (not (string-match org-ts-regexp link)))
10234 ;; URL-like link, normalize the use of angular brackets.
10235 (setq link (org-unbracket-string "<" ">" link)))
10237 ;; Check if we are linking to the current file with a search
10238 ;; option If yes, simplify the link by using only the search
10239 ;; option.
10240 (when (and buffer-file-name
10241 (let ((case-fold-search nil))
10242 (string-match "\\`file:\\(.+?\\)::" link)))
10243 (let ((path (match-string-no-properties 1 link))
10244 (search (substring-no-properties link (match-end 0))))
10245 (save-match-data
10246 (when (equal (file-truename buffer-file-name) (file-truename path))
10247 ;; We are linking to this same file, with a search option
10248 (setq link search)))))
10250 ;; Check if we can/should use a relative path. If yes, simplify the link
10251 (let ((case-fold-search nil))
10252 (when (string-match "\\`\\(file\\|docview\\):" link)
10253 (let* ((type (match-string-no-properties 0 link))
10254 (path (substring-no-properties link (match-end 0)))
10255 (origpath path))
10256 (cond
10257 ((or (eq org-link-file-path-type 'absolute)
10258 (equal complete-file '(16)))
10259 (setq path (abbreviate-file-name (expand-file-name path))))
10260 ((eq org-link-file-path-type 'noabbrev)
10261 (setq path (expand-file-name path)))
10262 ((eq org-link-file-path-type 'relative)
10263 (setq path (file-relative-name path)))
10265 (save-match-data
10266 (if (string-match (concat "^" (regexp-quote
10267 (expand-file-name
10268 (file-name-as-directory
10269 default-directory))))
10270 (expand-file-name path))
10271 ;; We are linking a file with relative path name.
10272 (setq path (substring (expand-file-name path)
10273 (match-end 0)))
10274 (setq path (abbreviate-file-name (expand-file-name path)))))))
10275 (setq link (concat type path))
10276 (when (equal desc origpath)
10277 (setq desc path)))))
10279 (unless auto-desc
10280 (let ((initial-input
10281 (cond
10282 (default-description)
10283 ((not org-make-link-description-function) desc)
10284 (t (condition-case nil
10285 (funcall org-make-link-description-function link desc)
10286 (error
10287 (message "Can't get link description from `%s'"
10288 (symbol-name org-make-link-description-function))
10289 (sit-for 2)
10290 nil))))))
10291 (setq desc (read-string "Description: " initial-input))))
10293 (unless (string-match "\\S-" desc) (setq desc nil))
10294 (when remove (apply 'delete-region remove))
10295 (insert (org-make-link-string link desc))
10296 ;; Redisplay so as the new link has proper invisible characters.
10297 (sit-for 0)))
10299 (defun org-link-try-special-completion (type)
10300 "If there is completion support for link type TYPE, offer it."
10301 (let ((fun (org-link-get-parameter type :complete)))
10302 (if (functionp fun)
10303 (funcall fun)
10304 (read-string "Link (no completion support): " (concat type ":")))))
10306 (defun org-file-complete-link (&optional arg)
10307 "Create a file link using completion."
10308 (let ((file (read-file-name "File: "))
10309 (pwd (file-name-as-directory (expand-file-name ".")))
10310 (pwd1 (file-name-as-directory (abbreviate-file-name
10311 (expand-file-name ".")))))
10312 (cond ((equal arg '(16))
10313 (concat "file:"
10314 (abbreviate-file-name (expand-file-name file))))
10315 ((string-match
10316 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10317 (concat "file:" (match-string 1 file)))
10318 ((string-match
10319 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10320 (expand-file-name file))
10321 (concat "file:"
10322 (match-string 1 (expand-file-name file))))
10323 (t (concat "file:" file)))))
10326 ;;; Opening/following a link
10328 (defvar org-link-search-failed nil)
10330 (defvar org-open-link-functions nil
10331 "Hook for functions finding a plain text link.
10332 These functions must take a single argument, the link content.
10333 They will be called for links that look like [[link text][description]]
10334 when LINK TEXT does not have a protocol like \"http:\" and does not look
10335 like a filename (e.g. \"./blue.png\").
10337 These functions will be called *before* Org attempts to resolve the
10338 link by doing text searches in the current buffer - so if you want a
10339 link \"[[target]]\" to still find \"<<target>>\", your function should
10340 handle this as a special case.
10342 When the function does handle the link, it must return a non-nil value.
10343 If it decides that it is not responsible for this link, it must return
10344 nil to indicate that that Org can continue with other options like
10345 exact and fuzzy text search.")
10347 (defun org-next-link (&optional search-backward)
10348 "Move forward to the next link.
10349 If the link is in hidden text, expose it."
10350 (interactive "P")
10351 (when (and org-link-search-failed (eq this-command last-command))
10352 (goto-char (point-min))
10353 (message "Link search wrapped back to beginning of buffer"))
10354 (setq org-link-search-failed nil)
10355 (let* ((pos (point))
10356 (ct (org-context))
10357 (a (assq :link ct))
10358 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10359 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10360 ((looking-at org-any-link-re)
10361 ;; Don't stay stuck at link without an org-link face
10362 (forward-char (if search-backward -1 1))))
10363 (if (funcall srch-fun org-any-link-re nil t)
10364 (progn
10365 (goto-char (match-beginning 0))
10366 (when (org-invisible-p) (org-show-context)))
10367 (goto-char pos)
10368 (setq org-link-search-failed t)
10369 (message "No further link found"))))
10371 (defun org-previous-link ()
10372 "Move backward to the previous link.
10373 If the link is in hidden text, expose it."
10374 (interactive)
10375 (funcall 'org-next-link t))
10377 (defun org-translate-link (s)
10378 "Translate a link string if a translation function has been defined."
10379 (with-temp-buffer
10380 (insert (org-trim s))
10381 (org-trim (org-element-interpret-data (org-element-context)))))
10383 (defun org-translate-link-from-planner (type path)
10384 "Translate a link from Emacs Planner syntax so that Org can follow it.
10385 This is still an experimental function, your mileage may vary."
10386 (cond
10387 ((member type '("http" "https" "news" "ftp"))
10388 ;; standard Internet links are the same.
10389 nil)
10390 ((and (equal type "irc") (string-match "^//" path))
10391 ;; Planner has two / at the beginning of an irc link, we have 1.
10392 ;; We should have zero, actually....
10393 (setq path (substring path 1)))
10394 ((and (equal type "lisp") (string-match "^/" path))
10395 ;; Planner has a slash, we do not.
10396 (setq type "elisp" path (substring path 1)))
10397 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10398 ;; A typical message link. Planner has the id after the final slash,
10399 ;; we separate it with a hash mark
10400 (setq path (concat (match-string 1 path) "#"
10401 (org-unbracket-string "<" ">" (match-string 2 path))))))
10402 (cons type path))
10404 (defun org-find-file-at-mouse (ev)
10405 "Open file link or URL at mouse."
10406 (interactive "e")
10407 (mouse-set-point ev)
10408 (org-open-at-point 'in-emacs))
10410 (defun org-open-at-mouse (ev)
10411 "Open file link or URL at mouse.
10412 See the docstring of `org-open-file' for details."
10413 (interactive "e")
10414 (mouse-set-point ev)
10415 (when (eq major-mode 'org-agenda-mode)
10416 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10417 (org-open-at-point))
10419 (defvar org-window-config-before-follow-link nil
10420 "The window configuration before following a link.
10421 This is saved in case the need arises to restore it.")
10423 ;;;###autoload
10424 (defun org-open-at-point-global ()
10425 "Follow a link or time-stamp like Org mode does.
10426 This command can be called in any mode to follow an external link
10427 or a time-stamp that has Org mode syntax. Its behavior is
10428 undefined when called on internal links (e.g., fuzzy links).
10429 Raise an error when there is nothing to follow. "
10430 (interactive)
10431 (cond ((org-in-regexp org-any-link-re)
10432 (org-open-link-from-string (match-string-no-properties 0)))
10433 ((or (org-in-regexp org-ts-regexp-both nil t)
10434 (org-in-regexp org-tsr-regexp-both nil t))
10435 (org-follow-timestamp-link))
10436 (t (user-error "No link found"))))
10438 ;;;###autoload
10439 (defun org-open-link-from-string (s &optional arg reference-buffer)
10440 "Open a link in the string S, as if it was in Org mode."
10441 (interactive "sLink: \nP")
10442 (let ((reference-buffer (or reference-buffer (current-buffer))))
10443 (with-temp-buffer
10444 (let ((org-inhibit-startup (not reference-buffer)))
10445 (org-mode)
10446 (insert s)
10447 (goto-char (point-min))
10448 (when reference-buffer
10449 (setq org-link-abbrev-alist-local
10450 (with-current-buffer reference-buffer
10451 org-link-abbrev-alist-local)))
10452 (org-open-at-point arg reference-buffer)))))
10454 (defvar org-open-at-point-functions nil
10455 "Hook that is run when following a link at point.
10457 Functions in this hook must return t if they identify and follow
10458 a link at point. If they don't find anything interesting at point,
10459 they must return nil.")
10461 (defvar org-link-search-inhibit-query nil)
10462 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10463 (defun org--open-doi-link (path)
10464 "Open a \"doi\" type link.
10465 PATH is a the path to search for, as a string."
10466 (browse-url (url-encode-url (concat org-doi-server-url path))))
10468 (defun org--open-elisp-link (path)
10469 "Open a \"elisp\" type link.
10470 PATH is the sexp to evaluate, as a string."
10471 (let ((cmd path))
10472 (if (or (and (org-string-nw-p
10473 org-confirm-elisp-link-not-regexp)
10474 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10475 (not org-confirm-elisp-link-function)
10476 (funcall org-confirm-elisp-link-function
10477 (format "Execute \"%s\" as elisp? "
10478 (org-add-props cmd nil 'face 'org-warning))))
10479 (message "%s => %s" cmd
10480 (if (eq (string-to-char cmd) ?\()
10481 (eval (read cmd))
10482 (call-interactively (read cmd))))
10483 (user-error "Abort"))))
10485 (defun org--open-help-link (path)
10486 "Open a \"help\" type link.
10487 PATH is a symbol name, as a string."
10488 (pcase (intern path)
10489 ((and (pred fboundp) variable) (describe-function variable))
10490 ((and (pred boundp) function) (describe-variable function))
10491 (name (user-error "Unknown function or variable: %s" name))))
10493 (defun org--open-shell-link (path)
10494 "Open a \"shell\" type link.
10495 PATH is the command to execute, as a string."
10496 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10497 (cmd path))
10498 (if (or (and (org-string-nw-p
10499 org-confirm-shell-link-not-regexp)
10500 (string-match
10501 org-confirm-shell-link-not-regexp cmd))
10502 (not org-confirm-shell-link-function)
10503 (funcall org-confirm-shell-link-function
10504 (format "Execute \"%s\" in shell? "
10505 (org-add-props cmd nil
10506 'face 'org-warning))))
10507 (progn
10508 (message "Executing %s" cmd)
10509 (shell-command cmd buf)
10510 (when (featurep 'midnight)
10511 (setq clean-buffer-list-kill-buffer-names
10512 (cons (buffer-name buf)
10513 clean-buffer-list-kill-buffer-names))))
10514 (user-error "Abort"))))
10516 (defun org-open-at-point (&optional arg reference-buffer)
10517 "Open link, timestamp, footnote or tags at point.
10519 When point is on a link, follow it. Normally, files will be
10520 opened by an appropriate application. If the optional prefix
10521 argument ARG is non-nil, Emacs will visit the file. With
10522 a double prefix argument, try to open outside of Emacs, in the
10523 application the system uses for this file type.
10525 When point is on a timestamp, open the agenda at the day
10526 specified.
10528 When point is a footnote definition, move to the first reference
10529 found. If it is on a reference, move to the associated
10530 definition.
10532 When point is on a headline, display a list of every link in the
10533 entry, so it is possible to pick one, or all, of them. If point
10534 is on a tag, call `org-tags-view' instead.
10536 When optional argument REFERENCE-BUFFER is non-nil, it should
10537 specify a buffer from where the link search should happen. This
10538 is used internally by `org-open-link-from-string'.
10540 On top of syntactically correct links, this function will also
10541 try to open links and time-stamps in comments, example
10542 blocks... i.e., whenever point is on something looking like
10543 a timestamp or a link."
10544 (interactive "P")
10545 ;; On a code block, open block's results.
10546 (unless (call-interactively 'org-babel-open-src-block-result)
10547 (org-load-modules-maybe)
10548 (setq org-window-config-before-follow-link (current-window-configuration))
10549 (org-remove-occur-highlights nil nil t)
10550 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10551 (let* ((context
10552 ;; Only consider supported types, even if they are not
10553 ;; the closest one.
10554 (org-element-lineage
10555 (org-element-context)
10556 '(clock footnote-definition footnote-reference headline
10557 inlinetask link timestamp)
10559 (type (org-element-type context))
10560 (value (org-element-property :value context)))
10561 (cond
10562 ;; On a headline or an inlinetask, but not on a timestamp,
10563 ;; a link, a footnote reference.
10564 ((memq type '(headline inlinetask))
10565 (org-match-line org-complex-heading-regexp)
10566 (if (and (match-beginning 5)
10567 (>= (point) (match-beginning 5))
10568 (< (point) (match-end 5)))
10569 ;; On tags.
10570 (org-tags-view arg (substring (match-string 5) 0 -1))
10571 ;; Not on tags.
10572 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10573 (`(nil . ,_)
10574 (require 'org-attach)
10575 (org-attach-reveal 'if-exists))
10576 (`(,links . ,links-end)
10577 (dolist (link (if (stringp links) (list links) links))
10578 (search-forward link nil links-end)
10579 (goto-char (match-beginning 0))
10580 (org-open-at-point))))))
10581 ;; On a footnote reference or at definition's label.
10582 ((or (eq type 'footnote-reference)
10583 (and (eq type 'footnote-definition)
10584 (save-excursion
10585 ;; Do not validate action when point is on the
10586 ;; spaces right after the footnote label, in
10587 ;; order to be on par with behaviour on links.
10588 (skip-chars-forward " \t")
10589 (let ((begin
10590 (org-element-property :contents-begin context)))
10591 (if begin (< (point) begin)
10592 (= (org-element-property :post-affiliated context)
10593 (line-beginning-position)))))))
10594 (org-footnote-action))
10595 ;; No valid context. Ignore catch-all types like `headline'.
10596 ;; If point is on something looking like a link or
10597 ;; a time-stamp, try opening it. It may be useful in
10598 ;; comments, example blocks...
10599 ((memq type '(footnote-definition headline inlinetask nil))
10600 (call-interactively #'org-open-at-point-global))
10601 ;; On a clock line, make sure point is on the timestamp
10602 ;; before opening it.
10603 ((and (eq type 'clock)
10604 value
10605 (>= (point) (org-element-property :begin value))
10606 (<= (point) (org-element-property :end value)))
10607 (org-follow-timestamp-link))
10608 ;; Do nothing on white spaces after an object.
10609 ((>= (point)
10610 (save-excursion
10611 (goto-char (org-element-property :end context))
10612 (skip-chars-backward " \t")
10613 (point)))
10614 (user-error "No link found"))
10615 ((eq type 'timestamp) (org-follow-timestamp-link))
10616 ((eq type 'link)
10617 (let ((type (org-element-property :type context))
10618 (path (org-link-unescape (org-element-property :path context))))
10619 ;; Switch back to REFERENCE-BUFFER needed when called in
10620 ;; a temporary buffer through `org-open-link-from-string'.
10621 (with-current-buffer (or reference-buffer (current-buffer))
10622 (cond
10623 ((equal type "file")
10624 (if (string-match "[*?{]" (file-name-nondirectory path))
10625 (dired path)
10626 ;; Look into `org-link-parameters' in order to find
10627 ;; a DEDICATED-FUNCTION to open file. The function
10628 ;; will be applied on raw link instead of parsed
10629 ;; link due to the limitation in `org-add-link-type'
10630 ;; ("open" function called with a single argument).
10631 ;; If no such function is found, fallback to
10632 ;; `org-open-file'.
10633 (let* ((option (org-element-property :search-option context))
10634 (app (org-element-property :application context))
10635 (dedicated-function
10636 (org-link-get-parameter
10637 (if app (concat type "+" app) type)
10638 :follow)))
10639 (if dedicated-function
10640 (funcall dedicated-function
10641 (concat path
10642 (and option (concat "::" option))))
10643 (apply #'org-open-file
10644 path
10645 (cond (arg)
10646 ((equal app "emacs") 'emacs)
10647 ((equal app "sys") 'system))
10648 (cond ((not option) nil)
10649 ((string-match-p "\\`[0-9]+\\'" option)
10650 (list (string-to-number option)))
10651 (t (list nil
10652 (org-link-unescape option)))))))))
10653 ((functionp (org-link-get-parameter type :follow))
10654 (funcall (org-link-get-parameter type :follow) path))
10655 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10656 (unless (run-hook-with-args-until-success
10657 'org-open-link-functions path)
10658 (if (not arg) (org-mark-ring-push)
10659 (switch-to-buffer-other-window
10660 (org-get-buffer-for-internal-link (current-buffer))))
10661 (let ((destination
10662 (org-with-wide-buffer
10663 (if (equal type "radio")
10664 (org-search-radio-target
10665 (org-element-property :path context))
10666 (org-link-search
10667 (if (member type '("custom-id" "coderef"))
10668 (org-element-property :raw-link context)
10669 path)
10670 ;; Prevent fuzzy links from matching
10671 ;; themselves.
10672 (and (equal type "fuzzy")
10673 (+ 2 (org-element-property :begin context)))))
10674 (point))))
10675 (unless (and (<= (point-min) destination)
10676 (>= (point-max) destination))
10677 (widen))
10678 (goto-char destination))))
10679 (t (browse-url-at-point))))))
10680 (t (user-error "No link found")))))
10681 (run-hook-with-args 'org-follow-link-hook)))
10683 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10684 "Offer links in the current entry and return the selected link.
10685 If there is only one link, return it.
10686 If NTH is an integer, return the NTH link found.
10687 If ZERO is a string, check also this string for a link, and if
10688 there is one, return it."
10689 (with-current-buffer buffer
10690 (org-with-wide-buffer
10691 (goto-char marker)
10692 (let ((cnt ?0)
10693 have-zero end links link c)
10694 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10695 (push (match-string 0 zero) links)
10696 (setq cnt (1- cnt) have-zero t))
10697 (save-excursion
10698 (org-back-to-heading t)
10699 (setq end (save-excursion (outline-next-heading) (point)))
10700 (while (re-search-forward org-any-link-re end t)
10701 (push (match-string 0) links))
10702 (setq links (org-uniquify (reverse links))))
10703 (cond
10704 ((null links)
10705 (message "No links"))
10706 ((equal (length links) 1)
10707 (setq link (car links)))
10708 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10709 (setq link (nth (if have-zero nth (1- nth)) links)))
10710 (t ; we have to select a link
10711 (save-excursion
10712 (save-window-excursion
10713 (delete-other-windows)
10714 (with-output-to-temp-buffer "*Select Link*"
10715 (dolist (l links)
10716 (cond
10717 ((not (string-match org-bracket-link-regexp l))
10718 (princ (format "[%c] %s\n" (cl-incf cnt)
10719 (org-unbracket-string "<" ">" l))))
10720 ((match-end 3)
10721 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10722 (match-string 3 l) (match-string 1 l))))
10723 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10724 (match-string 1 l)))))))
10725 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10726 (message "Select link to open, RET to open all:")
10727 (setq c (read-char-exclusive))
10728 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10729 (when (equal c ?q) (user-error "Abort"))
10730 (if (equal c ?\C-m)
10731 (setq link links)
10732 (setq nth (- c ?0))
10733 (when have-zero (setq nth (1+ nth)))
10734 (unless (and (integerp nth) (>= (length links) nth))
10735 (user-error "Invalid link selection"))
10736 (setq link (nth (1- nth) links)))))
10737 (cons link end)))))
10739 ;; TODO: These functions are deprecated since `org-open-at-point'
10740 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10741 (defun org-open-file-with-system (path)
10742 "Open file at PATH using the system way of opening it."
10743 (org-open-file path 'system))
10744 (defun org-open-file-with-emacs (path)
10745 "Open file at PATH in Emacs."
10746 (org-open-file path 'emacs))
10749 ;;; File search
10751 (defvar org-create-file-search-functions nil
10752 "List of functions to construct the right search string for a file link.
10753 These functions are called in turn with point at the location to
10754 which the link should point.
10756 A function in the hook should first test if it would like to
10757 handle this file type, for example by checking the `major-mode'
10758 or the file extension. If it decides not to handle this file, it
10759 should just return nil to give other functions a chance. If it
10760 does handle the file, it must return the search string to be used
10761 when following the link. The search string will be part of the
10762 file link, given after a double colon, and `org-open-at-point'
10763 will automatically search for it. If special measures must be
10764 taken to make the search successful, another function should be
10765 added to the companion hook `org-execute-file-search-functions',
10766 which see.
10768 A function in this hook may also use `setq' to set the variable
10769 `description' to provide a suggestion for the descriptive text to
10770 be used for this link when it gets inserted into an Org buffer
10771 with \\[org-insert-link].")
10773 (defvar org-execute-file-search-functions nil
10774 "List of functions to execute a file search triggered by a link.
10776 Functions added to this hook must accept a single argument, the
10777 search string that was part of the file link, the part after the
10778 double colon. The function must first check if it would like to
10779 handle this search, for example by checking the `major-mode' or
10780 the file extension. If it decides not to handle this search, it
10781 should just return nil to give other functions a chance. If it
10782 does handle the search, it must return a non-nil value to keep
10783 other functions from trying.
10785 Each function can access the current prefix argument through the
10786 variable `current-prefix-arg'. Note that a single prefix is used
10787 to force opening a link in Emacs, so it may be good to only use a
10788 numeric or double prefix to guide the search function.
10790 In case this is needed, a function in this hook can also restore
10791 the window configuration before `org-open-at-point' was called using:
10793 (set-window-configuration org-window-config-before-follow-link)")
10795 (defun org-search-radio-target (target)
10796 "Search a radio target matching TARGET in current buffer.
10797 White spaces are not significant."
10798 (let ((re (format "<<<%s>>>"
10799 (mapconcat #'regexp-quote
10800 (split-string target)
10801 "[ \t]+\\(?:\n[ \t]*\\)?")))
10802 (origin (point)))
10803 (goto-char (point-min))
10804 (catch :radio-match
10805 (while (re-search-forward re nil t)
10806 (backward-char)
10807 (let ((object (org-element-context)))
10808 (when (eq (org-element-type object) 'radio-target)
10809 (goto-char (org-element-property :begin object))
10810 (org-show-context 'link-search)
10811 (throw :radio-match nil))))
10812 (goto-char origin)
10813 (user-error "No match for radio target: %s" target))))
10815 (defun org-link-search (s &optional avoid-pos stealth)
10816 "Search for a search string S.
10818 If S starts with \"#\", it triggers a custom ID search.
10820 If S is enclosed within parenthesis, it initiates a coderef
10821 search.
10823 If S is surrounded by forward slashes, it is interpreted as
10824 a regular expression. In Org mode files, this will create an
10825 `org-occur' sparse tree. In ordinary files, `occur' will be used
10826 to list matches. If the current buffer is in `dired-mode', grep
10827 will be used to search in all files.
10829 When AVOID-POS is given, ignore matches near that position.
10831 When optional argument STEALTH is non-nil, do not modify
10832 visibility around point, thus ignoring `org-show-context-detail'
10833 variable.
10835 Search is case-insensitive and ignores white spaces. Return type
10836 of matched result, which is either `dedicated' or `fuzzy'."
10837 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10838 (let* ((case-fold-search t)
10839 (origin (point))
10840 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10841 (starred (eq (string-to-char normalized) ?*))
10842 (words (split-string (if starred (substring s 1) s)))
10843 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10844 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10845 type)
10846 (cond
10847 ;; Check if there are any special search functions.
10848 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10849 ((eq (string-to-char s) ?#)
10850 ;; Look for a custom ID S if S starts with "#".
10851 (let* ((id (substring normalized 1))
10852 (match (org-find-property "CUSTOM_ID" id)))
10853 (if match (progn (goto-char match) (setf type 'dedicated))
10854 (error "No match for custom ID: %s" id))))
10855 ((string-match "\\`(\\(.*\\))\\'" normalized)
10856 ;; Look for coderef targets if S is enclosed within parenthesis.
10857 (let ((coderef (match-string-no-properties 1 normalized))
10858 (re (substring s-single-re 1 -1)))
10859 (goto-char (point-min))
10860 (catch :coderef-match
10861 (while (re-search-forward re nil t)
10862 (let ((element (org-element-at-point)))
10863 (when (and (memq (org-element-type element)
10864 '(example-block src-block))
10865 ;; Build proper regexp according to current
10866 ;; block's label format.
10867 (let ((label-fmt
10868 (regexp-quote
10869 (or (org-element-property :label-fmt element)
10870 org-coderef-label-format))))
10871 (save-excursion
10872 (beginning-of-line)
10873 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10874 (format label-fmt coderef))))))
10875 (setq type 'dedicated)
10876 (goto-char (match-beginning 1))
10877 (throw :coderef-match nil))))
10878 (goto-char origin)
10879 (error "No match for coderef: %s" coderef))))
10880 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10881 ;; Look for a regular expression.
10882 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10883 (match-string 1 s)))
10884 ;; From here, we handle fuzzy links.
10886 ;; Look for targets, only if not in a headline search.
10887 ((and (not starred)
10888 (let ((target (format "<<%s>>" s-multi-re)))
10889 (catch :target-match
10890 (goto-char (point-min))
10891 (while (re-search-forward target nil t)
10892 (backward-char)
10893 (let ((context (org-element-context)))
10894 (when (eq (org-element-type context) 'target)
10895 (setq type 'dedicated)
10896 (goto-char (org-element-property :begin context))
10897 (throw :target-match t))))
10898 nil))))
10899 ;; Look for elements named after S, only if not in a headline
10900 ;; search.
10901 ((and (not starred)
10902 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10903 (catch :name-match
10904 (goto-char (point-min))
10905 (while (re-search-forward name nil t)
10906 (let ((element (org-element-at-point)))
10907 (when (equal words
10908 (split-string
10909 (org-element-property :name element)))
10910 (setq type 'dedicated)
10911 (beginning-of-line)
10912 (throw :name-match t))))
10913 nil))))
10914 ;; Regular text search. Prefer headlines in Org mode buffers.
10915 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10916 ;; statistics cookies and tags.
10917 ((and (derived-mode-p 'org-mode)
10918 (let ((title-re
10919 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10920 org-outline-regexp-bol
10921 org-comment-string
10922 (mapconcat #'regexp-quote words ".+")))
10923 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10924 (comment-re (eval-when-compile
10925 (format "\\`%s[ \t]+" org-comment-string))))
10926 (goto-char (point-min))
10927 (catch :found
10928 (while (re-search-forward title-re nil t)
10929 (when (equal words
10930 (split-string
10931 (replace-regexp-in-string
10932 cookie-re ""
10933 (replace-regexp-in-string
10934 comment-re "" (org-get-heading t t t)))))
10935 (throw :found t)))
10936 nil)))
10937 (beginning-of-line)
10938 (setq type 'dedicated))
10939 ;; Offer to create non-existent headline depending on
10940 ;; `org-link-search-must-match-exact-headline'.
10941 ((and (derived-mode-p 'org-mode)
10942 (not org-link-search-inhibit-query)
10943 (eq org-link-search-must-match-exact-headline 'query-to-create)
10944 (yes-or-no-p "No match - create this as a new heading? "))
10945 (goto-char (point-max))
10946 (unless (bolp) (newline))
10947 (org-insert-heading nil t t)
10948 (insert s "\n")
10949 (beginning-of-line 0))
10950 ;; Only headlines are looked after. No need to process
10951 ;; further: throw an error.
10952 ((and (derived-mode-p 'org-mode)
10953 (or starred org-link-search-must-match-exact-headline))
10954 (goto-char origin)
10955 (error "No match for fuzzy expression: %s" normalized))
10956 ;; Regular text search.
10957 ((catch :fuzzy-match
10958 (goto-char (point-min))
10959 (while (re-search-forward s-multi-re nil t)
10960 ;; Skip match if it contains AVOID-POS or it is included in
10961 ;; a link with a description but outside the description.
10962 (unless (or (and avoid-pos
10963 (<= (match-beginning 0) avoid-pos)
10964 (> (match-end 0) avoid-pos))
10965 (and (save-match-data
10966 (org-in-regexp org-bracket-link-regexp))
10967 (match-beginning 3)
10968 (or (> (match-beginning 3) (point))
10969 (<= (match-end 3) (point)))
10970 (org-element-lineage
10971 (save-match-data (org-element-context))
10972 '(link) t)))
10973 (goto-char (match-beginning 0))
10974 (setq type 'fuzzy)
10975 (throw :fuzzy-match t)))
10976 nil))
10977 ;; All failed. Throw an error.
10978 (t (goto-char origin)
10979 (error "No match for fuzzy expression: %s" normalized)))
10980 ;; Disclose surroundings of match, if appropriate.
10981 (when (and (derived-mode-p 'org-mode) (not stealth))
10982 (org-show-context 'link-search))
10983 type))
10985 (defun org-get-buffer-for-internal-link (buffer)
10986 "Return a buffer to be used for displaying the link target of internal links."
10987 (cond
10988 ((not org-display-internal-link-with-indirect-buffer)
10989 buffer)
10990 ((string-suffix-p "(Clone)" (buffer-name buffer))
10991 (message "Buffer is already a clone, not making another one")
10992 ;; we also do not modify visibility in this case
10993 buffer)
10994 (t ; make a new indirect buffer for displaying the link
10995 (let* ((bn (buffer-name buffer))
10996 (ibn (concat bn "(Clone)"))
10997 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10998 (with-current-buffer ib (org-overview))
10999 ib))))
11001 (defun org-do-occur (regexp &optional cleanup)
11002 "Call the Emacs command `occur'.
11003 If CLEANUP is non-nil, remove the printout of the regular expression
11004 in the *Occur* buffer. This is useful if the regex is long and not useful
11005 to read."
11006 (occur regexp)
11007 (when cleanup
11008 (let ((cwin (selected-window)) win beg end)
11009 (when (setq win (get-buffer-window "*Occur*"))
11010 (select-window win))
11011 (goto-char (point-min))
11012 (when (re-search-forward "match[a-z]+" nil t)
11013 (setq beg (match-end 0))
11014 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11015 (setq end (1- (match-beginning 0)))))
11016 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11017 (goto-char (point-min))
11018 (select-window cwin))))
11020 ;;; The mark ring for links jumps
11022 (defvar org-mark-ring nil
11023 "Mark ring for positions before jumps in Org mode.")
11024 (defvar org-mark-ring-last-goto nil
11025 "Last position in the mark ring used to go back.")
11026 ;; Fill and close the ring
11027 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11028 (dotimes (_ org-mark-ring-length)
11029 (push (make-marker) org-mark-ring))
11030 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11031 org-mark-ring)
11033 (defun org-mark-ring-push (&optional pos buffer)
11034 "Put the current position or POS into the mark ring and rotate it."
11035 (interactive)
11036 (setq pos (or pos (point)))
11037 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11038 (move-marker (car org-mark-ring)
11039 (or pos (point))
11040 (or buffer (current-buffer)))
11041 (message "%s"
11042 (substitute-command-keys
11043 "Position saved to mark ring, go back with \
11044 `\\[org-mark-ring-goto]'.")))
11046 (defun org-mark-ring-goto (&optional n)
11047 "Jump to the previous position in the mark ring.
11048 With prefix arg N, jump back that many stored positions. When
11049 called several times in succession, walk through the entire ring.
11050 Org mode commands jumping to a different position in the current file,
11051 or to another Org file, automatically push the old position onto the ring."
11052 (interactive "p")
11053 (let (p m)
11054 (if (eq last-command this-command)
11055 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11056 (setq p org-mark-ring))
11057 (setq org-mark-ring-last-goto p)
11058 (setq m (car p))
11059 (pop-to-buffer-same-window (marker-buffer m))
11060 (goto-char m)
11061 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11063 (defun org-add-angle-brackets (s)
11064 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11065 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11068 ;;; Following specific links
11070 (defvar org-agenda-buffer-tmp-name)
11071 (defvar org-agenda-start-on-weekday)
11072 (defun org-follow-timestamp-link ()
11073 "Open an agenda view for the time-stamp date/range at point."
11074 (cond
11075 ((org-at-date-range-p t)
11076 (let ((org-agenda-start-on-weekday)
11077 (t1 (match-string 1))
11078 (t2 (match-string 2)) tt1 tt2)
11079 (setq tt1 (time-to-days (org-time-string-to-time t1))
11080 tt2 (time-to-days (org-time-string-to-time t2)))
11081 (let ((org-agenda-buffer-tmp-name
11082 (format "*Org Agenda(a:%s)"
11083 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11084 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11085 ((org-at-timestamp-p 'lax)
11086 (let ((org-agenda-buffer-tmp-name
11087 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11088 (org-agenda-list nil (time-to-days (org-time-string-to-time
11089 (substring (match-string 1) 0 10)))
11090 1)))
11091 (t (error "This should not happen"))))
11094 ;;; Following file links
11095 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11096 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11097 (declare-function mailcap-mime-info
11098 "mailcap" (string &optional request no-decode))
11099 (defvar org-wait nil)
11100 (defun org-open-file (path &optional in-emacs line search)
11101 "Open the file at PATH.
11102 First, this expands any special file name abbreviations. Then the
11103 configuration variable `org-file-apps' is checked if it contains an
11104 entry for this file type, and if yes, the corresponding command is launched.
11106 If no application is found, Emacs simply visits the file.
11108 With optional prefix argument IN-EMACS, Emacs will visit the file.
11109 With a double \\[universal-argument] \\[universal-argument] \
11110 prefix arg, Org tries to avoid opening in Emacs
11111 and to use an external application to visit the file.
11113 Optional LINE specifies a line to go to, optional SEARCH a string
11114 to search for. If LINE or SEARCH is given, the file will be
11115 opened in Emacs, unless an entry from org-file-apps that makes
11116 use of groups in a regexp matches.
11118 If you want to change the way frames are used when following a
11119 link, please customize `org-link-frame-setup'.
11121 If the file does not exist, an error is thrown."
11122 (let* ((file (if (equal path "")
11123 buffer-file-name
11124 (substitute-in-file-name (expand-file-name path))))
11125 (file-apps (append org-file-apps (org-default-apps)))
11126 (apps (cl-remove-if
11127 'org-file-apps-entry-match-against-dlink-p file-apps))
11128 (apps-dlink (cl-remove-if-not
11129 'org-file-apps-entry-match-against-dlink-p file-apps))
11130 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11131 (dirp (unless remp (file-directory-p file)))
11132 (file (if (and dirp org-open-directory-means-index-dot-org)
11133 (concat (file-name-as-directory file) "index.org")
11134 file))
11135 (a-m-a-p (assq 'auto-mode apps))
11136 (dfile (downcase file))
11137 ;; Reconstruct the original link from the PATH, LINE and
11138 ;; SEARCH args.
11139 (link (cond (line (concat file "::" (number-to-string line)))
11140 (search (concat file "::" search))
11141 (t file)))
11142 (dlink (downcase link))
11143 (ext
11144 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11145 (match-string 1 dfile)))
11146 (save-position-maybe
11147 (let ((old-buffer (current-buffer))
11148 (old-pos (point))
11149 (old-mode major-mode))
11150 (lambda ()
11151 (and (derived-mode-p 'org-mode)
11152 (eq old-mode 'org-mode)
11153 (or (not (eq old-buffer (current-buffer)))
11154 (not (eq old-pos (point))))
11155 (org-mark-ring-push old-pos old-buffer)))))
11156 cmd link-match-data)
11157 (cond
11158 ((member in-emacs '((16) system))
11159 (setq cmd (cdr (assq 'system apps))))
11160 (in-emacs (setq cmd 'emacs))
11162 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11163 (and dirp (cdr (assq 'directory apps)))
11164 ;; First, try matching against apps-dlink if we
11165 ;; get a match here, store the match data for
11166 ;; later.
11167 (let ((match (assoc-default dlink apps-dlink
11168 'string-match)))
11169 (if match
11170 (progn (setq link-match-data (match-data))
11171 match)
11172 (progn (setq in-emacs (or in-emacs line search))
11173 nil))) ; if we have no match in apps-dlink,
11174 ; always open the file in emacs if line or search
11175 ; is given (for backwards compatibility)
11176 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11177 'string-match)
11178 (cdr (assoc ext apps))
11179 (cdr (assq t apps))))))
11180 (when (eq cmd 'system)
11181 (setq cmd (cdr (assq 'system apps))))
11182 (when (eq cmd 'default)
11183 (setq cmd (cdr (assoc t apps))))
11184 (when (eq cmd 'mailcap)
11185 (require 'mailcap)
11186 (mailcap-parse-mailcaps)
11187 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11188 (command (mailcap-mime-info mime-type)))
11189 (if (stringp command)
11190 (setq cmd command)
11191 (setq cmd 'emacs))))
11192 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11193 (not (file-exists-p file))
11194 (not org-open-non-existing-files))
11195 (user-error "No such file: %s" file))
11196 (cond
11197 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11198 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11199 (while (string-match "['\"]%s['\"]" cmd)
11200 (setq cmd (replace-match "%s" t t cmd)))
11201 (setq cmd (replace-regexp-in-string
11202 "%s"
11203 (shell-quote-argument (convert-standard-filename file))
11205 nil t))
11207 ;; Replace "%1", "%2" etc. in command with group matches from regex
11208 (save-match-data
11209 (let ((match-index 1)
11210 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11211 (set-match-data link-match-data)
11212 (while (<= match-index number-of-groups)
11213 (let ((regex (concat "%" (number-to-string match-index)))
11214 (replace-with (match-string match-index dlink)))
11215 (while (string-match regex cmd)
11216 (setq cmd (replace-match replace-with t t cmd))))
11217 (setq match-index (+ match-index 1)))))
11219 (save-window-excursion
11220 (message "Running %s...done" cmd)
11221 (start-process-shell-command cmd nil cmd)
11222 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11223 ((or (stringp cmd)
11224 (eq cmd 'emacs))
11225 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11226 (widen)
11227 (cond (line (org-goto-line line)
11228 (when (derived-mode-p 'org-mode) (org-reveal)))
11229 (search (condition-case err
11230 (org-link-search search)
11231 ;; Save position before error-ing out so user
11232 ;; can easily move back to the original buffer.
11233 (error (funcall save-position-maybe)
11234 (error (nth 1 err)))))))
11235 ((functionp cmd)
11236 (save-match-data
11237 (set-match-data link-match-data)
11238 (condition-case nil
11239 (funcall cmd file link)
11240 ;; FIXME: Remove this check when most default installations
11241 ;; of Emacs have at least Org 9.0.
11242 ((debug wrong-number-of-arguments wrong-type-argument
11243 invalid-function)
11244 (user-error "Please see Org News for version 9.0 about \
11245 `org-file-apps'--Lisp error: %S" cmd)))))
11246 ((consp cmd)
11247 ;; FIXME: Remove this check when most default installations of
11248 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11249 ;; fall back to `org-link-frame-setup' for an old usage of
11250 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11251 (user-error "Please see Org News for version 9.0 about \
11252 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11253 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11254 (funcall save-position-maybe)))
11256 (defun org-file-apps-entry-match-against-dlink-p (entry)
11257 "This function returns non-nil if `entry' uses a regular
11258 expression which should be matched against the whole link by
11259 org-open-file.
11261 It assumes that is the case when the entry uses a regular
11262 expression which has at least one grouping construct and the
11263 action is either a lisp form or a command string containing
11264 `%1', i.e. using at least one subexpression match as a
11265 parameter."
11266 (let ((selector (car entry))
11267 (action (cdr entry)))
11268 (if (stringp selector)
11269 (and (> (regexp-opt-depth selector) 0)
11270 (or (and (stringp action)
11271 (string-match "%[0-9]" action))
11272 (consp action)))
11273 nil)))
11275 (defun org-default-apps ()
11276 "Return the default applications for this operating system."
11277 (cond
11278 ((eq system-type 'darwin)
11279 org-file-apps-defaults-macosx)
11280 ((eq system-type 'windows-nt)
11281 org-file-apps-defaults-windowsnt)
11282 (t org-file-apps-defaults-gnu)))
11284 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11285 "Convert extensions to regular expressions in the cars of LIST.
11286 Also, weed out any non-string entries, because the return value is used
11287 only for regexp matching.
11288 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11289 point to the symbol `emacs', indicating that the file should
11290 be opened in Emacs."
11291 (append
11292 (delq nil
11293 (mapcar (lambda (x)
11294 (unless (not (stringp (car x)))
11295 (if (string-match "\\W" (car x))
11297 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11298 list))
11299 (when add-auto-mode
11300 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11302 (defvar ange-ftp-name-format)
11303 (defun org-file-remote-p (file)
11304 "Test whether FILE specifies a location on a remote system.
11305 Return non-nil if the location is indeed remote.
11307 For example, the filename \"/user@host:/foo\" specifies a location
11308 on the system \"/user@host:\"."
11309 (cond ((fboundp 'file-remote-p)
11310 (file-remote-p file))
11311 ((fboundp 'tramp-handle-file-remote-p)
11312 (tramp-handle-file-remote-p file))
11313 ((and (boundp 'ange-ftp-name-format)
11314 (string-match (car ange-ftp-name-format) file))
11315 t)))
11318 ;;;; Refiling
11320 (defun org-get-org-file ()
11321 "Read a filename, with default directory `org-directory'."
11322 (let ((default (or org-default-notes-file remember-data-file)))
11323 (read-file-name (format "File name [%s]: " default)
11324 (file-name-as-directory org-directory)
11325 default)))
11327 (defun org-notes-order-reversed-p ()
11328 "Check if the current file should receive notes in reversed order."
11329 (cond
11330 ((not org-reverse-note-order) nil)
11331 ((eq t org-reverse-note-order) t)
11332 ((not (listp org-reverse-note-order)) nil)
11333 (t (catch 'exit
11334 (dolist (entry org-reverse-note-order)
11335 (when (string-match (car entry) buffer-file-name)
11336 (throw 'exit (cdr entry))))))))
11338 (defvar org-refile-target-table nil
11339 "The list of refile targets, created by `org-refile'.")
11341 (defvar org-agenda-new-buffers nil
11342 "Buffers created to visit agenda files.")
11344 (defvar org-refile-cache nil
11345 "Cache for refile targets.")
11347 (defvar org-refile-markers nil
11348 "All the markers used for caching refile locations.")
11350 (defun org-refile-marker (pos)
11351 "Get a new refile marker, but only if caching is in use."
11352 (if (not org-refile-use-cache)
11354 (let ((m (make-marker)))
11355 (move-marker m pos)
11356 (push m org-refile-markers)
11357 m)))
11359 (defun org-refile-cache-clear ()
11360 "Clear the refile cache and disable all the markers."
11361 (dolist (m org-refile-markers) (move-marker m nil))
11362 (setq org-refile-markers nil)
11363 (setq org-refile-cache nil)
11364 (message "Refile cache has been cleared"))
11366 (defun org-refile-cache-check-set (set)
11367 "Check if all the markers in the cache still have live buffers."
11368 (let (marker)
11369 (catch 'exit
11370 (while (and set (setq marker (nth 3 (pop set))))
11371 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11372 (when (and marker (null (marker-buffer marker)))
11373 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11374 (sit-for 3)
11375 (throw 'exit nil)))
11376 t)))
11378 (defun org-refile-cache-put (set &rest identifiers)
11379 "Push the refile targets SET into the cache, under IDENTIFIERS."
11380 (let* ((key (sha1 (prin1-to-string identifiers)))
11381 (entry (assoc key org-refile-cache)))
11382 (if entry
11383 (setcdr entry set)
11384 (push (cons key set) org-refile-cache))))
11386 (defun org-refile-cache-get (&rest identifiers)
11387 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11388 (cond
11389 ((not org-refile-cache) nil)
11390 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11392 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11393 org-refile-cache))))
11394 (and set (org-refile-cache-check-set set) set)))))
11396 (defvar org-outline-path-cache nil
11397 "Alist between buffer positions and outline paths.
11398 It value is an alist (POSITION . PATH) where POSITION is the
11399 buffer position at the beginning of an entry and PATH is a list
11400 of strings describing the outline path for that entry, in reverse
11401 order.")
11403 (defun org-refile-get-targets (&optional default-buffer)
11404 "Produce a table with refile targets."
11405 (let ((case-fold-search nil)
11406 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11407 (entries (or org-refile-targets '((nil . (:level . 1)))))
11408 targets tgs files desc descre)
11409 (message "Getting targets...")
11410 (with-current-buffer (or default-buffer (current-buffer))
11411 (dolist (entry entries)
11412 (setq files (car entry) desc (cdr entry))
11413 (cond
11414 ((null files) (setq files (list (current-buffer))))
11415 ((eq files 'org-agenda-files)
11416 (setq files (org-agenda-files 'unrestricted)))
11417 ((and (symbolp files) (fboundp files))
11418 (setq files (funcall files)))
11419 ((and (symbolp files) (boundp files))
11420 (setq files (symbol-value files))))
11421 (when (stringp files) (setq files (list files)))
11422 (cond
11423 ((eq (car desc) :tag)
11424 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11425 ((eq (car desc) :todo)
11426 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11427 ((eq (car desc) :regexp)
11428 (setq descre (cdr desc)))
11429 ((eq (car desc) :level)
11430 (setq descre (concat "^\\*\\{" (number-to-string
11431 (if org-odd-levels-only
11432 (1- (* 2 (cdr desc)))
11433 (cdr desc)))
11434 "\\}[ \t]")))
11435 ((eq (car desc) :maxlevel)
11436 (setq descre (concat "^\\*\\{1," (number-to-string
11437 (if org-odd-levels-only
11438 (1- (* 2 (cdr desc)))
11439 (cdr desc)))
11440 "\\}[ \t]")))
11441 (t (error "Bad refiling target description %s" desc)))
11442 (dolist (f files)
11443 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11445 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11446 (progn
11447 (when (bufferp f)
11448 (setq f (buffer-file-name (buffer-base-buffer f))))
11449 (setq f (and f (expand-file-name f)))
11450 (when (eq org-refile-use-outline-path 'file)
11451 (push (list (file-name-nondirectory f) f nil nil) tgs))
11452 (when (eq org-refile-use-outline-path 'buffer-name)
11453 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11454 (when (eq org-refile-use-outline-path 'full-file-path)
11455 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11456 (org-with-wide-buffer
11457 (goto-char (point-min))
11458 (setq org-outline-path-cache nil)
11459 (while (re-search-forward descre nil t)
11460 (beginning-of-line)
11461 (let ((case-fold-search nil))
11462 (looking-at org-complex-heading-regexp))
11463 (let ((begin (point))
11464 (heading (match-string-no-properties 4)))
11465 (unless (or (and
11466 org-refile-target-verify-function
11467 (not
11468 (funcall org-refile-target-verify-function)))
11469 (not heading))
11470 (let ((re (format org-complex-heading-regexp-format
11471 (regexp-quote heading)))
11472 (target
11473 (if (not org-refile-use-outline-path) heading
11474 (mapconcat
11475 #'identity
11476 (append
11477 (pcase org-refile-use-outline-path
11478 (`file (list (file-name-nondirectory
11479 (buffer-file-name
11480 (buffer-base-buffer)))))
11481 (`full-file-path
11482 (list (buffer-file-name
11483 (buffer-base-buffer))))
11484 (`buffer-name
11485 (list (buffer-name
11486 (buffer-base-buffer))))
11487 (_ nil))
11488 (mapcar (lambda (s) (replace-regexp-in-string
11489 "/" "\\/" s nil t))
11490 (org-get-outline-path t t)))
11491 "/"))))
11492 (push (list target f re (org-refile-marker (point)))
11493 tgs)))
11494 (when (= (point) begin)
11495 ;; Verification function has not moved point.
11496 (end-of-line)))))))
11497 (when org-refile-use-cache
11498 (org-refile-cache-put tgs (buffer-file-name) descre))
11499 (setq targets (append tgs targets))))))
11500 (message "Getting targets...done")
11501 (delete-dups (nreverse targets))))
11503 (defun org--get-outline-path-1 (&optional use-cache)
11504 "Return outline path to current headline.
11506 Outline path is a list of strings, in reverse order. When
11507 optional argument USE-CACHE is non-nil, make use of a cache. See
11508 `org-get-outline-path' for details.
11510 Assume buffer is widened and point is on a headline."
11511 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11512 (let ((p (point))
11513 (heading (let ((case-fold-search nil))
11514 (looking-at org-complex-heading-regexp)
11515 (if (not (match-end 4)) ""
11516 ;; Remove statistics cookies.
11517 (org-trim
11518 (org-link-display-format
11519 (replace-regexp-in-string
11520 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11521 (match-string-no-properties 4))))))))
11522 (if (org-up-heading-safe)
11523 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11524 (when use-cache
11525 (push (cons p path) org-outline-path-cache))
11526 path)
11527 ;; This is a new root node. Since we assume we are moving
11528 ;; forward, we can drop previous cache so as to limit number
11529 ;; of associations there.
11530 (let ((path (list heading)))
11531 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11532 path)))))
11534 (defun org-get-outline-path (&optional with-self use-cache)
11535 "Return the outline path to the current entry.
11537 An outline path is a list of ancestors for current headline, as
11538 a list of strings. Statistics cookies are removed and links are
11539 replaced with their description, if any, or their path otherwise.
11541 When optional argument WITH-SELF is non-nil, the path also
11542 includes the current headline.
11544 When optional argument USE-CACHE is non-nil, cache outline paths
11545 between calls to this function so as to avoid backtracking. This
11546 argument is useful when planning to find more than one outline
11547 path in the same document. In that case, there are two
11548 conditions to satisfy:
11549 - `org-outline-path-cache' is set to nil before starting the
11550 process;
11551 - outline paths are computed by increasing buffer positions."
11552 (org-with-wide-buffer
11553 (and (or (and with-self (org-back-to-heading t))
11554 (org-up-heading-safe))
11555 (reverse (org--get-outline-path-1 use-cache)))))
11557 (defun org-format-outline-path (path &optional width prefix separator)
11558 "Format the outline path PATH for display.
11559 WIDTH is the maximum number of characters that is available.
11560 PREFIX is a prefix to be included in the returned string,
11561 such as the file name.
11562 SEPARATOR is inserted between the different parts of the path,
11563 the default is \"/\"."
11564 (setq width (or width 79))
11565 (setq path (delq nil path))
11566 (unless (> width 0)
11567 (user-error "Argument `width' must be positive"))
11568 (setq separator (or separator "/"))
11569 (let* ((org-odd-levels-only nil)
11570 (fpath (concat
11571 prefix (and prefix path separator)
11572 (mapconcat
11573 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11574 (cl-loop for head in path
11575 for n from 0
11576 collect (org-add-props
11577 head nil 'face
11578 (nth (% n org-n-level-faces) org-level-faces)))
11579 separator))))
11580 (when (> (length fpath) width)
11581 (if (< width 7)
11582 ;; It's unlikely that `width' will be this small, but don't
11583 ;; waste characters by adding ".." if it is.
11584 (setq fpath (substring fpath 0 width))
11585 (setf (substring fpath (- width 2)) "..")))
11586 fpath))
11588 (defun org-display-outline-path (&optional file current separator just-return-string)
11589 "Display the current outline path in the echo area.
11591 If FILE is non-nil, prepend the output with the file name.
11592 If CURRENT is non-nil, append the current heading to the output.
11593 SEPARATOR is passed through to `org-format-outline-path'. It separates
11594 the different parts of the path and defaults to \"/\".
11595 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11596 (interactive "P")
11597 (let* (case-fold-search
11598 (bfn (buffer-file-name (buffer-base-buffer)))
11599 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11600 res)
11601 (when current (setq path (append path
11602 (save-excursion
11603 (org-back-to-heading t)
11604 (when (looking-at org-complex-heading-regexp)
11605 (list (match-string 4)))))))
11606 (setq res
11607 (org-format-outline-path
11608 path
11609 (1- (frame-width))
11610 (and file bfn (concat (file-name-nondirectory bfn) separator))
11611 separator))
11612 (if just-return-string
11613 (org-no-properties res)
11614 (org-unlogged-message "%s" res))))
11616 (defvar org-refile-history nil
11617 "History for refiling operations.")
11619 (defvar org-after-refile-insert-hook nil
11620 "Hook run after `org-refile' has inserted its stuff at the new location.
11621 Note that this is still *before* the stuff will be removed from
11622 the *old* location.")
11624 (defvar org-capture-last-stored-marker)
11625 (defvar org-refile-keep nil
11626 "Non-nil means `org-refile' will copy instead of refile.")
11628 (defun org-copy ()
11629 "Like `org-refile', but copy."
11630 (interactive)
11631 (let ((org-refile-keep t))
11632 (funcall 'org-refile nil nil nil "Copy")))
11634 (defun org-refile (&optional arg default-buffer rfloc msg)
11635 "Move the entry or entries at point to another heading.
11637 The list of target headings is compiled using the information in
11638 `org-refile-targets', which see.
11640 At the target location, the entry is filed as a subitem of the
11641 target heading. Depending on `org-reverse-note-order', the new
11642 subitem will either be the first or the last subitem.
11644 If there is an active region, all entries in that region will be
11645 refiled. However, the region must fulfill the requirement that
11646 the first heading sets the top-level of the moved text.
11648 With a `\\[universal-argument]' ARG, the command will only visit the target \
11649 location
11650 and not actually move anything.
11652 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11653 location where the last
11654 refiling operation has put the subtree.
11656 With a numeric prefix argument of `2', refile to the running clock.
11658 With a numeric prefix argument of `3', emulate `org-refile-keep'
11659 being set to t and copy to the target location, don't move it.
11660 Beware that keeping refiled entries may result in duplicated ID
11661 properties.
11663 RFLOC can be a refile location obtained in a different way.
11665 MSG is a string to replace \"Refile\" in the default prompt with
11666 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11668 See also `org-refile-use-outline-path'.
11670 If you are using target caching (see `org-refile-use-cache'), you
11671 have to clear the target cache in order to find new targets.
11672 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11673 prefix argument (`C-u C-u C-u C-c C-w')."
11674 (interactive "P")
11675 (if (member arg '(0 (64)))
11676 (org-refile-cache-clear)
11677 (let* ((actionmsg (cond (msg msg)
11678 ((equal arg 3) "Refile (and keep)")
11679 (t "Refile")))
11680 (regionp (org-region-active-p))
11681 (region-start (and regionp (region-beginning)))
11682 (region-end (and regionp (region-end)))
11683 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11684 pos it nbuf file level reversed)
11685 (setq last-command nil)
11686 (when regionp
11687 (goto-char region-start)
11688 (or (bolp) (goto-char (point-at-bol)))
11689 (setq region-start (point))
11690 (unless (or (org-kill-is-subtree-p
11691 (buffer-substring region-start region-end))
11692 (prog1 org-refile-active-region-within-subtree
11693 (let ((s (point-at-eol)))
11694 (org-toggle-heading)
11695 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11696 (user-error "The region is not a (sequence of) subtree(s)")))
11697 (if (equal arg '(16))
11698 (org-refile-goto-last-stored)
11699 (when (or
11700 (and (equal arg 2)
11701 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11702 (prog1
11703 (setq it (list (or org-clock-heading "running clock")
11704 (buffer-file-name
11705 (marker-buffer org-clock-hd-marker))
11707 (marker-position org-clock-hd-marker)))
11708 (setq arg nil)))
11709 (setq it
11710 (or rfloc
11711 (let (heading-text)
11712 (save-excursion
11713 (unless (and arg (listp arg))
11714 (org-back-to-heading t)
11715 (setq heading-text
11716 (replace-regexp-in-string
11717 org-bracket-link-regexp
11718 "\\3"
11719 (or (nth 4 (org-heading-components))
11720 ""))))
11721 (org-refile-get-location
11722 (cond ((and arg (listp arg)) "Goto")
11723 (regionp (concat actionmsg " region to"))
11724 (t (concat actionmsg " subtree \""
11725 heading-text "\" to")))
11726 default-buffer
11727 (and (not (equal '(4) arg))
11728 org-refile-allow-creating-parent-nodes)))))))
11729 (setq file (nth 1 it)
11730 pos (nth 3 it))
11731 (when (and (not arg)
11733 (equal (buffer-file-name) file)
11734 (if regionp
11735 (and (>= pos region-start)
11736 (<= pos region-end))
11737 (and (>= pos (point))
11738 (< pos (save-excursion
11739 (org-end-of-subtree t t))))))
11740 (error "Cannot refile to position inside the tree or region"))
11741 (setq nbuf (or (find-buffer-visiting file)
11742 (find-file-noselect file)))
11743 (if (and arg (not (equal arg 3)))
11744 (progn
11745 (pop-to-buffer-same-window nbuf)
11746 (goto-char (cond (pos)
11747 ((org-notes-order-reversed-p) (point-min))
11748 (t (point-max))))
11749 (org-show-context 'org-goto))
11750 (if regionp
11751 (progn
11752 (org-kill-new (buffer-substring region-start region-end))
11753 (org-save-markers-in-region region-start region-end))
11754 (org-copy-subtree 1 nil t))
11755 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11756 (find-file-noselect file)))
11757 (setq reversed (org-notes-order-reversed-p))
11758 (org-with-wide-buffer
11759 (if pos
11760 (progn
11761 (goto-char pos)
11762 (setq level (org-get-valid-level (funcall outline-level) 1))
11763 (goto-char
11764 (if reversed
11765 (or (outline-next-heading) (point-max))
11766 (or (save-excursion (org-get-next-sibling))
11767 (org-end-of-subtree t t)
11768 (point-max)))))
11769 (setq level 1)
11770 (if (not reversed)
11771 (goto-char (point-max))
11772 (goto-char (point-min))
11773 (or (outline-next-heading) (goto-char (point-max)))))
11774 (unless (bolp) (newline))
11775 (org-paste-subtree level nil nil t)
11776 (when org-log-refile
11777 (org-add-log-setup 'refile nil nil org-log-refile)
11778 (unless (eq org-log-refile 'note)
11779 (save-excursion (org-add-log-note))))
11780 (and org-auto-align-tags
11781 (let ((org-loop-over-headlines-in-active-region nil))
11782 (org-set-tags nil t)))
11783 (let ((bookmark-name (plist-get org-bookmark-names-plist
11784 :last-refile)))
11785 (when bookmark-name
11786 (with-demoted-errors
11787 (bookmark-set bookmark-name))))
11788 ;; If we are refiling for capture, make sure that the
11789 ;; last-capture pointers point here
11790 (when (bound-and-true-p org-capture-is-refiling)
11791 (let ((bookmark-name (plist-get org-bookmark-names-plist
11792 :last-capture-marker)))
11793 (when bookmark-name
11794 (with-demoted-errors
11795 (bookmark-set bookmark-name))))
11796 (move-marker org-capture-last-stored-marker (point)))
11797 (when (fboundp 'deactivate-mark) (deactivate-mark))
11798 (run-hooks 'org-after-refile-insert-hook)))
11799 (unless org-refile-keep
11800 (if regionp
11801 (delete-region (point) (+ (point) (- region-end region-start)))
11802 (delete-region
11803 (and (org-back-to-heading t) (point))
11804 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11805 (when (featurep 'org-inlinetask)
11806 (org-inlinetask-remove-END-maybe))
11807 (setq org-markers-to-move nil)
11808 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11810 (defun org-refile-goto-last-stored ()
11811 "Go to the location where the last refile was stored."
11812 (interactive)
11813 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11814 (message "This is the location of the last refile"))
11816 (defun org-refile--get-location (refloc tbl)
11817 "When user refile to REFLOC, find the associated target in TBL.
11818 Also check `org-refile-target-table'."
11819 (car (delq
11821 (mapcar
11822 (lambda (r) (or (assoc r tbl)
11823 (assoc r org-refile-target-table)))
11824 (list (replace-regexp-in-string "/$" "" refloc)
11825 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11827 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11828 "Prompt the user for a refile location, using PROMPT.
11829 PROMPT should not be suffixed with a colon and a space, because
11830 this function appends the default value from
11831 `org-refile-history' automatically, if that is not empty."
11832 (let ((org-refile-targets org-refile-targets)
11833 (org-refile-use-outline-path org-refile-use-outline-path))
11834 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11835 (unless org-refile-target-table
11836 (user-error "No refile targets"))
11837 (let* ((cbuf (current-buffer))
11838 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11839 (cfunc (if (and org-refile-use-outline-path
11840 org-outline-path-complete-in-steps)
11841 #'org-olpath-completing-read
11842 #'completing-read))
11843 (extra (if org-refile-use-outline-path "/" ""))
11844 (cbnex (concat (buffer-name) extra))
11845 (filename (and cfn (expand-file-name cfn)))
11846 (tbl (mapcar
11847 (lambda (x)
11848 (if (and (not (member org-refile-use-outline-path
11849 '(file full-file-path)))
11850 (not (equal filename (nth 1 x))))
11851 (cons (concat (car x) extra " ("
11852 (file-name-nondirectory (nth 1 x)) ")")
11853 (cdr x))
11854 (cons (concat (car x) extra) (cdr x))))
11855 org-refile-target-table))
11856 (completion-ignore-case t)
11857 cdef
11858 (prompt (concat prompt
11859 (or (and (car org-refile-history)
11860 (concat " (default " (car org-refile-history) ")"))
11861 (and (assoc cbnex tbl) (setq cdef cbnex)
11862 (concat " (default " cbnex ")"))) ": "))
11863 pa answ parent-target child parent old-hist)
11864 (setq old-hist org-refile-history)
11865 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11866 nil 'org-refile-history (or cdef (car org-refile-history))))
11867 (if (setq pa (org-refile--get-location answ tbl))
11868 (progn
11869 (org-refile-check-position pa)
11870 (when (or (not org-refile-history)
11871 (not (eq old-hist org-refile-history))
11872 (not (equal (car pa) (car org-refile-history))))
11873 (setq org-refile-history
11874 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11875 org-refile-history
11876 (cdr org-refile-history))))
11877 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11878 (pop org-refile-history)))
11880 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11881 (progn
11882 (setq parent (match-string 1 answ)
11883 child (match-string 2 answ))
11884 (setq parent-target (org-refile--get-location parent tbl))
11885 (when (and parent-target
11886 (or (eq new-nodes t)
11887 (and (eq new-nodes 'confirm)
11888 (y-or-n-p (format "Create new node \"%s\"? "
11889 child)))))
11890 (org-refile-new-child parent-target child)))
11891 (user-error "Invalid target location")))))
11893 (declare-function org-string-nw-p "org-macs" (s))
11894 (defun org-refile-check-position (refile-pointer)
11895 "Check if the refile pointer matches the headline to which it points."
11896 (let* ((file (nth 1 refile-pointer))
11897 (re (nth 2 refile-pointer))
11898 (pos (nth 3 refile-pointer))
11899 buffer)
11900 (if (and (not (markerp pos)) (not file))
11901 (user-error "Please indicate a target file in the refile path")
11902 (when (org-string-nw-p re)
11903 (setq buffer (if (markerp pos)
11904 (marker-buffer pos)
11905 (or (find-buffer-visiting file)
11906 (find-file-noselect file))))
11907 (with-current-buffer buffer
11908 (org-with-wide-buffer
11909 (goto-char pos)
11910 (beginning-of-line 1)
11911 (unless (looking-at-p re)
11912 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11914 (defun org-refile-new-child (parent-target child)
11915 "Use refile target PARENT-TARGET to add new CHILD below it."
11916 (unless parent-target
11917 (error "Cannot find parent for new node"))
11918 (let ((file (nth 1 parent-target))
11919 (pos (nth 3 parent-target))
11920 level)
11921 (with-current-buffer (or (find-buffer-visiting file)
11922 (find-file-noselect file))
11923 (org-with-wide-buffer
11924 (if pos
11925 (goto-char pos)
11926 (goto-char (point-max))
11927 (unless (bolp) (newline)))
11928 (when (looking-at org-outline-regexp)
11929 (setq level (funcall outline-level))
11930 (org-end-of-subtree t t))
11931 (org-back-over-empty-lines)
11932 (insert "\n" (make-string
11933 (if pos (org-get-valid-level level 1) 1) ?*)
11934 " " child "\n")
11935 (beginning-of-line 0)
11936 (list (concat (car parent-target) "/" child) file "" (point))))))
11938 (defun org-olpath-completing-read (prompt collection &rest args)
11939 "Read an outline path like a file name."
11940 (let ((thetable collection))
11941 (apply #'completing-read
11942 prompt
11943 (lambda (string predicate &optional flag)
11944 (cond
11945 ((eq flag nil) (try-completion string thetable))
11946 ((eq flag t)
11947 (let ((l (length string)))
11948 (mapcar (lambda (x)
11949 (let ((r (substring x l))
11950 (f (if (string-match " ([^)]*)$" x)
11951 (match-string 0 x)
11952 "")))
11953 (if (string-match "/" r)
11954 (concat string (substring r 0 (match-end 0)) f)
11955 x)))
11956 (all-completions string thetable predicate))))
11957 ;; Exact match?
11958 ((eq flag 'lambda) (assoc string thetable))))
11959 args)))
11961 ;;;; Dynamic blocks
11963 (defun org-find-dblock (name)
11964 "Find the first dynamic block with name NAME in the buffer.
11965 If not found, stay at current position and return nil."
11966 (let ((case-fold-search t) pos)
11967 (save-excursion
11968 (goto-char (point-min))
11969 (setq pos (and (re-search-forward
11970 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11971 (match-beginning 0))))
11972 (when pos (goto-char pos))
11973 pos))
11975 (defun org-create-dblock (plist)
11976 "Create a dynamic block section, with parameters taken from PLIST.
11977 PLIST must contain a :name entry which is used as the name of the block."
11978 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11979 (end-of-line 1)
11980 (newline))
11981 (let ((col (current-column))
11982 (name (plist-get plist :name)))
11983 (insert "#+BEGIN: " name)
11984 (while plist
11985 (if (eq (car plist) :name)
11986 (setq plist (cddr plist))
11987 (insert " " (prin1-to-string (pop plist)))))
11988 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11989 (beginning-of-line -2)))
11991 (defun org-prepare-dblock ()
11992 "Prepare dynamic block for refresh.
11993 This empties the block, puts the cursor at the insert position and returns
11994 the property list including an extra property :name with the block name."
11995 (unless (looking-at org-dblock-start-re)
11996 (user-error "Not at a dynamic block"))
11997 (let* ((begdel (1+ (match-end 0)))
11998 (name (org-no-properties (match-string 1)))
11999 (params (append (list :name name)
12000 (read (concat "(" (match-string 3) ")")))))
12001 (save-excursion
12002 (beginning-of-line 1)
12003 (skip-chars-forward " \t")
12004 (setq params (plist-put params :indentation-column (current-column))))
12005 (unless (re-search-forward org-dblock-end-re nil t)
12006 (error "Dynamic block not terminated"))
12007 (setq params
12008 (append params
12009 (list :content (buffer-substring
12010 begdel (match-beginning 0)))))
12011 (delete-region begdel (match-beginning 0))
12012 (goto-char begdel)
12013 (open-line 1)
12014 params))
12016 (defun org-map-dblocks (&optional command)
12017 "Apply COMMAND to all dynamic blocks in the current buffer.
12018 If COMMAND is not given, use `org-update-dblock'."
12019 (let ((cmd (or command 'org-update-dblock)))
12020 (save-excursion
12021 (goto-char (point-min))
12022 (while (re-search-forward org-dblock-start-re nil t)
12023 (goto-char (match-beginning 0))
12024 (save-excursion
12025 (condition-case nil
12026 (funcall cmd)
12027 (error (message "Error during update of dynamic block"))))
12028 (unless (re-search-forward org-dblock-end-re nil t)
12029 (error "Dynamic block not terminated"))))))
12031 (defun org-dblock-update (&optional arg)
12032 "User command for updating dynamic blocks.
12033 Update the dynamic block at point. With prefix ARG, update all dynamic
12034 blocks in the buffer."
12035 (interactive "P")
12036 (if arg
12037 (org-update-all-dblocks)
12038 (or (looking-at org-dblock-start-re)
12039 (org-beginning-of-dblock))
12040 (org-update-dblock)))
12042 (defun org-update-dblock ()
12043 "Update the dynamic block at point.
12044 This means to empty the block, parse for parameters and then call
12045 the correct writing function."
12046 (interactive)
12047 (save-excursion
12048 (let* ((win (selected-window))
12049 (pos (point))
12050 (line (org-current-line))
12051 (params (org-prepare-dblock))
12052 (name (plist-get params :name))
12053 (indent (plist-get params :indentation-column))
12054 (cmd (intern (concat "org-dblock-write:" name))))
12055 (message "Updating dynamic block `%s' at line %d..." name line)
12056 (funcall cmd params)
12057 (message "Updating dynamic block `%s' at line %d...done" name line)
12058 (goto-char pos)
12059 (when (and indent (> indent 0))
12060 (setq indent (make-string indent ?\ ))
12061 (save-excursion
12062 (select-window win)
12063 (org-beginning-of-dblock)
12064 (forward-line 1)
12065 (while (not (looking-at org-dblock-end-re))
12066 (insert indent)
12067 (beginning-of-line 2))
12068 (when (looking-at org-dblock-end-re)
12069 (and (looking-at "[ \t]+")
12070 (replace-match ""))
12071 (insert indent)))))))
12073 (defun org-beginning-of-dblock ()
12074 "Find the beginning of the dynamic block at point.
12075 Error if there is no such block at point."
12076 (let ((pos (point))
12077 beg)
12078 (end-of-line 1)
12079 (if (and (re-search-backward org-dblock-start-re nil t)
12080 (setq beg (match-beginning 0))
12081 (re-search-forward org-dblock-end-re nil t)
12082 (> (match-end 0) pos))
12083 (goto-char beg)
12084 (goto-char pos)
12085 (error "Not in a dynamic block"))))
12087 (defun org-update-all-dblocks ()
12088 "Update all dynamic blocks in the buffer.
12089 This function can be used in a hook."
12090 (interactive)
12091 (when (derived-mode-p 'org-mode)
12092 (org-map-dblocks 'org-update-dblock)))
12095 ;;;; Completion
12097 (declare-function org-export-backend-options "ox" (cl-x) t)
12098 (defun org-get-export-keywords ()
12099 "Return a list of all currently understood export keywords.
12100 Export keywords include options, block names, attributes and
12101 keywords relative to each registered export back-end."
12102 (let (keywords)
12103 (dolist (backend
12104 (bound-and-true-p org-export-registered-backends)
12105 (delq nil keywords))
12106 ;; Back-end name (for keywords, like #+LATEX:)
12107 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12108 (dolist (option-entry (org-export-backend-options backend))
12109 ;; Back-end options.
12110 (push (nth 1 option-entry) keywords)))))
12112 (defconst org-options-keywords
12113 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12114 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12115 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12116 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12117 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12119 (defcustom org-structure-template-alist
12120 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12121 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12122 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12123 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12124 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12125 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12126 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12127 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12128 ("L" "#+LaTeX: ")
12129 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12130 ("H" "#+HTML: ")
12131 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12132 ("A" "#+ASCII: ")
12133 ("i" "#+INDEX: ?")
12134 ("I" "#+INCLUDE: %file ?"))
12135 "Structure completion elements.
12136 This is a list of abbreviation keys and values. The value gets inserted
12137 if you type `<' followed by the key and then press the completion key,
12138 usually `TAB'. %file will be replaced by a file name after prompting
12139 for the file using completion. The cursor will be placed at the position
12140 of the `?' in the template.
12141 There are two templates for each key, the first uses the original Org syntax,
12142 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12143 the default when the /org-mtags.el/ module has been loaded. See also the
12144 variable `org-mtags-prefer-muse-templates'."
12145 :group 'org-completion
12146 :type '(repeat
12147 (list
12148 (string :tag "Key")
12149 (string :tag "Template")))
12150 :version "26.1"
12151 :package-version '(Org . "8.3"))
12153 (defun org-try-structure-completion ()
12154 "Try to complete a structure template before point.
12155 This looks for strings like \"<e\" on an otherwise empty line and
12156 expands them."
12157 (let ((l (buffer-substring (point-at-bol) (point)))
12159 (when (and (looking-at "[ \t]*$")
12160 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12161 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12162 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12163 (match-beginning 1)) a)
12164 t)))
12166 (defun org-complete-expand-structure-template (start cell)
12167 "Expand a structure template."
12168 (let ((rpl (nth 1 cell))
12169 (ind ""))
12170 (delete-region start (point))
12171 (when (string-match "\\`[ \t]*#\\+" rpl)
12172 (cond
12173 ((bolp))
12174 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12175 (setq ind (buffer-substring (point-at-bol) (point))))
12176 (t (newline))))
12177 (setq start (point))
12178 (when (string-match "%file" rpl)
12179 (setq rpl (replace-match
12180 (concat
12181 "\""
12182 (save-match-data
12183 (abbreviate-file-name (read-file-name "Include file: ")))
12184 "\"")
12185 t t rpl)))
12186 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12187 (concat "\n" ind)))
12188 (insert rpl)
12189 (when (re-search-backward "\\?" start t) (delete-char 1))))
12191 ;;;; TODO, DEADLINE, Comments
12193 (defun org-toggle-comment ()
12194 "Change the COMMENT state of an entry."
12195 (interactive)
12196 (save-excursion
12197 (org-back-to-heading)
12198 (let ((case-fold-search nil))
12199 (looking-at org-complex-heading-regexp))
12200 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12201 (skip-chars-forward " \t")
12202 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12203 (if (org-in-commented-heading-p t)
12204 (delete-region (point)
12205 (progn (search-forward " " (line-end-position) 'move)
12206 (skip-chars-forward " \t")
12207 (point)))
12208 (insert org-comment-string)
12209 (unless (eolp) (insert " ")))))
12211 (defvar org-last-todo-state-is-todo nil
12212 "This is non-nil when the last TODO state change led to a TODO state.
12213 If the last change removed the TODO tag or switched to DONE, then
12214 this is nil.")
12216 (defvar org-setting-tags nil) ; dynamically skipped
12218 (defvar org-todo-setup-filter-hook nil
12219 "Hook for functions that pre-filter todo specs.
12220 Each function takes a todo spec and returns either nil or the spec
12221 transformed into canonical form." )
12223 (defvar org-todo-get-default-hook nil
12224 "Hook for functions that get a default item for todo.
12225 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12226 nil or a string to be used for the todo mark." )
12228 (defvar org-agenda-headline-snapshot-before-repeat)
12230 (defun org-current-effective-time ()
12231 "Return current time adjusted for `org-extend-today-until' variable."
12232 (let* ((ct (org-current-time))
12233 (dct (decode-time ct))
12234 (ct1
12235 (cond
12236 (org-use-last-clock-out-time-as-effective-time
12237 (or (org-clock-get-last-clock-out-time) ct))
12238 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12239 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12240 (t ct))))
12241 ct1))
12243 (defun org-todo-yesterday (&optional arg)
12244 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12245 (interactive "P")
12246 (if (eq major-mode 'org-agenda-mode)
12247 (apply 'org-agenda-todo-yesterday arg)
12248 (let* ((org-use-effective-time t)
12249 (hour (nth 2 (decode-time (org-current-time))))
12250 (org-extend-today-until (1+ hour)))
12251 (org-todo arg))))
12253 (defvar org-block-entry-blocking ""
12254 "First entry preventing the TODO state change.")
12256 (defun org-cancel-repeater ()
12257 "Cancel a repeater by setting its numeric value to zero."
12258 (interactive)
12259 (save-excursion
12260 (org-back-to-heading t)
12261 (let ((bound1 (point))
12262 (bound0 (save-excursion (outline-next-heading) (point))))
12263 (when (and (re-search-forward
12264 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12265 org-deadline-time-regexp "\\)\\|\\("
12266 org-ts-regexp "\\)")
12267 bound0 t)
12268 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12269 bound1 t))
12270 (replace-match "0" t nil nil 1)))))
12272 (defvar org-state)
12273 (defvar org-blocked-by-checkboxes)
12274 (defun org-todo (&optional arg)
12275 "Change the TODO state of an item.
12277 The state of an item is given by a keyword at the start of the heading,
12278 like
12279 *** TODO Write paper
12280 *** DONE Call mom
12282 The different keywords are specified in the variable `org-todo-keywords'.
12283 By default the available states are \"TODO\" and \"DONE\". So, for this
12284 example: when the item starts with TODO, it is changed to DONE.
12285 When it starts with DONE, the DONE is removed. And when neither TODO nor
12286 DONE are present, add TODO at the beginning of the heading.
12288 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12289 state.
12290 With numeric prefix ARG, switch to that state.
12291 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12292 next set of TODO \
12293 keywords (nextset).
12294 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12295 prefix, circumvent any state blocking.
12296 With a numeric prefix arg of 0, inhibit note taking for the change.
12297 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12299 When called through ELisp, arg is also interpreted in the following way:
12300 `none' -> empty state
12301 \"\" -> switch to empty state
12302 `done' -> switch to DONE
12303 `nextset' -> switch to the next set of keywords
12304 `previousset' -> switch to the previous set of keywords
12305 \"WAITING\" -> switch to the specified keyword, but only if it
12306 really is a member of `org-todo-keywords'."
12307 (interactive "P")
12308 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12309 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12310 'region-start-level 'region))
12311 org-loop-over-headlines-in-active-region)
12312 (org-map-entries
12313 `(org-todo ,arg)
12314 org-loop-over-headlines-in-active-region
12315 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12316 (when (equal arg '(16)) (setq arg 'nextset))
12317 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12318 (let ((org-blocker-hook org-blocker-hook)
12319 commentp
12320 case-fold-search)
12321 (when (equal arg '(64))
12322 (setq arg nil org-blocker-hook nil))
12323 (when (and org-blocker-hook
12324 (or org-inhibit-blocking
12325 (org-entry-get nil "NOBLOCKING")))
12326 (setq org-blocker-hook nil))
12327 (save-excursion
12328 (catch 'exit
12329 (org-back-to-heading t)
12330 (when (org-in-commented-heading-p t)
12331 (org-toggle-comment)
12332 (setq commentp t))
12333 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12334 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12335 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12336 (let* ((match-data (match-data))
12337 (startpos (point-at-bol))
12338 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12339 (org-log-done org-log-done)
12340 (org-log-repeat org-log-repeat)
12341 (org-todo-log-states org-todo-log-states)
12342 (org-inhibit-logging
12343 (if (equal arg 0)
12344 (progn (setq arg nil) 'note) org-inhibit-logging))
12345 (this (match-string 1))
12346 (hl-pos (match-beginning 0))
12347 (head (org-get-todo-sequence-head this))
12348 (ass (assoc head org-todo-kwd-alist))
12349 (interpret (nth 1 ass))
12350 (done-word (nth 3 ass))
12351 (final-done-word (nth 4 ass))
12352 (org-last-state (or this ""))
12353 (completion-ignore-case t)
12354 (member (member this org-todo-keywords-1))
12355 (tail (cdr member))
12356 (org-state (cond
12357 ((and org-todo-key-trigger
12358 (or (and (equal arg '(4))
12359 (eq org-use-fast-todo-selection 'prefix))
12360 (and (not arg) org-use-fast-todo-selection
12361 (not (eq org-use-fast-todo-selection
12362 'prefix)))))
12363 ;; Use fast selection.
12364 (org-fast-todo-selection))
12365 ((and (equal arg '(4))
12366 (or (not org-use-fast-todo-selection)
12367 (not org-todo-key-trigger)))
12368 ;; Read a state with completion.
12369 (completing-read
12370 "State: " (mapcar #'list org-todo-keywords-1)
12371 nil t))
12372 ((eq arg 'right)
12373 (if this
12374 (if tail (car tail) nil)
12375 (car org-todo-keywords-1)))
12376 ((eq arg 'left)
12377 (unless (equal member org-todo-keywords-1)
12378 (if this
12379 (nth (- (length org-todo-keywords-1)
12380 (length tail) 2)
12381 org-todo-keywords-1)
12382 (org-last org-todo-keywords-1))))
12383 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12384 (setq arg nil))) ;hack to fall back to cycling
12385 (arg
12386 ;; User or caller requests a specific state.
12387 (cond
12388 ((equal arg "") nil)
12389 ((eq arg 'none) nil)
12390 ((eq arg 'done) (or done-word (car org-done-keywords)))
12391 ((eq arg 'nextset)
12392 (or (car (cdr (member head org-todo-heads)))
12393 (car org-todo-heads)))
12394 ((eq arg 'previousset)
12395 (let ((org-todo-heads (reverse org-todo-heads)))
12396 (or (car (cdr (member head org-todo-heads)))
12397 (car org-todo-heads))))
12398 ((car (member arg org-todo-keywords-1)))
12399 ((stringp arg)
12400 (user-error "State `%s' not valid in this file" arg))
12401 ((nth (1- (prefix-numeric-value arg))
12402 org-todo-keywords-1))))
12403 ((null member) (or head (car org-todo-keywords-1)))
12404 ((equal this final-done-word) nil) ;-> make empty
12405 ((null tail) nil) ;-> first entry
12406 ((memq interpret '(type priority))
12407 (if (eq this-command last-command)
12408 (car tail)
12409 (if (> (length tail) 0)
12410 (or done-word (car org-done-keywords))
12411 nil)))
12413 (car tail))))
12414 (org-state (or
12415 (run-hook-with-args-until-success
12416 'org-todo-get-default-hook org-state org-last-state)
12417 org-state))
12418 (next (if org-state (concat " " org-state " ") " "))
12419 (change-plist (list :type 'todo-state-change :from this :to org-state
12420 :position startpos))
12421 dolog now-done-p)
12422 (when org-blocker-hook
12423 (let (org-blocked-by-checkboxes block-reason)
12424 (setq org-last-todo-state-is-todo
12425 (not (member this org-done-keywords)))
12426 (unless (save-excursion
12427 (save-match-data
12428 (org-with-wide-buffer
12429 (run-hook-with-args-until-failure
12430 'org-blocker-hook change-plist))))
12431 (setq block-reason (if org-blocked-by-checkboxes
12432 "contained checkboxes"
12433 (format "\"%s\"" org-block-entry-blocking)))
12434 (if (called-interactively-p 'interactive)
12435 (user-error "TODO state change from %s to %s blocked (by %s)"
12436 this org-state block-reason)
12437 ;; Fail silently.
12438 (message "TODO state change from %s to %s blocked (by %s)"
12439 this org-state block-reason)
12440 (throw 'exit nil)))))
12441 (store-match-data match-data)
12442 (replace-match next t t)
12443 (cond ((equal this org-state)
12444 (message "TODO state was already %s" (org-trim next)))
12445 ((not (pos-visible-in-window-p hl-pos))
12446 (message "TODO state changed to %s" (org-trim next))))
12447 (unless head
12448 (setq head (org-get-todo-sequence-head org-state)
12449 ass (assoc head org-todo-kwd-alist)
12450 interpret (nth 1 ass)
12451 done-word (nth 3 ass)
12452 final-done-word (nth 4 ass)))
12453 (when (memq arg '(nextset previousset))
12454 (message "Keyword-Set %d/%d: %s"
12455 (- (length org-todo-sets) -1
12456 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12457 (length org-todo-sets)
12458 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12459 (setq org-last-todo-state-is-todo
12460 (not (member org-state org-done-keywords)))
12461 (setq now-done-p (and (member org-state org-done-keywords)
12462 (not (member this org-done-keywords))))
12463 (and logging (org-local-logging logging))
12464 (when (and (or org-todo-log-states org-log-done)
12465 (not (eq org-inhibit-logging t))
12466 (not (memq arg '(nextset previousset))))
12467 ;; We need to look at recording a time and note.
12468 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12469 (nth 2 (assoc this org-todo-log-states))))
12470 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12471 (setq dolog 'time))
12472 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12473 (and org-state
12474 (member org-state org-not-done-keywords)
12475 (not (member this org-not-done-keywords))))
12476 ;; This is now a todo state and was not one before
12477 ;; If there was a CLOSED time stamp, get rid of it.
12478 (org-add-planning-info nil nil 'closed))
12479 (when (and now-done-p org-log-done)
12480 ;; It is now done, and it was not done before.
12481 (org-add-planning-info 'closed (org-current-effective-time))
12482 (when (and (not dolog) (eq 'note org-log-done))
12483 (org-add-log-setup 'done org-state this 'note)))
12484 (when (and org-state dolog)
12485 ;; This is a non-nil state, and we need to log it.
12486 (org-add-log-setup 'state org-state this dolog)))
12487 ;; Fixup tag positioning.
12488 (org-todo-trigger-tag-changes org-state)
12489 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12490 (when org-provide-todo-statistics
12491 (org-update-parent-todo-statistics))
12492 (run-hooks 'org-after-todo-state-change-hook)
12493 (when (and arg (not (member org-state org-done-keywords)))
12494 (setq head (org-get-todo-sequence-head org-state)))
12495 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12496 ;; Do we need to trigger a repeat?
12497 (when now-done-p
12498 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12499 ;; This is for the agenda, take a snapshot of the headline.
12500 (save-match-data
12501 (setq org-agenda-headline-snapshot-before-repeat
12502 (org-get-heading))))
12503 (org-auto-repeat-maybe org-state))
12504 ;; Fixup cursor location if close to the keyword.
12505 (when (and (outline-on-heading-p)
12506 (not (bolp))
12507 (save-excursion (beginning-of-line 1)
12508 (looking-at org-todo-line-regexp))
12509 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12510 (goto-char (or (match-end 2) (match-end 1)))
12511 (and (looking-at " ") (just-one-space)))
12512 (when org-trigger-hook
12513 (save-excursion
12514 (run-hook-with-args 'org-trigger-hook change-plist)))
12515 (when commentp (org-toggle-comment))))))))
12517 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12518 "Block turning an entry into a TODO, using the hierarchy.
12519 This checks whether the current task should be blocked from state
12520 changes. Such blocking occurs when:
12522 1. The task has children which are not all in a completed state.
12524 2. A task has a parent with the property :ORDERED:, and there
12525 are siblings prior to the current task with incomplete
12526 status.
12528 3. The parent of the task is blocked because it has siblings that should
12529 be done first, or is child of a block grandparent TODO entry."
12531 (if (not org-enforce-todo-dependencies)
12532 t ; if locally turned off don't block
12533 (catch 'dont-block
12534 ;; If this is not a todo state change, or if this entry is already DONE,
12535 ;; do not block
12536 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12537 (member (plist-get change-plist :from)
12538 (cons 'done org-done-keywords))
12539 (member (plist-get change-plist :to)
12540 (cons 'todo org-not-done-keywords))
12541 (not (plist-get change-plist :to)))
12542 (throw 'dont-block t))
12543 ;; If this task has children, and any are undone, it's blocked
12544 (save-excursion
12545 (org-back-to-heading t)
12546 (let ((this-level (funcall outline-level)))
12547 (outline-next-heading)
12548 (let ((child-level (funcall outline-level)))
12549 (while (and (not (eobp))
12550 (> child-level this-level))
12551 ;; this todo has children, check whether they are all
12552 ;; completed
12553 (when (and (not (org-entry-is-done-p))
12554 (org-entry-is-todo-p))
12555 (setq org-block-entry-blocking (org-get-heading))
12556 (throw 'dont-block nil))
12557 (outline-next-heading)
12558 (setq child-level (funcall outline-level))))))
12559 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12560 ;; any previous siblings are undone, it's blocked
12561 (save-excursion
12562 (org-back-to-heading t)
12563 (let* ((pos (point))
12564 (parent-pos (and (org-up-heading-safe) (point)))
12565 (case-fold-search nil))
12566 (unless parent-pos (throw 'dont-block t)) ; no parent
12567 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12568 (forward-line 1)
12569 (re-search-forward org-not-done-heading-regexp pos t))
12570 (setq org-block-entry-blocking (match-string 0))
12571 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12572 ;; Search further up the hierarchy, to see if an ancestor is blocked
12573 (while t
12574 (goto-char parent-pos)
12575 (unless (looking-at org-not-done-heading-regexp)
12576 (throw 'dont-block t)) ; do not block, parent is not a TODO
12577 (setq pos (point))
12578 (setq parent-pos (and (org-up-heading-safe) (point)))
12579 (unless parent-pos (throw 'dont-block t)) ; no parent
12580 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12581 (forward-line 1)
12582 (re-search-forward org-not-done-heading-regexp pos t)
12583 (setq org-block-entry-blocking (org-get-heading)))
12584 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12586 (defcustom org-track-ordered-property-with-tag nil
12587 "Should the ORDERED property also be shown as a tag?
12588 The ORDERED property decides if an entry should require subtasks to be
12589 completed in sequence. Since a property is not very visible, setting
12590 this option means that toggling the ORDERED property with the command
12591 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12592 not relevant for the behavior, but it makes things more visible.
12594 Note that toggling the tag with tags commands will not change the property
12595 and therefore not influence behavior!
12597 This can be t, meaning the tag ORDERED should be used, It can also be a
12598 string to select a different tag for this task."
12599 :group 'org-todo
12600 :type '(choice
12601 (const :tag "No tracking" nil)
12602 (const :tag "Track with ORDERED tag" t)
12603 (string :tag "Use other tag")))
12605 (defun org-toggle-ordered-property ()
12606 "Toggle the ORDERED property of the current entry.
12607 For better visibility, you can track the value of this property with a tag.
12608 See variable `org-track-ordered-property-with-tag'."
12609 (interactive)
12610 (let* ((t1 org-track-ordered-property-with-tag)
12611 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12612 (save-excursion
12613 (org-back-to-heading)
12614 (if (org-entry-get nil "ORDERED")
12615 (progn
12616 (org-delete-property "ORDERED")
12617 (and tag (org-toggle-tag tag 'off))
12618 (message "Subtasks can be completed in arbitrary order"))
12619 (org-entry-put nil "ORDERED" "t")
12620 (and tag (org-toggle-tag tag 'on))
12621 (message "Subtasks must be completed in sequence")))))
12623 (defun org-block-todo-from-checkboxes (change-plist)
12624 "Block turning an entry into a TODO, using checkboxes.
12625 This checks whether the current task should be blocked from state
12626 changes because there are unchecked boxes in this entry."
12627 (if (not org-enforce-todo-checkbox-dependencies)
12628 t ; if locally turned off don't block
12629 (catch 'dont-block
12630 ;; If this is not a todo state change, or if this entry is already DONE,
12631 ;; do not block
12632 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12633 (member (plist-get change-plist :from)
12634 (cons 'done org-done-keywords))
12635 (member (plist-get change-plist :to)
12636 (cons 'todo org-not-done-keywords))
12637 (not (plist-get change-plist :to)))
12638 (throw 'dont-block t))
12639 ;; If this task has checkboxes that are not checked, it's blocked
12640 (save-excursion
12641 (org-back-to-heading t)
12642 (let ((beg (point)) end)
12643 (outline-next-heading)
12644 (setq end (point))
12645 (goto-char beg)
12646 (when (org-list-search-forward
12647 (concat (org-item-beginning-re)
12648 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12649 "\\[[- ]\\]")
12650 end t)
12651 (when (boundp 'org-blocked-by-checkboxes)
12652 (setq org-blocked-by-checkboxes t))
12653 (throw 'dont-block nil))))
12654 t))) ; do not block
12656 (defun org-entry-blocked-p ()
12657 "Non-nil if entry at point is blocked."
12658 (and (not (org-entry-get nil "NOBLOCKING"))
12659 (member (org-entry-get nil "TODO") org-not-done-keywords)
12660 (not (run-hook-with-args-until-failure
12661 'org-blocker-hook
12662 (list :type 'todo-state-change
12663 :position (point)
12664 :from 'todo
12665 :to 'done)))))
12667 (defun org-update-statistics-cookies (all)
12668 "Update the statistics cookie, either from TODO or from checkboxes.
12669 This should be called with the cursor in a line with a statistics
12670 cookie. When called with a \\[universal-argument] prefix, update
12671 all statistics cookies in the buffer."
12672 (interactive "P")
12673 (if all
12674 (progn
12675 (org-update-checkbox-count 'all)
12676 (org-map-entries 'org-update-parent-todo-statistics))
12677 (if (not (org-at-heading-p))
12678 (org-update-checkbox-count)
12679 (let ((pos (point-marker))
12680 end l1 l2)
12681 (ignore-errors (org-back-to-heading t))
12682 (if (not (org-at-heading-p))
12683 (org-update-checkbox-count)
12684 (setq l1 (org-outline-level))
12685 (setq end (save-excursion
12686 (outline-next-heading)
12687 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12688 (point)))
12689 (if (and (save-excursion
12690 (re-search-forward
12691 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12692 (not (save-excursion (re-search-forward
12693 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12694 (org-update-checkbox-count)
12695 (if (and l2 (> l2 l1))
12696 (progn
12697 (goto-char end)
12698 (org-update-parent-todo-statistics))
12699 (goto-char pos)
12700 (beginning-of-line 1)
12701 (while (re-search-forward
12702 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12703 (point-at-eol) t)
12704 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12705 (goto-char pos)
12706 (move-marker pos nil)))))
12708 (defvar org-entry-property-inherited-from) ;; defined below
12709 (defun org-update-parent-todo-statistics ()
12710 "Update any statistics cookie in the parent of the current headline.
12711 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12712 the entire subtree and this will travel up the hierarchy and update
12713 statistics everywhere."
12714 (let* ((prop (save-excursion (org-up-heading-safe)
12715 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12716 (recursive (or (not org-hierarchical-todo-statistics)
12717 (and prop (string-match "\\<recursive\\>" prop))))
12718 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12720 (first t)
12721 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12722 level ltoggle l1 new ndel
12723 (cnt-all 0) (cnt-done 0) is-percent kwd
12724 checkbox-beg cookie-present)
12725 (catch 'exit
12726 (save-excursion
12727 (beginning-of-line 1)
12728 (setq ltoggle (funcall outline-level))
12729 ;; Three situations are to consider:
12731 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12732 ;; to the top-level ancestor on the headline;
12734 ;; 2. If parent has "recursive" property, repeat up to the
12735 ;; headline setting that property, taking inheritance into
12736 ;; account;
12738 ;; 3. Else, move up to direct parent and proceed only once.
12739 (while (and (setq level (org-up-heading-safe))
12740 (or recursive first)
12741 (>= (point) lim))
12742 (setq first nil cookie-present nil)
12743 (unless (and level
12744 (not (string-match
12745 "\\<checkbox\\>"
12746 (downcase (or (org-entry-get nil "COOKIE_DATA")
12747 "")))))
12748 (throw 'exit nil))
12749 (while (re-search-forward box-re (point-at-eol) t)
12750 (setq cnt-all 0 cnt-done 0 cookie-present t)
12751 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12752 (save-match-data
12753 (unless (outline-next-heading) (throw 'exit nil))
12754 (while (and (looking-at org-complex-heading-regexp)
12755 (> (setq l1 (length (match-string 1))) level))
12756 (setq kwd (and (or recursive (= l1 ltoggle))
12757 (match-string 2)))
12758 (if (or (eq org-provide-todo-statistics 'all-headlines)
12759 (and (eq org-provide-todo-statistics t)
12760 (or (member kwd org-done-keywords)))
12761 (and (listp org-provide-todo-statistics)
12762 (stringp (car org-provide-todo-statistics))
12763 (or (member kwd org-provide-todo-statistics)
12764 (member kwd org-done-keywords)))
12765 (and (listp org-provide-todo-statistics)
12766 (listp (car org-provide-todo-statistics))
12767 (or (member kwd (car org-provide-todo-statistics))
12768 (and (member kwd org-done-keywords)
12769 (member kwd (cadr org-provide-todo-statistics))))))
12770 (setq cnt-all (1+ cnt-all))
12771 (and (eq org-provide-todo-statistics t)
12773 (setq cnt-all (1+ cnt-all))))
12774 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12775 (member kwd org-done-keywords))
12776 (and (listp org-provide-todo-statistics)
12777 (listp (car org-provide-todo-statistics))
12778 (member kwd org-done-keywords)
12779 (member kwd (cadr org-provide-todo-statistics)))
12780 (and (listp org-provide-todo-statistics)
12781 (stringp (car org-provide-todo-statistics))
12782 (member kwd org-done-keywords)))
12783 (setq cnt-done (1+ cnt-done)))
12784 (outline-next-heading)))
12785 (setq new
12786 (if is-percent
12787 (format "[%d%%]" (floor (* 100.0 cnt-done)
12788 (max 1 cnt-all)))
12789 (format "[%d/%d]" cnt-done cnt-all))
12790 ndel (- (match-end 0) checkbox-beg))
12791 (goto-char checkbox-beg)
12792 (insert new)
12793 (delete-region (point) (+ (point) ndel))
12794 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12795 (when cookie-present
12796 (run-hook-with-args 'org-after-todo-statistics-hook
12797 cnt-done (- cnt-all cnt-done))))))
12798 (run-hooks 'org-todo-statistics-hook)))
12800 (defvar org-after-todo-statistics-hook nil
12801 "Hook that is called after a TODO statistics cookie has been updated.
12802 Each function is called with two arguments: the number of not-done entries
12803 and the number of done entries.
12805 For example, the following function, when added to this hook, will switch
12806 an entry to DONE when all children are done, and back to TODO when new
12807 entries are set to a TODO status. Note that this hook is only called
12808 when there is a statistics cookie in the headline!
12810 (defun org-summary-todo (n-done n-not-done)
12811 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12812 (let (org-log-done org-log-states) ; turn off logging
12813 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12816 (defvar org-todo-statistics-hook nil
12817 "Hook that is run whenever Org thinks TODO statistics should be updated.
12818 This hook runs even if there is no statistics cookie present, in which case
12819 `org-after-todo-statistics-hook' would not run.")
12821 (defun org-todo-trigger-tag-changes (state)
12822 "Apply the changes defined in `org-todo-state-tags-triggers'."
12823 (let ((l org-todo-state-tags-triggers)
12824 changes)
12825 (when (or (not state) (equal state ""))
12826 (setq changes (append changes (cdr (assoc "" l)))))
12827 (when (and (stringp state) (> (length state) 0))
12828 (setq changes (append changes (cdr (assoc state l)))))
12829 (when (member state org-not-done-keywords)
12830 (setq changes (append changes (cdr (assq 'todo l)))))
12831 (when (member state org-done-keywords)
12832 (setq changes (append changes (cdr (assq 'done l)))))
12833 (dolist (c changes)
12834 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12836 (defun org-local-logging (value)
12837 "Get logging settings from a property VALUE."
12838 ;; Directly set the variables, they are already local.
12839 (setq org-log-done nil
12840 org-log-repeat nil
12841 org-todo-log-states nil)
12842 (dolist (w (split-string value))
12843 (let (a)
12844 (cond
12845 ((setq a (assoc w org-startup-options))
12846 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12847 (set (nth 1 a) (nth 2 a))))
12848 ((setq a (org-extract-log-state-settings w))
12849 (and (member (car a) org-todo-keywords-1)
12850 (push a org-todo-log-states)))))))
12852 (defun org-get-todo-sequence-head (kwd)
12853 "Return the head of the TODO sequence to which KWD belongs.
12854 If KWD is not set, check if there is a text property remembering the
12855 right sequence."
12856 (let (p)
12857 (cond
12858 ((not kwd)
12859 (or (get-text-property (point-at-bol) 'org-todo-head)
12860 (progn
12861 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12862 nil (point-at-eol)))
12863 (get-text-property p 'org-todo-head))))
12864 ((not (member kwd org-todo-keywords-1))
12865 (car org-todo-keywords-1))
12866 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12868 (defun org-fast-todo-selection ()
12869 "Fast TODO keyword selection with single keys.
12870 Returns the new TODO keyword, or nil if no state change should occur."
12871 (let* ((fulltable org-todo-key-alist)
12872 (done-keywords org-done-keywords) ;; needed for the faces.
12873 (maxlen (apply 'max (mapcar
12874 (lambda (x)
12875 (if (stringp (car x)) (string-width (car x)) 0))
12876 fulltable)))
12877 (expert nil)
12878 (fwidth (+ maxlen 3 1 3))
12879 (ncol (/ (- (window-width) 4) fwidth))
12880 tg cnt e c tbl
12881 groups ingroup)
12882 (save-excursion
12883 (save-window-excursion
12884 (if expert
12885 (set-buffer (get-buffer-create " *Org todo*"))
12886 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12887 (erase-buffer)
12888 (setq-local org-done-keywords done-keywords)
12889 (setq tbl fulltable cnt 0)
12890 (while (setq e (pop tbl))
12891 (cond
12892 ((equal e '(:startgroup))
12893 (push '() groups) (setq ingroup t)
12894 (unless (= cnt 0)
12895 (setq cnt 0)
12896 (insert "\n"))
12897 (insert "{ "))
12898 ((equal e '(:endgroup))
12899 (setq ingroup nil cnt 0)
12900 (insert "}\n"))
12901 ((equal e '(:newline))
12902 (unless (= cnt 0)
12903 (setq cnt 0)
12904 (insert "\n")
12905 (setq e (car tbl))
12906 (while (equal (car tbl) '(:newline))
12907 (insert "\n")
12908 (setq tbl (cdr tbl)))))
12910 (setq tg (car e) c (cdr e))
12911 (when ingroup (push tg (car groups)))
12912 (setq tg (org-add-props tg nil 'face
12913 (org-get-todo-face tg)))
12914 (when (and (= cnt 0) (not ingroup)) (insert " "))
12915 (insert "[" c "] " tg (make-string
12916 (- fwidth 4 (length tg)) ?\ ))
12917 (when (= (setq cnt (1+ cnt)) ncol)
12918 (insert "\n")
12919 (when ingroup (insert " "))
12920 (setq cnt 0)))))
12921 (insert "\n")
12922 (goto-char (point-min))
12923 (unless expert (org-fit-window-to-buffer))
12924 (message "[a-z..]:Set [SPC]:clear")
12925 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12926 (cond
12927 ((or (= c ?\C-g)
12928 (and (= c ?q) (not (rassoc c fulltable))))
12929 (setq quit-flag t))
12930 ((= c ?\ ) nil)
12931 ((setq e (rassoc c fulltable) tg (car e))
12933 (t (setq quit-flag t)))))))
12935 (defun org-entry-is-todo-p ()
12936 (member (org-get-todo-state) org-not-done-keywords))
12938 (defun org-entry-is-done-p ()
12939 (member (org-get-todo-state) org-done-keywords))
12941 (defun org-get-todo-state ()
12942 "Return the TODO keyword of the current subtree."
12943 (save-excursion
12944 (org-back-to-heading t)
12945 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12946 (match-end 2)
12947 (match-string 2))))
12949 (defun org-at-date-range-p (&optional inactive-ok)
12950 "Non-nil if point is inside a date range.
12952 When optional argument INACTIVE-OK is non-nil, also consider
12953 inactive time ranges.
12955 When this function returns a non-nil value, match data is set
12956 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12957 on INACTIVE-OK."
12958 (interactive)
12959 (save-excursion
12960 (catch 'exit
12961 (let ((pos (point)))
12962 (skip-chars-backward "^[<\r\n")
12963 (skip-chars-backward "<[")
12964 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12965 (>= (match-end 0) pos)
12966 (throw 'exit t))
12967 (skip-chars-backward "^<[\r\n")
12968 (skip-chars-backward "<[")
12969 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12970 (>= (match-end 0) pos)
12971 (throw 'exit t)))
12972 nil)))
12974 (defun org-get-repeat (&optional timestamp)
12975 "Check if there is a time-stamp with repeater in this entry.
12977 Return the repeater, as a string, or nil. Also return nil when
12978 this function is called before first heading.
12980 When optional argument TIMESTAMP is a string, extract the
12981 repeater from there instead."
12982 (save-match-data
12983 (cond (timestamp
12984 (and (string-match org-repeat-re timestamp)
12985 (match-string-no-properties 1 timestamp)))
12986 ((org-before-first-heading-p) nil)
12988 (save-excursion
12989 (org-back-to-heading t)
12990 (let ((end (org-entry-end-position)))
12991 (catch :repeat
12992 (while (re-search-forward org-repeat-re end t)
12993 (when (save-match-data (org-at-timestamp-p 'agenda))
12994 (throw :repeat (match-string-no-properties 1)))))))))))
12996 (defvar org-last-changed-timestamp)
12997 (defvar org-last-inserted-timestamp)
12998 (defvar org-log-post-message)
12999 (defvar org-log-note-purpose)
13000 (defvar org-log-note-how nil)
13001 (defvar org-log-note-extra)
13002 (defun org-auto-repeat-maybe (done-word)
13003 "Check if the current headline contains a repeated time-stamp.
13005 If yes, set TODO state back to what it was and change the base date
13006 of repeating deadline/scheduled time stamps to new date.
13008 This function is run automatically after each state change to a DONE state."
13009 (let* ((repeat (org-get-repeat))
13010 (aa (assoc org-last-state org-todo-kwd-alist))
13011 (interpret (nth 1 aa))
13012 (head (nth 2 aa))
13013 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13014 (msg "Entry repeats: ")
13015 (org-log-done nil)
13016 (org-todo-log-states nil)
13017 (end (copy-marker (org-entry-end-position))))
13018 (unwind-protect
13019 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13020 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13021 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13022 org-todo-repeat-to-state)))
13023 (org-todo (cond
13024 ((and to-state (member to-state org-todo-keywords-1))
13025 to-state)
13026 ((eq interpret 'type) org-last-state)
13027 (head)
13028 (t 'none))))
13029 (org-back-to-heading t)
13030 (org-add-planning-info nil nil 'closed)
13031 ;; When `org-log-repeat' is non-nil or entry contains
13032 ;; a clock, set LAST_REPEAT property.
13033 (when (or org-log-repeat
13034 (catch :clock
13035 (save-excursion
13036 (while (re-search-forward org-clock-line-re end t)
13037 (when (org-at-clock-log-p) (throw :clock t))))))
13038 (org-entry-put nil "LAST_REPEAT" (format-time-string
13039 (org-time-stamp-format t t)
13040 (current-time))))
13041 (when org-log-repeat
13042 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13043 (memq 'org-add-log-note post-command-hook))
13044 ;; We are already setup for some record.
13045 (when (eq org-log-repeat 'note)
13046 ;; Make sure we take a note, not only a time stamp.
13047 (setq org-log-note-how 'note))
13048 ;; Set up for taking a record.
13049 (org-add-log-setup 'state
13050 (or done-word (car org-done-keywords))
13051 org-last-state
13052 org-log-repeat)))
13053 (let ((planning-re (regexp-opt
13054 (list org-scheduled-string org-deadline-string))))
13055 (while (re-search-forward org-ts-regexp end t)
13056 (let* ((ts (match-string 0))
13057 (planning? (org-at-planning-p))
13058 (type (if (not planning?) "Plain:"
13059 (save-excursion
13060 (re-search-backward
13061 planning-re (line-beginning-position) t)
13062 (match-string 0)))))
13063 (cond
13064 ;; Ignore fake time-stamps (e.g., within comments).
13065 ((not (org-at-timestamp-p 'agenda)))
13066 ;; Time-stamps without a repeater are usually
13067 ;; skipped. However, a SCHEDULED time-stamp without
13068 ;; one is removed, as they are no longer relevant.
13069 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13070 ts))
13071 (when (equal type org-scheduled-string)
13072 (org-remove-timestamp-with-keyword type)))
13074 (let ((n (string-to-number (match-string 2 ts)))
13075 (what (match-string 3 ts)))
13076 (when (equal what "w") (setq n (* n 7) what "d"))
13077 (when (and (equal what "h")
13078 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13079 ts)))
13080 (user-error
13081 "Cannot repeat in Repeat in %d hour(s) because no hour \
13082 has been set"
13084 ;; Preparation, see if we need to modify the start
13085 ;; date for the change.
13086 (when (match-end 1)
13087 (let ((time (save-match-data
13088 (org-time-string-to-time ts))))
13089 (cond
13090 ((equal (match-string 1 ts) ".")
13091 ;; Shift starting date to today
13092 (org-timestamp-change
13093 (- (org-today) (time-to-days time))
13094 'day))
13095 ((equal (match-string 1 ts) "+")
13096 (let ((nshiftmax 10)
13097 (nshift 0))
13098 (while (or (= nshift 0)
13099 (not (time-less-p (current-time) time)))
13100 (when (= (cl-incf nshift) nshiftmax)
13101 (or (y-or-n-p
13102 (format "%d repeater intervals were not \
13103 enough to shift date past today. Continue? "
13104 nshift))
13105 (user-error "Abort")))
13106 (org-timestamp-change n (cdr (assoc what whata)))
13107 (org-in-regexp org-ts-regexp3)
13108 (setq ts (match-string 1))
13109 (setq time
13110 (save-match-data
13111 (org-time-string-to-time ts)))))
13112 (org-timestamp-change (- n) (cdr (assoc what whata)))
13113 ;; Rematch, so that we have everything in place
13114 ;; for the real shift.
13115 (org-in-regexp org-ts-regexp3)
13116 (setq ts (match-string 1))
13117 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13118 ts)))))
13119 (save-excursion
13120 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13121 (setq msg
13122 (concat
13123 msg type " " org-last-changed-timestamp " "))))))))
13124 (setq org-log-post-message msg)
13125 (message "%s" msg))
13126 (set-marker end nil))))
13128 (defun org-show-todo-tree (arg)
13129 "Make a compact tree which shows all headlines marked with TODO.
13130 The tree will show the lines where the regexp matches, and all higher
13131 headlines above the match.
13132 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13133 With a numeric prefix N, construct a sparse tree for the Nth element
13134 of `org-todo-keywords-1'."
13135 (interactive "P")
13136 (let ((case-fold-search nil)
13137 (kwd-re
13138 (cond ((null arg) org-not-done-regexp)
13139 ((equal arg '(4))
13140 (let ((kwd
13141 (completing-read "Keyword (or KWD1|KWD2|...): "
13142 (mapcar #'list org-todo-keywords-1))))
13143 (concat "\\("
13144 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13145 "\\)\\>")))
13146 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13147 (regexp-quote (nth (1- (prefix-numeric-value arg))
13148 org-todo-keywords-1)))
13149 (t (user-error "Invalid prefix argument: %s" arg)))))
13150 (message "%d TODO entries found"
13151 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13153 (defun org--deadline-or-schedule (arg type time)
13154 "Insert DEADLINE or SCHEDULE information in current entry.
13155 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13156 `org-schedule' for information about ARG and TIME arguments."
13157 (let* ((deadline? (eq type 'deadline))
13158 (keyword (if deadline? org-deadline-string org-scheduled-string))
13159 (log (if deadline? org-log-redeadline org-log-reschedule))
13160 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13161 (old-date-time (and old-date (org-time-string-to-time old-date)))
13162 ;; Save repeater cookie from either TIME or current scheduled
13163 ;; time stamp. We are going to insert it back at the end of
13164 ;; the process.
13165 (repeater (or (and (org-string-nw-p time)
13166 ;; We use `org-repeat-re' because we need
13167 ;; to tell the difference between a real
13168 ;; repeater and a time delta, e.g. "+2d".
13169 (string-match org-repeat-re time)
13170 (match-string 1 time))
13171 (and (org-string-nw-p old-date)
13172 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13173 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13174 old-date)
13175 (match-string 1 old-date)))))
13176 (pcase arg
13177 (`(4)
13178 (when (and old-date log)
13179 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13180 nil old-date log))
13181 (org-remove-timestamp-with-keyword keyword)
13182 (message (if deadline? "Item no longer has a deadline."
13183 "Item is no longer scheduled.")))
13184 (`(16)
13185 (save-excursion
13186 (org-back-to-heading t)
13187 (let ((regexp (if deadline? org-deadline-time-regexp
13188 org-scheduled-time-regexp)))
13189 (if (not (re-search-forward regexp (line-end-position 2) t))
13190 (user-error (if deadline? "No deadline information to update"
13191 "No scheduled information to update"))
13192 (let* ((rpl0 (match-string 1))
13193 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13194 (msg (if deadline? "Warn starting from" "Delay until")))
13195 (replace-match
13196 (concat keyword
13197 " <" rpl
13198 (format " -%dd"
13199 (abs (- (time-to-days
13200 (save-match-data
13201 (org-read-date
13202 nil t nil msg old-date-time)))
13203 (time-to-days old-date-time))))
13204 ">") t t))))))
13206 (org-add-planning-info type time 'closed)
13207 (when (and old-date
13209 (not (equal old-date org-last-inserted-timestamp)))
13210 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13211 org-last-inserted-timestamp
13212 old-date
13213 log))
13214 (when repeater
13215 (save-excursion
13216 (org-back-to-heading t)
13217 (when (re-search-forward
13218 (concat keyword " " org-last-inserted-timestamp)
13219 (line-end-position 2)
13221 (goto-char (1- (match-end 0)))
13222 (insert " " repeater)
13223 (setq org-last-inserted-timestamp
13224 (concat (substring org-last-inserted-timestamp 0 -1)
13225 " " repeater
13226 (substring org-last-inserted-timestamp -1))))))
13227 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13228 org-last-inserted-timestamp)))))
13230 (defun org-deadline (arg &optional time)
13231 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13232 With one universal prefix argument, remove any deadline from the item.
13233 With two universal prefix arguments, prompt for a warning delay.
13234 With argument TIME, set the deadline at the corresponding date. TIME
13235 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13236 (interactive "P")
13237 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13238 (org-map-entries
13239 (lambda () (org--deadline-or-schedule arg 'deadline time))
13241 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13242 'region-start-level
13243 'region)
13244 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13245 (org--deadline-or-schedule arg 'deadline time)))
13247 (defun org-schedule (arg &optional time)
13248 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13249 With one universal prefix argument, remove any scheduling date from the item.
13250 With two universal prefix arguments, prompt for a delay cookie.
13251 With argument TIME, scheduled at the corresponding date. TIME can
13252 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13253 (interactive "P")
13254 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13255 (org-map-entries
13256 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13258 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13259 'region-start-level
13260 'region)
13261 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13262 (org--deadline-or-schedule arg 'scheduled time)))
13264 (defun org-get-scheduled-time (pom &optional inherit)
13265 "Get the scheduled time as a time tuple, of a format suitable
13266 for calling org-schedule with, or if there is no scheduling,
13267 returns nil."
13268 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13269 (when time
13270 (apply 'encode-time (org-parse-time-string time)))))
13272 (defun org-get-deadline-time (pom &optional inherit)
13273 "Get the deadline as a time tuple, of a format suitable for
13274 calling org-deadline with, or if there is no scheduling, returns
13275 nil."
13276 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13277 (when time
13278 (apply 'encode-time (org-parse-time-string time)))))
13280 (defun org-remove-timestamp-with-keyword (keyword)
13281 "Remove all time stamps with KEYWORD in the current entry."
13282 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13283 beg)
13284 (save-excursion
13285 (org-back-to-heading t)
13286 (setq beg (point))
13287 (outline-next-heading)
13288 (while (re-search-backward re beg t)
13289 (replace-match "")
13290 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13291 (equal (char-before) ?\ ))
13292 (backward-delete-char 1)
13293 (when (string-match "^[ \t]*$" (buffer-substring
13294 (point-at-bol) (point-at-eol)))
13295 (delete-region (point-at-bol)
13296 (min (point-max) (1+ (point-at-eol))))))))))
13298 (defvar org-time-was-given) ; dynamically scoped parameter
13299 (defvar org-end-time-was-given) ; dynamically scoped parameter
13301 (defun org-at-planning-p ()
13302 "Non-nil when point is on a planning info line."
13303 ;; This is as accurate and faster than `org-element-at-point' since
13304 ;; planning info location is fixed in the section.
13305 (org-with-wide-buffer
13306 (beginning-of-line)
13307 (and (looking-at-p org-planning-line-re)
13308 (eq (point)
13309 (ignore-errors
13310 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13311 (org-back-to-heading t)
13312 (org-with-limited-levels (org-back-to-heading t)))
13313 (line-beginning-position 2))))))
13315 (defun org-add-planning-info (what &optional time &rest remove)
13316 "Insert new timestamp with keyword in the planning line.
13317 WHAT indicates what kind of time stamp to add. It is a symbol
13318 among `closed', `deadline', `scheduled' and nil. TIME indicates
13319 the time to use. If none is given, the user is prompted for
13320 a date. REMOVE indicates what kind of entries to remove. An old
13321 WHAT entry will also be removed."
13322 (let (org-time-was-given org-end-time-was-given default-time default-input)
13323 (catch 'exit
13324 (when (and (memq what '(scheduled deadline))
13325 (or (not time)
13326 (and (stringp time)
13327 (string-match "^[-+]+[0-9]" time))))
13328 ;; Try to get a default date/time from existing timestamp
13329 (save-excursion
13330 (org-back-to-heading t)
13331 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13332 (when (re-search-forward (if (eq what 'scheduled)
13333 org-scheduled-time-regexp
13334 org-deadline-time-regexp)
13335 end t)
13336 (setq ts (match-string 1)
13337 default-time (apply 'encode-time (org-parse-time-string ts))
13338 default-input (and ts (org-get-compact-tod ts)))))))
13339 (when what
13340 (setq time
13341 (if (stringp time)
13342 ;; This is a string (relative or absolute), set
13343 ;; proper date.
13344 (apply #'encode-time
13345 (org-read-date-analyze
13346 time default-time (decode-time default-time)))
13347 ;; If necessary, get the time from the user
13348 (or time (org-read-date nil 'to-time nil nil
13349 default-time default-input)))))
13351 (org-with-wide-buffer
13352 (org-back-to-heading t)
13353 (forward-line)
13354 (unless (bolp) (insert "\n"))
13355 (cond ((looking-at-p org-planning-line-re)
13356 ;; Move to current indentation.
13357 (skip-chars-forward " \t")
13358 ;; Check if we have to remove something.
13359 (dolist (type (if what (cons what remove) remove))
13360 (save-excursion
13361 (when (re-search-forward
13362 (cl-case type
13363 (closed org-closed-time-regexp)
13364 (deadline org-deadline-time-regexp)
13365 (scheduled org-scheduled-time-regexp)
13366 (otherwise
13367 (error "Invalid planning type: %s" type)))
13368 (line-end-position) t)
13369 ;; Delete until next keyword or end of line.
13370 (delete-region
13371 (match-beginning 0)
13372 (if (re-search-forward org-keyword-time-not-clock-regexp
13373 (line-end-position)
13375 (match-beginning 0)
13376 (line-end-position))))))
13377 ;; If there is nothing more to add and no more keyword
13378 ;; is left, remove the line completely.
13379 (if (and (looking-at-p "[ \t]*$") (not what))
13380 (delete-region (line-beginning-position)
13381 (line-beginning-position 2))
13382 ;; If we removed last keyword, do not leave trailing
13383 ;; white space at the end of line.
13384 (let ((p (point)))
13385 (save-excursion
13386 (end-of-line)
13387 (unless (= (skip-chars-backward " \t" p) 0)
13388 (delete-region (point) (line-end-position)))))))
13389 ((not what) (throw 'exit nil)) ; Nothing to do.
13390 (t (insert-before-markers "\n")
13391 (backward-char 1)
13392 (when org-adapt-indentation
13393 (indent-to-column (1+ (org-outline-level))))))
13394 (when what
13395 ;; Insert planning keyword.
13396 (insert (cl-case what
13397 (closed org-closed-string)
13398 (deadline org-deadline-string)
13399 (scheduled org-scheduled-string)
13400 (otherwise (error "Invalid planning type: %s" what)))
13401 " ")
13402 ;; Insert associated timestamp.
13403 (let ((ts (org-insert-time-stamp
13404 time
13405 (or org-time-was-given
13406 (and (eq what 'closed) org-log-done-with-time))
13407 (eq what 'closed)
13408 nil nil (list org-end-time-was-given))))
13409 (unless (eolp) (insert " "))
13410 ts))))))
13412 (defvar org-log-note-marker (make-marker)
13413 "Marker pointing at the entry where the note is to be inserted.")
13414 (defvar org-log-note-purpose nil)
13415 (defvar org-log-note-state nil)
13416 (defvar org-log-note-previous-state nil)
13417 (defvar org-log-note-extra nil)
13418 (defvar org-log-note-window-configuration nil)
13419 (defvar org-log-note-return-to (make-marker))
13420 (defvar org-log-note-effective-time nil
13421 "Remembered current time so that dynamically scoped
13422 `org-extend-today-until' affects timestamps in state change log")
13424 (defvar org-log-post-message nil
13425 "Message to be displayed after a log note has been stored.
13426 The auto-repeater uses this.")
13428 (defun org-add-note ()
13429 "Add a note to the current entry.
13430 This is done in the same way as adding a state change note."
13431 (interactive)
13432 (org-add-log-setup 'note))
13434 (defun org-log-beginning (&optional create)
13435 "Return expected start of log notes in current entry.
13436 When optional argument CREATE is non-nil, the function creates
13437 a drawer to store notes, if necessary. Returned position ignores
13438 narrowing."
13439 (org-with-wide-buffer
13440 (let ((drawer (org-log-into-drawer)))
13441 (cond
13442 (drawer
13443 (org-end-of-meta-data)
13444 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13445 (end (if (org-at-heading-p) (point)
13446 (save-excursion (outline-next-heading) (point))))
13447 (case-fold-search t))
13448 (catch 'exit
13449 ;; Try to find existing drawer.
13450 (while (re-search-forward regexp end t)
13451 (let ((element (org-element-at-point)))
13452 (when (eq (org-element-type element) 'drawer)
13453 (let ((cend (org-element-property :contents-end element)))
13454 (when (and (not org-log-states-order-reversed) cend)
13455 (goto-char cend)))
13456 (throw 'exit nil))))
13457 ;; No drawer found. Create one, if permitted.
13458 (when create
13459 (unless (bolp) (insert "\n"))
13460 (let ((beg (point)))
13461 (insert ":" drawer ":\n:END:\n")
13462 (org-indent-region beg (point)))
13463 (end-of-line -1)))))
13465 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13466 (skip-chars-forward " \t\n")
13467 (beginning-of-line)
13468 (unless org-log-states-order-reversed
13469 (org-skip-over-state-notes)
13470 (skip-chars-backward " \t\n")
13471 (forward-line)))))
13472 (if (bolp) (point) (line-beginning-position 2))))
13474 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13475 "Set up the post command hook to take a note.
13476 If this is about to TODO state change, the new state is expected in STATE.
13477 HOW is an indicator what kind of note should be created.
13478 EXTRA is additional text that will be inserted into the notes buffer."
13479 (move-marker org-log-note-marker (point))
13480 (setq org-log-note-purpose purpose
13481 org-log-note-state state
13482 org-log-note-previous-state prev-state
13483 org-log-note-how how
13484 org-log-note-extra extra
13485 org-log-note-effective-time (org-current-effective-time))
13486 (add-hook 'post-command-hook 'org-add-log-note 'append))
13488 (defun org-skip-over-state-notes ()
13489 "Skip past the list of State notes in an entry."
13490 (when (ignore-errors (goto-char (org-in-item-p)))
13491 (let* ((struct (org-list-struct))
13492 (prevs (org-list-prevs-alist struct))
13493 (regexp
13494 (concat "[ \t]*- +"
13495 (replace-regexp-in-string
13496 " +" " +"
13497 (org-replace-escapes
13498 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13499 `(("%d" . ,org-ts-regexp-inactive)
13500 ("%D" . ,org-ts-regexp)
13501 ("%s" . "\"\\S-+\"")
13502 ("%S" . "\"\\S-+\"")
13503 ("%t" . ,org-ts-regexp-inactive)
13504 ("%T" . ,org-ts-regexp)
13505 ("%u" . ".*?")
13506 ("%U" . ".*?")))))))
13507 (while (looking-at-p regexp)
13508 (goto-char (or (org-list-get-next-item (point) struct prevs)
13509 (org-list-get-item-end (point) struct)))))))
13511 (defun org-add-log-note (&optional _purpose)
13512 "Pop up a window for taking a note, and add this note later."
13513 (remove-hook 'post-command-hook 'org-add-log-note)
13514 (setq org-log-note-window-configuration (current-window-configuration))
13515 (delete-other-windows)
13516 (move-marker org-log-note-return-to (point))
13517 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13518 (goto-char org-log-note-marker)
13519 (org-switch-to-buffer-other-window "*Org Note*")
13520 (erase-buffer)
13521 (if (memq org-log-note-how '(time state))
13522 (org-store-log-note)
13523 (let ((org-inhibit-startup t)) (org-mode))
13524 (insert (format "# Insert note for %s.
13525 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13526 (cond
13527 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13528 ((eq org-log-note-purpose 'done) "closed todo item")
13529 ((eq org-log-note-purpose 'state)
13530 (format "state change from \"%s\" to \"%s\""
13531 (or org-log-note-previous-state "")
13532 (or org-log-note-state "")))
13533 ((eq org-log-note-purpose 'reschedule)
13534 "rescheduling")
13535 ((eq org-log-note-purpose 'delschedule)
13536 "no longer scheduled")
13537 ((eq org-log-note-purpose 'redeadline)
13538 "changing deadline")
13539 ((eq org-log-note-purpose 'deldeadline)
13540 "removing deadline")
13541 ((eq org-log-note-purpose 'refile)
13542 "refiling")
13543 ((eq org-log-note-purpose 'note)
13544 "this entry")
13545 (t (error "This should not happen")))))
13546 (when org-log-note-extra (insert org-log-note-extra))
13547 (setq-local org-finish-function 'org-store-log-note)
13548 (run-hooks 'org-log-buffer-setup-hook)))
13550 (defvar org-note-abort nil) ; dynamically scoped
13551 (defun org-store-log-note ()
13552 "Finish taking a log note, and insert it to where it belongs."
13553 (let ((txt (prog1 (buffer-string)
13554 (kill-buffer)))
13555 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13556 lines)
13557 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13558 (setq txt (replace-match "" t t txt)))
13559 (when (string-match "\\s-+\\'" txt)
13560 (setq txt (replace-match "" t t txt)))
13561 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13562 (when (org-string-nw-p note)
13563 (setq note
13564 (org-replace-escapes
13565 note
13566 (list (cons "%u" (user-login-name))
13567 (cons "%U" user-full-name)
13568 (cons "%t" (format-time-string
13569 (org-time-stamp-format 'long 'inactive)
13570 org-log-note-effective-time))
13571 (cons "%T" (format-time-string
13572 (org-time-stamp-format 'long nil)
13573 org-log-note-effective-time))
13574 (cons "%d" (format-time-string
13575 (org-time-stamp-format nil 'inactive)
13576 org-log-note-effective-time))
13577 (cons "%D" (format-time-string
13578 (org-time-stamp-format nil nil)
13579 org-log-note-effective-time))
13580 (cons "%s" (cond
13581 ((not org-log-note-state) "")
13582 ((string-match-p org-ts-regexp
13583 org-log-note-state)
13584 (format "\"[%s]\""
13585 (substring org-log-note-state 1 -1)))
13586 (t (format "\"%s\"" org-log-note-state))))
13587 (cons "%S"
13588 (cond
13589 ((not org-log-note-previous-state) "")
13590 ((string-match-p org-ts-regexp
13591 org-log-note-previous-state)
13592 (format "\"[%s]\""
13593 (substring
13594 org-log-note-previous-state 1 -1)))
13595 (t (format "\"%s\""
13596 org-log-note-previous-state)))))))
13597 (when lines (setq note (concat note " \\\\")))
13598 (push note lines))
13599 (when (and lines (not org-note-abort))
13600 (with-current-buffer (marker-buffer org-log-note-marker)
13601 (org-with-wide-buffer
13602 ;; Find location for the new note.
13603 (goto-char org-log-note-marker)
13604 (set-marker org-log-note-marker nil)
13605 ;; Note associated to a clock is to be located right after
13606 ;; the clock. Do not move point.
13607 (unless (eq org-log-note-purpose 'clock-out)
13608 (goto-char (org-log-beginning t)))
13609 ;; Make sure point is at the beginning of an empty line.
13610 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13611 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13612 ;; In an existing list, add a new item at the top level.
13613 ;; Otherwise, indent line like a regular one.
13614 (let ((itemp (org-in-item-p)))
13615 (if itemp
13616 (indent-line-to
13617 (let ((struct (save-excursion
13618 (goto-char itemp) (org-list-struct))))
13619 (org-list-get-ind (org-list-get-top-point struct) struct)))
13620 (org-indent-line)))
13621 (insert (org-list-bullet-string "-") (pop lines))
13622 (let ((ind (org-list-item-body-column (line-beginning-position))))
13623 (dolist (line lines)
13624 (insert "\n")
13625 (indent-line-to ind)
13626 (insert line)))
13627 (message "Note stored")
13628 (org-back-to-heading t)
13629 (org-cycle-hide-drawers 'children))
13630 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13631 ;; from within `org-add-log-note' because `buffer-undo-list'
13632 ;; is then modified outside of `org-with-remote-undo'.
13633 (when (eq this-command 'org-agenda-todo)
13634 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13635 ;; Don't add undo information when called from `org-agenda-todo'.
13636 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13637 (set-window-configuration org-log-note-window-configuration)
13638 (with-current-buffer (marker-buffer org-log-note-return-to)
13639 (goto-char org-log-note-return-to))
13640 (move-marker org-log-note-return-to nil)
13641 (when org-log-post-message (message "%s" org-log-post-message))))
13643 (defun org-remove-empty-drawer-at (pos)
13644 "Remove an empty drawer at position POS.
13645 POS may also be a marker."
13646 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13647 (org-with-wide-buffer
13648 (goto-char pos)
13649 (let ((drawer (org-element-at-point)))
13650 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13651 (not (org-element-property :contents-begin drawer)))
13652 (delete-region (org-element-property :begin drawer)
13653 (progn (goto-char (org-element-property :end drawer))
13654 (skip-chars-backward " \r\t\n")
13655 (forward-line)
13656 (point))))))))
13658 (defvar org-ts-type nil)
13659 (defun org-sparse-tree (&optional arg type)
13660 "Create a sparse tree, prompt for the details.
13661 This command can create sparse trees. You first need to select the type
13662 of match used to create the tree:
13664 t Show all TODO entries.
13665 T Show entries with a specific TODO keyword.
13666 m Show entries selected by a tags/property match.
13667 p Enter a property name and its value (both with completion on existing
13668 names/values) and show entries with that property.
13669 r Show entries matching a regular expression (`/' can be used as well).
13670 b Show deadlines and scheduled items before a date.
13671 a Show deadlines and scheduled items after a date.
13672 d Show deadlines due within `org-deadline-warning-days'.
13673 D Show deadlines and scheduled items between a date range."
13674 (interactive "P")
13675 (setq type (or type org-sparse-tree-default-date-type))
13676 (setq org-ts-type type)
13677 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13678 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13679 \[c]ycle through date types: %s"
13680 (cl-case type
13681 (all "all timestamps")
13682 (scheduled "only scheduled")
13683 (deadline "only deadline")
13684 (active "only active timestamps")
13685 (inactive "only inactive timestamps")
13686 (closed "with a closed time-stamp")
13687 (otherwise "scheduled/deadline")))
13688 (let ((answer (read-char-exclusive)))
13689 (cl-case answer
13691 (org-sparse-tree
13693 (cadr
13694 (memq type '(nil all scheduled deadline active inactive closed)))))
13695 (?d (call-interactively 'org-check-deadlines))
13696 (?b (call-interactively 'org-check-before-date))
13697 (?a (call-interactively 'org-check-after-date))
13698 (?D (call-interactively 'org-check-dates-range))
13699 (?t (call-interactively 'org-show-todo-tree))
13700 (?T (org-show-todo-tree '(4)))
13701 (?m (call-interactively 'org-match-sparse-tree))
13702 ((?p ?P)
13703 (let* ((kwd (completing-read
13704 "Property: " (mapcar #'list (org-buffer-property-keys))))
13705 (value (completing-read
13706 "Value: " (mapcar #'list (org-property-values kwd)))))
13707 (unless (string-match "\\`{.*}\\'" value)
13708 (setq value (concat "\"" value "\"")))
13709 (org-match-sparse-tree arg (concat kwd "=" value))))
13710 ((?r ?R ?/) (call-interactively 'org-occur))
13711 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13713 (defvar-local org-occur-highlights nil
13714 "List of overlays used for occur matches.")
13715 (defvar-local org-occur-parameters nil
13716 "Parameters of the active org-occur calls.
13717 This is a list, each call to org-occur pushes as cons cell,
13718 containing the regular expression and the callback, onto the list.
13719 The list can contain several entries if `org-occur' has been called
13720 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13721 will only contain one set of parameters. When the highlights are
13722 removed (for example with `C-c C-c', or with the next edit (depending
13723 on `org-remove-highlights-with-change'), this variable is emptied
13724 as well.")
13726 (defun org-occur (regexp &optional keep-previous callback)
13727 "Make a compact tree which shows all matches of REGEXP.
13729 The tree will show the lines where the regexp matches, and any other context
13730 defined in `org-show-context-detail', which see.
13732 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13733 done by a previous call to `org-occur' will be kept, to allow stacking of
13734 calls to this command.
13736 Optional argument CALLBACK can be a function of no argument. In this case,
13737 it is called with point at the end of the match, match data being set
13738 accordingly. Current match is shown only if the return value is non-nil.
13739 The function must neither move point nor alter narrowing."
13740 (interactive "sRegexp: \nP")
13741 (when (equal regexp "")
13742 (user-error "Regexp cannot be empty"))
13743 (unless keep-previous
13744 (org-remove-occur-highlights nil nil t))
13745 (push (cons regexp callback) org-occur-parameters)
13746 (let ((cnt 0))
13747 (save-excursion
13748 (goto-char (point-min))
13749 (when (or (not keep-previous) ; do not want to keep
13750 (not org-occur-highlights)) ; no previous matches
13751 ;; hide everything
13752 (org-overview))
13753 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13754 (isearch-no-upper-case-p regexp t)
13755 org-occur-case-fold-search)))
13756 (while (re-search-forward regexp nil t)
13757 (when (or (not callback)
13758 (save-match-data (funcall callback)))
13759 (setq cnt (1+ cnt))
13760 (when org-highlight-sparse-tree-matches
13761 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13762 (org-show-context 'occur-tree)))))
13763 (when org-remove-highlights-with-change
13764 (add-hook 'before-change-functions 'org-remove-occur-highlights
13765 nil 'local))
13766 (unless org-sparse-tree-open-archived-trees
13767 (org-hide-archived-subtrees (point-min) (point-max)))
13768 (run-hooks 'org-occur-hook)
13769 (when (called-interactively-p 'interactive)
13770 (message "%d match(es) for regexp %s" cnt regexp))
13771 cnt))
13773 (defun org-occur-next-match (&optional n _reset)
13774 "Function for `next-error-function' to find sparse tree matches.
13775 N is the number of matches to move, when negative move backwards.
13776 This function always goes back to the starting point when no
13777 match is found."
13778 (let* ((limit (if (< n 0) (point-min) (point-max)))
13779 (search-func (if (< n 0)
13780 'previous-single-char-property-change
13781 'next-single-char-property-change))
13782 (n (abs n))
13783 (pos (point))
13785 (catch 'exit
13786 (while (setq p1 (funcall search-func (point) 'org-type))
13787 (when (equal p1 limit)
13788 (goto-char pos)
13789 (user-error "No more matches"))
13790 (when (equal (get-char-property p1 'org-type) 'org-occur)
13791 (setq n (1- n))
13792 (when (= n 0)
13793 (goto-char p1)
13794 (throw 'exit (point))))
13795 (goto-char p1))
13796 (goto-char p1)
13797 (user-error "No more matches"))))
13799 (defun org-show-context (&optional key)
13800 "Make sure point and context are visible.
13801 Optional argument KEY, when non-nil, is a symbol. See
13802 `org-show-context-detail' for allowed values and how much is to
13803 be shown."
13804 (org-show-set-visibility
13805 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13806 ((cdr (assq key org-show-context-detail)))
13807 (t (cdr (assq 'default org-show-context-detail))))))
13809 (defun org-show-set-visibility (detail)
13810 "Set visibility around point according to DETAIL.
13811 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13812 `tree', `canonical' or t. See `org-show-context-detail' for more
13813 information."
13814 ;; Show current heading and possibly its entry, following headline
13815 ;; or all children.
13816 (if (and (org-at-heading-p) (not (eq detail 'local)))
13817 (org-flag-heading nil)
13818 (org-show-entry)
13819 ;; If point is hidden within a drawer or a block, make sure to
13820 ;; expose it.
13821 (dolist (o (overlays-at (point)))
13822 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13823 (delete-overlay o)))
13824 (unless (org-before-first-heading-p)
13825 (org-with-limited-levels
13826 (cl-case detail
13827 ((tree canonical t) (org-show-children))
13828 ((nil minimal ancestors))
13829 (t (save-excursion
13830 (outline-next-heading)
13831 (org-flag-heading nil)))))))
13832 ;; Show all siblings.
13833 (when (eq detail 'lineage) (org-show-siblings))
13834 ;; Show ancestors, possibly with their children.
13835 (when (memq detail '(ancestors lineage tree canonical t))
13836 (save-excursion
13837 (while (org-up-heading-safe)
13838 (org-flag-heading nil)
13839 (when (memq detail '(canonical t)) (org-show-entry))
13840 (when (memq detail '(tree canonical t)) (org-show-children))))))
13842 (defvar org-reveal-start-hook nil
13843 "Hook run before revealing a location.")
13845 (defun org-reveal (&optional siblings)
13846 "Show current entry, hierarchy above it, and the following headline.
13848 This can be used to show a consistent set of context around
13849 locations exposed with `org-show-context'.
13851 With optional argument SIBLINGS, on each level of the hierarchy all
13852 siblings are shown. This repairs the tree structure to what it would
13853 look like when opened with hierarchical calls to `org-cycle'.
13855 With a \\[universal-argument] \\[universal-argument] prefix, \
13856 go to the parent and show the entire tree."
13857 (interactive "P")
13858 (run-hooks 'org-reveal-start-hook)
13859 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13860 ((equal siblings '(16))
13861 (save-excursion
13862 (when (org-up-heading-safe)
13863 (org-show-subtree)
13864 (run-hook-with-args 'org-cycle-hook 'subtree))))
13865 (t (org-show-set-visibility 'lineage))))
13867 (defun org-highlight-new-match (beg end)
13868 "Highlight from BEG to END and mark the highlight is an occur headline."
13869 (let ((ov (make-overlay beg end)))
13870 (overlay-put ov 'face 'secondary-selection)
13871 (overlay-put ov 'org-type 'org-occur)
13872 (push ov org-occur-highlights)))
13874 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13875 "Remove the occur highlights from the buffer.
13876 BEG and END are ignored. If NOREMOVE is nil, remove this function
13877 from the `before-change-functions' in the current buffer."
13878 (interactive)
13879 (unless org-inhibit-highlight-removal
13880 (mapc #'delete-overlay org-occur-highlights)
13881 (setq org-occur-highlights nil)
13882 (setq org-occur-parameters nil)
13883 (unless noremove
13884 (remove-hook 'before-change-functions
13885 'org-remove-occur-highlights 'local))))
13887 ;;;; Priorities
13889 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13890 "Regular expression matching the priority indicator.")
13892 (defvar org-remove-priority-next-time nil)
13894 (defun org-priority-up ()
13895 "Increase the priority of the current item."
13896 (interactive)
13897 (org-priority 'up))
13899 (defun org-priority-down ()
13900 "Decrease the priority of the current item."
13901 (interactive)
13902 (org-priority 'down))
13904 (defun org-priority (&optional action _show)
13905 "Change the priority of an item.
13906 ACTION can be `set', `up', `down', or a character."
13907 (interactive "P")
13908 (if (equal action '(4))
13909 (org-show-priority)
13910 (unless org-enable-priority-commands
13911 (user-error "Priority commands are disabled"))
13912 (setq action (or action 'set))
13913 (let (current new news have remove)
13914 (save-excursion
13915 (org-back-to-heading t)
13916 (when (looking-at org-priority-regexp)
13917 (setq current (string-to-char (match-string 2))
13918 have t))
13919 (cond
13920 ((eq action 'remove)
13921 (setq remove t new ?\ ))
13922 ((or (eq action 'set)
13923 (integerp action))
13924 (if (not (eq action 'set))
13925 (setq new action)
13926 (message "Priority %c-%c, SPC to remove: "
13927 org-highest-priority org-lowest-priority)
13928 (save-match-data
13929 (setq new (read-char-exclusive))))
13930 (when (and (= (upcase org-highest-priority) org-highest-priority)
13931 (= (upcase org-lowest-priority) org-lowest-priority))
13932 (setq new (upcase new)))
13933 (cond ((equal new ?\ ) (setq remove t))
13934 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13935 (user-error "Priority must be between `%c' and `%c'"
13936 org-highest-priority org-lowest-priority))))
13937 ((eq action 'up)
13938 (setq new (if have
13939 (1- current) ; normal cycling
13940 ;; last priority was empty
13941 (if (eq last-command this-command)
13942 org-lowest-priority ; wrap around empty to lowest
13943 ;; default
13944 (if org-priority-start-cycle-with-default
13945 org-default-priority
13946 (1- org-default-priority))))))
13947 ((eq action 'down)
13948 (setq new (if have
13949 (1+ current) ; normal cycling
13950 ;; last priority was empty
13951 (if (eq last-command this-command)
13952 org-highest-priority ; wrap around empty to highest
13953 ;; default
13954 (if org-priority-start-cycle-with-default
13955 org-default-priority
13956 (1+ org-default-priority))))))
13957 (t (user-error "Invalid action")))
13958 (when (or (< (upcase new) org-highest-priority)
13959 (> (upcase new) org-lowest-priority))
13960 (if (and (memq action '(up down))
13961 (not have) (not (eq last-command this-command)))
13962 ;; `new' is from default priority
13963 (error
13964 "The default can not be set, see `org-default-priority' why")
13965 ;; normal cycling: `new' is beyond highest/lowest priority
13966 ;; and is wrapped around to the empty priority
13967 (setq remove t)))
13968 (setq news (format "%c" new))
13969 (if have
13970 (if remove
13971 (replace-match "" t t nil 1)
13972 (replace-match news t t nil 2))
13973 (if remove
13974 (user-error "No priority cookie found in line")
13975 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13976 (if (match-end 2)
13977 (progn
13978 (goto-char (match-end 2))
13979 (insert " [#" news "]"))
13980 (goto-char (match-beginning 3))
13981 (insert "[#" news "] "))))
13982 (org-set-tags nil 'align))
13983 (if remove
13984 (message "Priority removed")
13985 (message "Priority of current item set to %s" news)))))
13987 (defun org-show-priority ()
13988 "Show the priority of the current item.
13989 This priority is composed of the main priority given with the [#A] cookies,
13990 and by additional input from the age of a schedules or deadline entry."
13991 (interactive)
13992 (let ((pri (if (eq major-mode 'org-agenda-mode)
13993 (org-get-at-bol 'priority)
13994 (save-excursion
13995 (save-match-data
13996 (beginning-of-line)
13997 (and (looking-at org-heading-regexp)
13998 (org-get-priority (match-string 0))))))))
13999 (message "Priority is %d" (if pri pri -1000))))
14001 (defun org-get-priority (s)
14002 "Find priority cookie and return priority."
14003 (save-match-data
14004 (if (functionp org-get-priority-function)
14005 (funcall org-get-priority-function)
14006 (if (not (string-match org-priority-regexp s))
14007 (* 1000 (- org-lowest-priority org-default-priority))
14008 (* 1000 (- org-lowest-priority
14009 (string-to-char (match-string 2 s))))))))
14011 ;;;; Tags
14013 (defvar org-agenda-archives-mode)
14014 (defvar org-map-continue-from nil
14015 "Position from where mapping should continue.
14016 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14018 (defvar org-scanner-tags nil
14019 "The current tag list while the tags scanner is running.")
14021 (defvar org-trust-scanner-tags nil
14022 "Should `org-get-tags-at' use the tags for the scanner.
14023 This is for internal dynamical scoping only.
14024 When this is non-nil, the function `org-get-tags-at' will return the value
14025 of `org-scanner-tags' instead of building the list by itself. This
14026 can lead to large speed-ups when the tags scanner is used in a file with
14027 many entries, and when the list of tags is retrieved, for example to
14028 obtain a list of properties. Building the tags list for each entry in such
14029 a file becomes an N^2 operation - but with this variable set, it scales
14030 as N.")
14032 (defvar org--matcher-tags-todo-only nil)
14034 (defun org-scan-tags (action matcher todo-only &optional start-level)
14035 "Scan headline tags with inheritance and produce output ACTION.
14037 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14038 or `agenda' to produce an entry list for an agenda view. It can also be
14039 a Lisp form or a function that should be called at each matched headline, in
14040 this case the return value is a list of all return values from these calls.
14042 MATCHER is a function accepting three arguments, returning
14043 a non-nil value whenever a given set of tags qualifies a headline
14044 for inclusion. See `org-make-tags-matcher' for more information.
14045 As a special case, it can also be set to t (respectively nil) in
14046 order to match all (respectively none) headline.
14048 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14049 included in the output.
14051 START-LEVEL can be a string with asterisks, reducing the scope to
14052 headlines matching this string."
14053 (require 'org-agenda)
14054 (let* ((re (concat "^"
14055 (if start-level
14056 ;; Get the correct level to match
14057 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14058 org-outline-regexp)
14059 " *\\(\\<\\("
14060 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14061 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14062 (props (list 'face 'default
14063 'done-face 'org-agenda-done
14064 'undone-face 'default
14065 'mouse-face 'highlight
14066 'org-not-done-regexp org-not-done-regexp
14067 'org-todo-regexp org-todo-regexp
14068 'org-complex-heading-regexp org-complex-heading-regexp
14069 'help-echo
14070 (format "mouse-2 or RET jump to org file %s"
14071 (abbreviate-file-name
14072 (or (buffer-file-name (buffer-base-buffer))
14073 (buffer-name (buffer-base-buffer)))))))
14074 (org-map-continue-from nil)
14075 lspos tags tags-list
14076 (tags-alist (list (cons 0 org-file-tags)))
14077 (llast 0) rtn rtn1 level category i txt
14078 todo marker entry priority
14079 ts-date ts-date-type ts-date-pair)
14080 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14081 (setq action (list 'lambda nil action)))
14082 (save-excursion
14083 (goto-char (point-min))
14084 (when (eq action 'sparse-tree)
14085 (org-overview)
14086 (org-remove-occur-highlights))
14087 (while (let (case-fold-search)
14088 (re-search-forward re nil t))
14089 (setq org-map-continue-from nil)
14090 (catch :skip
14091 (setq todo
14092 ;; TODO: is the 1-2 difference a bug?
14093 (when (match-end 1) (match-string-no-properties 2))
14094 tags (when (match-end 4) (match-string-no-properties 4)))
14095 (goto-char (setq lspos (match-beginning 0)))
14096 (setq level (org-reduced-level (org-outline-level))
14097 category (org-get-category))
14098 (when (eq action 'agenda)
14099 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14100 ts-date (car ts-date-pair)
14101 ts-date-type (cdr ts-date-pair)))
14102 (setq i llast llast level)
14103 ;; remove tag lists from same and sublevels
14104 (while (>= i level)
14105 (when (setq entry (assoc i tags-alist))
14106 (setq tags-alist (delete entry tags-alist)))
14107 (setq i (1- i)))
14108 ;; add the next tags
14109 (when tags
14110 (setq tags (org-split-string tags ":")
14111 tags-alist
14112 (cons (cons level tags) tags-alist)))
14113 ;; compile tags for current headline
14114 (setq tags-list
14115 (if org-use-tag-inheritance
14116 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14117 tags)
14118 org-scanner-tags tags-list)
14119 (when org-use-tag-inheritance
14120 (setcdr (car tags-alist)
14121 (mapcar (lambda (x)
14122 (setq x (copy-sequence x))
14123 (org-add-prop-inherited x))
14124 (cdar tags-alist))))
14125 (when (and tags org-use-tag-inheritance
14126 (or (not (eq t org-use-tag-inheritance))
14127 org-tags-exclude-from-inheritance))
14128 ;; Selective inheritance, remove uninherited ones.
14129 (setcdr (car tags-alist)
14130 (org-remove-uninherited-tags (cdar tags-alist))))
14131 (when (and
14133 ;; eval matcher only when the todo condition is OK
14134 (and (or (not todo-only) (member todo org-todo-keywords-1))
14135 (if (functionp matcher)
14136 (let ((case-fold-search t) (org-trust-scanner-tags t))
14137 (funcall matcher todo tags-list level))
14138 matcher))
14140 ;; Call the skipper, but return t if it does not
14141 ;; skip, so that the `and' form continues evaluating.
14142 (progn
14143 (unless (eq action 'sparse-tree) (org-agenda-skip))
14146 ;; Check if timestamps are deselecting this entry
14147 (or (not todo-only)
14148 (and (member todo org-todo-keywords-1)
14149 (or (not org-agenda-tags-todo-honor-ignore-options)
14150 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14152 ;; select this headline
14153 (cond
14154 ((eq action 'sparse-tree)
14155 (and org-highlight-sparse-tree-matches
14156 (org-get-heading) (match-end 0)
14157 (org-highlight-new-match
14158 (match-beginning 1) (match-end 1)))
14159 (org-show-context 'tags-tree))
14160 ((eq action 'agenda)
14161 (setq txt (org-agenda-format-item
14163 (concat
14164 (if (eq org-tags-match-list-sublevels 'indented)
14165 (make-string (1- level) ?.) "")
14166 (org-get-heading))
14167 (make-string level ?\s)
14168 category
14169 tags-list)
14170 priority (org-get-priority txt))
14171 (goto-char lspos)
14172 (setq marker (org-agenda-new-marker))
14173 (org-add-props txt props
14174 'org-marker marker 'org-hd-marker marker 'org-category category
14175 'todo-state todo
14176 'ts-date ts-date
14177 'priority priority
14178 'type (concat "tagsmatch" ts-date-type))
14179 (push txt rtn))
14180 ((functionp action)
14181 (setq org-map-continue-from nil)
14182 (save-excursion
14183 (setq rtn1 (funcall action))
14184 (push rtn1 rtn)))
14185 (t (user-error "Invalid action")))
14187 ;; if we are to skip sublevels, jump to end of subtree
14188 (unless org-tags-match-list-sublevels
14189 (org-end-of-subtree t)
14190 (backward-char 1))))
14191 ;; Get the correct position from where to continue
14192 (if org-map-continue-from
14193 (goto-char org-map-continue-from)
14194 (and (= (point) lspos) (end-of-line 1)))))
14195 (when (and (eq action 'sparse-tree)
14196 (not org-sparse-tree-open-archived-trees))
14197 (org-hide-archived-subtrees (point-min) (point-max)))
14198 (nreverse rtn)))
14200 (defun org-remove-uninherited-tags (tags)
14201 "Remove all tags that are not inherited from the list TAGS."
14202 (cond
14203 ((eq org-use-tag-inheritance t)
14204 (if org-tags-exclude-from-inheritance
14205 (org-delete-all org-tags-exclude-from-inheritance tags)
14206 tags))
14207 ((not org-use-tag-inheritance) nil)
14208 ((stringp org-use-tag-inheritance)
14209 (delq nil (mapcar
14210 (lambda (x)
14211 (if (and (string-match org-use-tag-inheritance x)
14212 (not (member x org-tags-exclude-from-inheritance)))
14213 x nil))
14214 tags)))
14215 ((listp org-use-tag-inheritance)
14216 (delq nil (mapcar
14217 (lambda (x)
14218 (if (member x org-use-tag-inheritance) x nil))
14219 tags)))))
14221 (defun org-match-sparse-tree (&optional todo-only match)
14222 "Create a sparse tree according to tags string MATCH.
14224 MATCH is a string with match syntax. It can contain a selection
14225 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14226 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14227 those. See the manual for details.
14229 If optional argument TODO-ONLY is non-nil, only select lines that
14230 are also TODO tasks."
14231 (interactive "P")
14232 (org-agenda-prepare-buffers (list (current-buffer)))
14233 (let ((org--matcher-tags-todo-only todo-only))
14234 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14235 org--matcher-tags-todo-only)))
14237 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14239 (defvar org-cached-props nil)
14240 (defun org-cached-entry-get (pom property)
14241 (if (or (eq t org-use-property-inheritance)
14242 (and (stringp org-use-property-inheritance)
14243 (let ((case-fold-search t))
14244 (string-match-p org-use-property-inheritance property)))
14245 (and (listp org-use-property-inheritance)
14246 (member-ignore-case property org-use-property-inheritance)))
14247 ;; Caching is not possible, check it directly.
14248 (org-entry-get pom property 'inherit)
14249 ;; Get all properties, so we can do complicated checks easily.
14250 (cdr (assoc-string property
14251 (or org-cached-props
14252 (setq org-cached-props (org-entry-properties pom)))
14253 t))))
14255 (defun org-global-tags-completion-table (&optional files)
14256 "Return the list of all tags in all agenda buffer/files.
14257 Optional FILES argument is a list of files which can be used
14258 instead of the agenda files."
14259 (save-excursion
14260 (org-uniquify
14261 (delq nil
14262 (apply #'append
14263 (mapcar
14264 (lambda (file)
14265 (set-buffer (find-file-noselect file))
14266 (mapcar (lambda (x)
14267 (and (stringp (car-safe x))
14268 (list (car-safe x))))
14269 (or org-current-tag-alist (org-get-buffer-tags))))
14270 (if (car-safe files) files
14271 (org-agenda-files))))))))
14273 (defun org-make-tags-matcher (match)
14274 "Create the TAGS/TODO matcher form for the selection string MATCH.
14276 Returns a cons of the selection string MATCH and a function
14277 implementing the matcher.
14279 The matcher is to be called at an Org entry, with point on the
14280 headline, and returns non-nil if the entry matches the selection
14281 string MATCH. It must be called with three arguments: the TODO
14282 keyword at the entry (or nil if none), the list of all tags at
14283 the entry including inherited ones and the reduced level of the
14284 headline. Additionally, the category of the entry, if any, must
14285 be specified as the text property `org-category' on the headline.
14287 This function sets the variable `org--matcher-tags-todo-only' to
14288 a non-nil value if the matcher restricts matching to TODO
14289 entries, otherwise it is not touched.
14291 See also `org-scan-tags'."
14292 (unless match
14293 ;; Get a new match request, with completion against the global
14294 ;; tags table and the local tags in current buffer.
14295 (let ((org-last-tags-completion-table
14296 (org-uniquify
14297 (delq nil (append (org-get-buffer-tags)
14298 (org-global-tags-completion-table))))))
14299 (setq match
14300 (completing-read
14301 "Match: "
14302 'org-tags-completion-function nil nil nil 'org-tags-history))))
14304 (let ((match0 match)
14305 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14306 (start 0)
14307 tagsmatch todomatch tagsmatcher todomatcher)
14309 ;; Expand group tags.
14310 (setq match (org-tags-expand match))
14312 ;; Check if there is a TODO part of this match, which would be the
14313 ;; part after a "/". To make sure that this slash is not part of
14314 ;; a property value to be matched against, we also check that
14315 ;; there is no / after that slash. First, find the last slash.
14316 (let ((s 0))
14317 (while (string-match "/+" match s)
14318 (setq start (match-beginning 0))
14319 (setq s (match-end 0))))
14320 (if (and (string-match "/+" match start)
14321 (not (string-match-p "\"" match start)))
14322 ;; Match contains also a TODO-matching request.
14323 (progn
14324 (setq tagsmatch (substring match 0 (match-beginning 0)))
14325 (setq todomatch (substring match (match-end 0)))
14326 (when (string-prefix-p "!" todomatch)
14327 (setq org--matcher-tags-todo-only t)
14328 (setq todomatch (substring todomatch 1)))
14329 (when (string-match "\\`\\s-*\\'" todomatch)
14330 (setq todomatch nil)))
14331 ;; Only matching tags.
14332 (setq tagsmatch match)
14333 (setq todomatch nil))
14335 ;; Make the tags matcher.
14336 (when (org-string-nw-p tagsmatch)
14337 (let ((orlist nil)
14338 (orterms (org-split-string tagsmatch "|"))
14339 term)
14340 (while (setq term (pop orterms))
14341 (while (and (equal (substring term -1) "\\") orterms)
14342 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14343 (while (string-match re term)
14344 (let* ((rest (substring term (match-end 0)))
14345 (minus (and (match-end 1)
14346 (equal (match-string 1 term) "-")))
14347 (tag (save-match-data
14348 (replace-regexp-in-string
14349 "\\\\-" "-" (match-string 2 term))))
14350 (regexp (eq (string-to-char tag) ?{))
14351 (levelp (match-end 4))
14352 (propp (match-end 5))
14354 (cond
14355 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14356 (levelp
14357 `(,(org-op-to-function (match-string 3 term))
14358 level
14359 ,(string-to-number (match-string 4 term))))
14360 (propp
14361 (let* ((gv (pcase (upcase (match-string 5 term))
14362 ("CATEGORY"
14363 '(get-text-property (point) 'org-category))
14364 ("TODO" 'todo)
14365 (p `(org-cached-entry-get nil ,p))))
14366 (pv (match-string 7 term))
14367 (regexp (eq (string-to-char pv) ?{))
14368 (strp (eq (string-to-char pv) ?\"))
14369 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14370 (po (org-op-to-function (match-string 6 term)
14371 (if timep 'time strp))))
14372 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14373 (when timep (setq pv (org-matcher-time pv)))
14374 (cond ((and regexp (eq po 'org<>))
14375 `(not (string-match ,pv (or ,gv ""))))
14376 (regexp `(string-match ,pv (or ,gv "")))
14377 (strp `(,po (or ,gv "") ,pv))
14379 `(,po
14380 (string-to-number (or ,gv ""))
14381 ,(string-to-number pv))))))
14382 (t `(member ,tag tags-list)))))
14383 (push (if minus `(not ,mm) mm) tagsmatcher)
14384 (setq term rest)))
14385 (push `(and ,@tagsmatcher) orlist)
14386 (setq tagsmatcher nil))
14387 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14389 ;; Make the TODO matcher.
14390 (when (org-string-nw-p todomatch)
14391 (let ((orlist nil))
14392 (dolist (term (org-split-string todomatch "|"))
14393 (while (string-match re term)
14394 (let* ((minus (and (match-end 1)
14395 (equal (match-string 1 term) "-")))
14396 (kwd (match-string 2 term))
14397 (regexp (eq (string-to-char kwd) ?{))
14398 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14399 `(equal todo ,kwd))))
14400 (push (if minus `(not ,mm) mm) todomatcher))
14401 (setq term (substring term (match-end 0))))
14402 (push (if (> (length todomatcher) 1)
14403 (cons 'and todomatcher)
14404 (car todomatcher))
14405 orlist)
14406 (setq todomatcher nil))
14407 (setq todomatcher (cons 'or orlist))))
14409 ;; Return the string and function of the matcher. If no
14410 ;; tags-specific or todo-specific matcher exists, match
14411 ;; everything.
14412 (let ((matcher (if (and tagsmatcher todomatcher)
14413 `(and ,tagsmatcher ,todomatcher)
14414 (or tagsmatcher todomatcher t))))
14415 (when org--matcher-tags-todo-only
14416 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14417 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14419 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14420 "Expand group tags in MATCH.
14422 This replaces every group tag in MATCH with a regexp tag search.
14423 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14424 will be replaced like this:
14426 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14427 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14428 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14430 Replacing by a regexp preserves the structure of the match.
14431 E.g., this expansion
14433 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14435 will match anything tagged with \"Lab\" and \"Home\", or tagged
14436 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14438 A group tag in MATCH can contain regular expressions of its own.
14439 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14440 will be replaced like this:
14442 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14444 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14445 assumed to be a single group tag, and the function will return
14446 the list of tags in this group.
14448 When DOWNCASE is non-nil, expand downcased TAGS."
14449 (if org-group-tags
14450 (let* ((case-fold-search t)
14451 (stable org-mode-syntax-table)
14452 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14453 (taggroups (if downcased
14454 (mapcar (lambda (tg) (mapcar #'downcase tg))
14455 taggroups)
14456 taggroups))
14457 (taggroups-keys (mapcar #'car taggroups))
14458 (return-match (if downcased (downcase match) match))
14459 (count 0)
14460 (work-already-expanded tags-already-expanded)
14461 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14462 ;; @ and _ are allowed as word-components in tags.
14463 (modify-syntax-entry ?@ "w" stable)
14464 (modify-syntax-entry ?_ "w" stable)
14465 ;; Temporarily replace regexp-expressions in the match-expression.
14466 (while (string-match "{.+?}" return-match)
14467 (cl-incf count)
14468 (push (match-string 0 return-match) regexps-in-match)
14469 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14470 (while (and taggroups-keys
14471 (with-syntax-table stable
14472 (string-match
14473 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14474 (regexp-opt taggroups-keys) "\\>\\)")
14475 return-match)))
14476 (let* ((dir (match-string 1 return-match))
14477 (tag (match-string 2 return-match))
14478 (tag (if downcased (downcase tag) tag)))
14479 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14480 (member tag work-already-expanded))
14481 (setq tags-in-group (assoc tag taggroups))
14482 (push tag work-already-expanded)
14483 ;; Recursively expand each tag in the group, if the tag hasn't
14484 ;; already been expanded. Restore the match-data after all recursive calls.
14485 (save-match-data
14486 (let (tags-expanded)
14487 (dolist (x (cdr tags-in-group))
14488 (if (and (member x taggroups-keys)
14489 (not (member x work-already-expanded)))
14490 (setq tags-expanded
14491 (delete-dups
14492 (append
14493 (org-tags-expand x t downcased
14494 work-already-expanded)
14495 tags-expanded)))
14496 (setq tags-expanded
14497 (append (list x) tags-expanded)))
14498 (setq work-already-expanded
14499 (delete-dups
14500 (append tags-expanded
14501 work-already-expanded))))
14502 (setq tags-in-group
14503 (delete-dups (cons (car tags-in-group)
14504 tags-expanded)))))
14505 ;; Filter tag-regexps from tags.
14506 (setq regexp-in-group-escaped
14507 (delq nil (mapcar (lambda (x)
14508 (if (stringp x)
14509 (and (equal "{" (substring x 0 1))
14510 (equal "}" (substring x -1))
14513 tags-in-group))
14514 regexp-in-group
14515 (mapcar (lambda (x)
14516 (substring x 1 -1))
14517 regexp-in-group-escaped)
14518 tags-in-group
14519 (delq nil (mapcar (lambda (x)
14520 (if (stringp x)
14521 (and (not (equal "{" (substring x 0 1)))
14522 (not (equal "}" (substring x -1)))
14525 tags-in-group)))
14526 ;; If single-as-list, do no more in the while-loop.
14527 (if (not single-as-list)
14528 (progn
14529 (when regexp-in-group
14530 (setq regexp-in-group
14531 (concat "\\|"
14532 (mapconcat 'identity regexp-in-group
14533 "\\|"))))
14534 (setq tags-in-group
14535 (concat dir
14536 "{\\<"
14537 (regexp-opt tags-in-group)
14538 "\\>"
14539 regexp-in-group
14540 "}"))
14541 (when (stringp tags-in-group)
14542 (org-add-props tags-in-group '(grouptag t)))
14543 (setq return-match
14544 (replace-match tags-in-group t t return-match)))
14545 (setq tags-in-group
14546 (append regexp-in-group-escaped tags-in-group))))
14547 (setq taggroups-keys (delete tag taggroups-keys))))
14548 ;; Add the regular expressions back into the match-expression again.
14549 (while regexps-in-match
14550 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14551 (pop regexps-in-match)
14552 return-match t t))
14553 (cl-decf count))
14554 (if single-as-list
14555 (if tags-in-group tags-in-group (list return-match))
14556 return-match))
14557 (if single-as-list
14558 (list (if downcased (downcase match) match))
14559 match)))
14561 (defun org-op-to-function (op &optional stringp)
14562 "Turn an operator into the appropriate function."
14563 (setq op
14564 (cond
14565 ((equal op "<" ) '(< string< org-time<))
14566 ((equal op ">" ) '(> org-string> org-time>))
14567 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14568 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14569 ((member op '("=" "==")) '(= string= org-time=))
14570 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14571 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14573 (defun org<> (a b) (not (= a b)))
14574 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14575 (defun org-string>= (a b) (not (string< a b)))
14576 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14577 (defun org-string<> (a b) (not (string= a b)))
14578 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14579 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14580 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14581 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14582 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14583 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14584 (defun org-2ft (s)
14585 "Convert S to a floating point time.
14586 If S is already a number, just return it. If it is a string, parse
14587 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14588 (cond
14589 ((numberp s) s)
14590 ((stringp s)
14591 (condition-case nil
14592 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14593 (error 0.)))
14594 (t 0.)))
14596 (defun org-time-today ()
14597 "Time in seconds today at 0:00.
14598 Returns the float number of seconds since the beginning of the
14599 epoch to the beginning of today (00:00)."
14600 (float-time (apply 'encode-time
14601 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14603 (defun org-matcher-time (s)
14604 "Interpret a time comparison value."
14605 (save-match-data
14606 (cond
14607 ((string= s "<now>") (float-time))
14608 ((string= s "<today>") (org-time-today))
14609 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14610 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14611 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14612 (+ (org-time-today)
14613 (* (string-to-number (match-string 1 s))
14614 (cdr (assoc (match-string 2 s)
14615 '(("d" . 86400.0) ("w" . 604800.0)
14616 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14617 (t (org-2ft s)))))
14619 (defun org-match-any-p (re list)
14620 "Does re match any element of list?"
14621 (setq list (mapcar (lambda (x) (string-match re x)) list))
14622 (delq nil list))
14624 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14625 (defvar org-tags-overlay (make-overlay 1 1))
14626 (delete-overlay org-tags-overlay)
14628 (defun org-get-local-tags-at (&optional pos)
14629 "Get a list of tags defined in the current headline."
14630 (org-get-tags-at pos 'local))
14632 (defun org-get-local-tags ()
14633 "Get a list of tags defined in the current headline."
14634 (org-get-tags-at nil 'local))
14636 (defun org-get-tags-at (&optional pos local)
14637 "Get a list of all headline tags applicable at POS.
14638 POS defaults to point. If tags are inherited, the list contains
14639 the targets in the same sequence as the headlines appear, i.e.
14640 the tags of the current headline come last.
14641 When LOCAL is non-nil, only return tags from the current headline,
14642 ignore inherited ones."
14643 (interactive)
14644 (if (and org-trust-scanner-tags
14645 (or (not pos) (equal pos (point)))
14646 (not local))
14647 org-scanner-tags
14648 (let (tags ltags lastpos parent)
14649 (save-excursion
14650 (save-restriction
14651 (widen)
14652 (goto-char (or pos (point)))
14653 (save-match-data
14654 (catch 'done
14655 (condition-case nil
14656 (progn
14657 (org-back-to-heading t)
14658 (while (not (equal lastpos (point)))
14659 (setq lastpos (point))
14660 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14661 (setq ltags (org-split-string
14662 (match-string-no-properties 1) ":"))
14663 (when parent
14664 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14665 (setq tags (append
14666 (if parent
14667 (org-remove-uninherited-tags ltags)
14668 ltags)
14669 tags)))
14670 (or org-use-tag-inheritance (throw 'done t))
14671 (when local (throw 'done t))
14672 (or (org-up-heading-safe) (error nil))
14673 (setq parent t)))
14674 (error nil)))))
14675 (if local
14676 tags
14677 (reverse (delete-dups
14678 (reverse (append
14679 (org-remove-uninherited-tags
14680 org-file-tags)
14681 tags)))))))))
14683 (defun org-add-prop-inherited (s)
14684 (add-text-properties 0 (length s) '(inherited t) s)
14687 (defun org-toggle-tag (tag &optional onoff)
14688 "Toggle the tag TAG for the current line.
14689 If ONOFF is `on' or `off', don't toggle but set to this state."
14690 (save-excursion
14691 (org-back-to-heading t)
14692 (let ((current
14693 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14694 (line-end-position) t)
14695 (let ((tags (match-string 1)))
14696 ;; Clear current tags.
14697 (replace-match "")
14698 ;; Reverse the tags list so any new tag is appended to
14699 ;; the current list of tags.
14700 (nreverse (org-split-string tags ":")))))
14701 res)
14702 (pcase onoff
14703 (`off (setq current (delete tag current)))
14704 ((or `on (guard (not (member tag current))))
14705 (setq res t)
14706 (cl-pushnew tag current :test #'equal))
14707 (_ (setq current (delete tag current))))
14708 (end-of-line)
14709 (if current
14710 (progn
14711 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14712 (org-set-tags nil t))
14713 (delete-horizontal-space))
14714 (run-hooks 'org-after-tags-change-hook)
14715 res)))
14717 (defun org--align-tags-here (to-col)
14718 "Align tags on the current headline to TO-COL.
14719 Assume point is on a headline."
14720 (let ((pos (point)))
14721 (beginning-of-line)
14722 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14723 (>= pos (match-beginning 2)))
14724 ;; No tags or point within tags: do not align.
14725 (goto-char pos)
14726 (goto-char (match-beginning 1))
14727 (let ((shift (max (- (if (>= to-col 0) to-col
14728 (- (abs to-col) (string-width (match-string 2))))
14729 (current-column))
14730 1)))
14731 (replace-match (make-string shift ?\s) nil nil nil 1)
14732 ;; Preserve initial position, if possible. In any case, stop
14733 ;; before tags.
14734 (when (< pos (point)) (goto-char pos))))))
14736 (defun org-set-tags-command (&optional arg just-align)
14737 "Call the set-tags command for the current entry."
14738 (interactive "P")
14739 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14740 (org-set-tags arg just-align)
14741 (save-excursion
14742 (unless (and (org-region-active-p)
14743 org-loop-over-headlines-in-active-region)
14744 (org-back-to-heading t))
14745 (org-set-tags arg just-align))))
14747 (defun org-set-tags-to (data)
14748 "Set the tags of the current entry to DATA, replacing the current tags.
14749 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14750 If DATA is nil or the empty string, any tags will be removed."
14751 (interactive "sTags: ")
14752 (setq data
14753 (cond
14754 ((eq data nil) "")
14755 ((equal data "") "")
14756 ((stringp data)
14757 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14758 ":"))
14759 ((listp data)
14760 (concat ":" (mapconcat 'identity data ":") ":"))))
14761 (when data
14762 (save-excursion
14763 (org-back-to-heading t)
14764 (when (let ((case-fold-search nil))
14765 (looking-at org-complex-heading-regexp))
14766 (if (match-end 5)
14767 (progn
14768 (goto-char (match-beginning 5))
14769 (insert data)
14770 (delete-region (point) (point-at-eol))
14771 (org-set-tags nil 'align))
14772 (goto-char (point-at-eol))
14773 (insert " " data)
14774 (org-set-tags nil 'align)))
14775 (beginning-of-line 1)
14776 (when (looking-at ".*?\\([ \t]+\\)$")
14777 (delete-region (match-beginning 1) (match-end 1))))))
14779 (defun org-align-all-tags ()
14780 "Align the tags in all headings."
14781 (interactive)
14782 (save-excursion
14783 (or (ignore-errors (org-back-to-heading t))
14784 (outline-next-heading))
14785 (if (org-at-heading-p)
14786 (org-set-tags t)
14787 (message "No headings"))))
14789 (defvar org-indent-indentation-per-level)
14790 (defun org-set-tags (&optional arg just-align)
14791 "Set the tags for the current headline.
14792 With prefix ARG, realign all tags in headings in the current buffer.
14793 When JUST-ALIGN is non-nil, only align tags."
14794 (interactive "P")
14795 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14796 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14797 'region-start-level
14798 'region))
14799 org-loop-over-headlines-in-active-region)
14800 (org-map-entries
14801 ;; We don't use ARG and JUST-ALIGN here because these args
14802 ;; are not useful when looping over headlines.
14803 #'org-set-tags
14804 org-loop-over-headlines-in-active-region
14806 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14807 (let ((org-setting-tags t))
14808 (if arg
14809 (save-excursion
14810 (goto-char (point-min))
14811 (while (re-search-forward org-outline-regexp-bol nil t)
14812 (org-set-tags nil t)
14813 (end-of-line))
14814 (message "All tags realigned to column %d" org-tags-column))
14815 (let* ((current (org-get-tags-string))
14816 (tags
14817 (if just-align current
14818 ;; Get a new set of tags from the user.
14819 (save-excursion
14820 (let* ((seen)
14821 (table
14822 (setq
14823 org-last-tags-completion-table
14824 ;; Uniquify tags in alists, yet preserve
14825 ;; structure (i.e., keywords).
14826 (delq nil
14827 (mapcar
14828 (lambda (pair)
14829 (let ((head (car pair)))
14830 (cond ((symbolp head) pair)
14831 ((member head seen) nil)
14832 (t (push head seen)
14833 pair))))
14834 (append
14835 (or org-current-tag-alist
14836 (org-get-buffer-tags))
14837 (and
14838 org-complete-tags-always-offer-all-agenda-tags
14839 (org-global-tags-completion-table
14840 (org-agenda-files))))))))
14841 (current-tags (org-split-string current ":"))
14842 (inherited-tags
14843 (nreverse (nthcdr (length current-tags)
14844 (nreverse (org-get-tags-at))))))
14845 (replace-regexp-in-string
14846 "\\([-+&]+\\|,\\)"
14848 (if (or (eq t org-use-fast-tag-selection)
14849 (and org-use-fast-tag-selection
14850 (delq nil (mapcar #'cdr table))))
14851 (org-fast-tag-selection
14852 current-tags inherited-tags table
14853 (and org-fast-tag-selection-include-todo
14854 org-todo-key-alist))
14855 (let ((org-add-colon-after-tag-completion
14856 (< 1 (length table))))
14857 (org-trim
14858 (completing-read
14859 "Tags: "
14860 #'org-tags-completion-function
14861 nil nil current 'org-tags-history))))))))))
14863 (when org-tags-sort-function
14864 (setq tags
14865 (mapconcat
14866 #'identity
14867 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14868 org-tags-sort-function)
14869 ":")))
14871 (if (or (string= ":" tags)
14872 (string= "::" tags))
14873 (setq tags ""))
14874 (if (not (org-string-nw-p tags)) (setq tags "")
14875 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14876 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14878 ;; Insert new tags at the correct column.
14879 (unless (equal current tags)
14880 (save-excursion
14881 (beginning-of-line)
14882 (let ((case-fold-search nil))
14883 (looking-at org-complex-heading-regexp))
14884 ;; Remove current tags, if any.
14885 (when (match-end 5) (replace-match "" nil nil nil 5))
14886 ;; Insert new tags, if any. Otherwise, remove trailing
14887 ;; white spaces.
14888 (end-of-line)
14889 (if (not (equal tags ""))
14890 ;; When text is being inserted on an invisible
14891 ;; region boundary, it can be inadvertently sucked
14892 ;; into invisibility.
14893 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14894 (skip-chars-backward " \t")
14895 (delete-region (point) (line-end-position)))))
14896 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14897 ;; is on.
14898 (unless (equal tags "")
14899 (let* ((level (save-excursion
14900 (beginning-of-line)
14901 (skip-chars-forward "\\*")))
14902 (offset (if (bound-and-true-p org-indent-mode)
14903 (* (1- org-indent-indentation-per-level)
14904 (1- level))
14906 (tags-column
14907 (+ org-tags-column
14908 (if (> org-tags-column 0) (- offset) offset))))
14909 (org--align-tags-here tags-column))))
14910 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14912 (defun org-change-tag-in-region (beg end tag off)
14913 "Add or remove TAG for each entry in the region.
14914 This works in the agenda, and also in an Org buffer."
14915 (interactive
14916 (list (region-beginning) (region-end)
14917 (let ((org-last-tags-completion-table
14918 (if (derived-mode-p 'org-mode)
14919 (org-uniquify
14920 (delq nil (append (org-get-buffer-tags)
14921 (org-global-tags-completion-table))))
14922 (org-global-tags-completion-table))))
14923 (completing-read
14924 "Tag: " 'org-tags-completion-function nil nil nil
14925 'org-tags-history))
14926 (progn
14927 (message "[s]et or [r]emove? ")
14928 (equal (read-char-exclusive) ?r))))
14929 (when (fboundp 'deactivate-mark) (deactivate-mark))
14930 (let ((agendap (equal major-mode 'org-agenda-mode))
14931 l1 l2 m buf pos newhead (cnt 0))
14932 (goto-char end)
14933 (setq l2 (1- (org-current-line)))
14934 (goto-char beg)
14935 (setq l1 (org-current-line))
14936 (cl-loop for l from l1 to l2 do
14937 (org-goto-line l)
14938 (setq m (get-text-property (point) 'org-hd-marker))
14939 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14940 (and agendap m))
14941 (setq buf (if agendap (marker-buffer m) (current-buffer))
14942 pos (if agendap m (point)))
14943 (with-current-buffer buf
14944 (save-excursion
14945 (save-restriction
14946 (goto-char pos)
14947 (setq cnt (1+ cnt))
14948 (org-toggle-tag tag (if off 'off 'on))
14949 (setq newhead (org-get-heading)))))
14950 (and agendap (org-agenda-change-all-lines newhead m))))
14951 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14953 (defun org-tags-completion-function (string _predicate &optional flag)
14954 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14955 (confirm (lambda (x) (stringp (car x)))))
14956 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14957 (setq s1 (match-string 1 string)
14958 s2 (match-string 2 string))
14959 (setq s1 "" s2 string))
14960 (cond
14961 ((eq flag nil)
14962 ;; try completion
14963 (setq rtn (try-completion s2 ctable confirm))
14964 (when (stringp rtn)
14965 (setq rtn
14966 (concat s1 s2 (substring rtn (length s2))
14967 (if (and org-add-colon-after-tag-completion
14968 (assoc rtn ctable))
14969 ":" ""))))
14970 rtn)
14971 ((eq flag t)
14972 ;; all-completions
14973 (all-completions s2 ctable confirm))
14974 ((eq flag 'lambda)
14975 ;; exact match?
14976 (assoc s2 ctable)))))
14978 (defun org-fast-tag-insert (kwd tags face &optional end)
14979 "Insert KDW, and the TAGS, the latter with face FACE.
14980 Also insert END."
14981 (insert (format "%-12s" (concat kwd ":"))
14982 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14983 (or end "")))
14985 (defun org-fast-tag-show-exit (flag)
14986 (save-excursion
14987 (org-goto-line 3)
14988 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14989 (replace-match ""))
14990 (when flag
14991 (end-of-line 1)
14992 (org-move-to-column (- (window-width) 19) t)
14993 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14995 (defun org-set-current-tags-overlay (current prefix)
14996 "Add an overlay to CURRENT tag with PREFIX."
14997 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14998 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14999 (org-overlay-display org-tags-overlay (concat prefix s))))
15001 (defvar org-last-tag-selection-key nil)
15002 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15003 "Fast tag selection with single keys.
15004 CURRENT is the current list of tags in the headline, INHERITED is the
15005 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15006 possibly with grouping information. TODO-TABLE is a similar table with
15007 TODO keywords, should these have keys assigned to them.
15008 If the keys are nil, a-z are automatically assigned.
15009 Returns the new tags string, or nil to not change the current settings."
15010 (let* ((fulltable (append table todo-table))
15011 (maxlen (apply 'max (mapcar
15012 (lambda (x)
15013 (if (stringp (car x)) (string-width (car x)) 0))
15014 fulltable)))
15015 (buf (current-buffer))
15016 (expert (eq org-fast-tag-selection-single-key 'expert))
15017 (buffer-tags nil)
15018 (fwidth (+ maxlen 3 1 3))
15019 (ncol (/ (- (window-width) 4) fwidth))
15020 (i-face 'org-done)
15021 (c-face 'org-todo)
15022 tg cnt e c char c1 c2 ntable tbl rtn
15023 ov-start ov-end ov-prefix
15024 (exit-after-next org-fast-tag-selection-single-key)
15025 (done-keywords org-done-keywords)
15026 groups ingroup intaggroup)
15027 (save-excursion
15028 (beginning-of-line 1)
15029 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15030 (setq ov-start (match-beginning 1)
15031 ov-end (match-end 1)
15032 ov-prefix "")
15033 (setq ov-start (1- (point-at-eol))
15034 ov-end (1+ ov-start))
15035 (skip-chars-forward "^\n\r")
15036 (setq ov-prefix
15037 (concat
15038 (buffer-substring (1- (point)) (point))
15039 (if (> (current-column) org-tags-column)
15041 (make-string (- org-tags-column (current-column)) ?\ ))))))
15042 (move-overlay org-tags-overlay ov-start ov-end)
15043 (save-window-excursion
15044 (if expert
15045 (set-buffer (get-buffer-create " *Org tags*"))
15046 (delete-other-windows)
15047 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15048 (org-switch-to-buffer-other-window " *Org tags*"))
15049 (erase-buffer)
15050 (setq-local org-done-keywords done-keywords)
15051 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15052 (org-fast-tag-insert "Current" current c-face "\n\n")
15053 (org-fast-tag-show-exit exit-after-next)
15054 (org-set-current-tags-overlay current ov-prefix)
15055 (setq tbl fulltable char ?a cnt 0)
15056 (while (setq e (pop tbl))
15057 (cond
15058 ((eq (car e) :startgroup)
15059 (push '() groups) (setq ingroup t)
15060 (unless (zerop cnt)
15061 (setq cnt 0)
15062 (insert "\n"))
15063 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15064 ((eq (car e) :endgroup)
15065 (setq ingroup nil cnt 0)
15066 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15067 ((eq (car e) :startgrouptag)
15068 (setq intaggroup t)
15069 (unless (zerop cnt)
15070 (setq cnt 0)
15071 (insert "\n"))
15072 (insert "[ "))
15073 ((eq (car e) :endgrouptag)
15074 (setq intaggroup nil cnt 0)
15075 (insert "]\n"))
15076 ((equal e '(:newline))
15077 (unless (zerop cnt)
15078 (setq cnt 0)
15079 (insert "\n")
15080 (setq e (car tbl))
15081 (while (equal (car tbl) '(:newline))
15082 (insert "\n")
15083 (setq tbl (cdr tbl)))))
15084 ((equal e '(:grouptags)) (insert " : "))
15086 (setq tg (copy-sequence (car e)) c2 nil)
15087 (if (cdr e)
15088 (setq c (cdr e))
15089 ;; automatically assign a character.
15090 (setq c1 (string-to-char
15091 (downcase (substring
15092 tg (if (= (string-to-char tg) ?@) 1 0)))))
15093 (if (or (rassoc c1 ntable) (rassoc c1 table))
15094 (while (or (rassoc char ntable) (rassoc char table))
15095 (setq char (1+ char)))
15096 (setq c2 c1))
15097 (setq c (or c2 char)))
15098 (when ingroup (push tg (car groups)))
15099 (setq tg (org-add-props tg nil 'face
15100 (cond
15101 ((not (assoc tg table))
15102 (org-get-todo-face tg))
15103 ((member tg current) c-face)
15104 ((member tg inherited) i-face))))
15105 (when (equal (caar tbl) :grouptags)
15106 (org-add-props tg nil 'face 'org-tag-group))
15107 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15108 (insert "[" c "] " tg (make-string
15109 (- fwidth 4 (length tg)) ?\ ))
15110 (push (cons tg c) ntable)
15111 (when (= (cl-incf cnt) ncol)
15112 (insert "\n")
15113 (when (or ingroup intaggroup) (insert " "))
15114 (setq cnt 0)))))
15115 (setq ntable (nreverse ntable))
15116 (insert "\n")
15117 (goto-char (point-min))
15118 (unless expert (org-fit-window-to-buffer))
15119 (setq rtn
15120 (catch 'exit
15121 (while t
15122 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15123 (if (not groups) "no " "")
15124 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15125 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15126 (setq org-last-tag-selection-key c)
15127 (cond
15128 ((= c ?\r) (throw 'exit t))
15129 ((= c ?!)
15130 (setq groups (not groups))
15131 (goto-char (point-min))
15132 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15133 ((= c ?\C-c)
15134 (if (not expert)
15135 (org-fast-tag-show-exit
15136 (setq exit-after-next (not exit-after-next)))
15137 (setq expert nil)
15138 (delete-other-windows)
15139 (set-window-buffer (split-window-vertically) " *Org tags*")
15140 (org-switch-to-buffer-other-window " *Org tags*")
15141 (org-fit-window-to-buffer)))
15142 ((or (= c ?\C-g)
15143 (and (= c ?q) (not (rassoc c ntable))))
15144 (delete-overlay org-tags-overlay)
15145 (setq quit-flag t))
15146 ((= c ?\ )
15147 (setq current nil)
15148 (when exit-after-next (setq exit-after-next 'now)))
15149 ((= c ?\t)
15150 (condition-case nil
15151 (setq tg (completing-read
15152 "Tag: "
15153 (or buffer-tags
15154 (with-current-buffer buf
15155 (setq buffer-tags
15156 (org-get-buffer-tags))))))
15157 (quit (setq tg "")))
15158 (when (string-match "\\S-" tg)
15159 (cl-pushnew (list tg) buffer-tags :test #'equal)
15160 (if (member tg current)
15161 (setq current (delete tg current))
15162 (push tg current)))
15163 (when exit-after-next (setq exit-after-next 'now)))
15164 ((setq e (rassoc c todo-table) tg (car e))
15165 (with-current-buffer buf
15166 (save-excursion (org-todo tg)))
15167 (when exit-after-next (setq exit-after-next 'now)))
15168 ((setq e (rassoc c ntable) tg (car e))
15169 (if (member tg current)
15170 (setq current (delete tg current))
15171 (cl-loop for g in groups do
15172 (when (member tg g)
15173 (dolist (x g) (setq current (delete x current)))))
15174 (push tg current))
15175 (when exit-after-next (setq exit-after-next 'now))))
15177 ;; Create a sorted list
15178 (setq current
15179 (sort current
15180 (lambda (a b)
15181 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15182 (when (eq exit-after-next 'now) (throw 'exit t))
15183 (goto-char (point-min))
15184 (beginning-of-line 2)
15185 (delete-region (point) (point-at-eol))
15186 (org-fast-tag-insert "Current" current c-face)
15187 (org-set-current-tags-overlay current ov-prefix)
15188 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15189 (setq tg (match-string 1))
15190 (add-text-properties
15191 (match-beginning 1) (match-end 1)
15192 (list 'face
15193 (cond
15194 ((member tg current) c-face)
15195 ((member tg inherited) i-face)
15196 (t (get-text-property (match-beginning 1) 'face))))))
15197 (goto-char (point-min)))))
15198 (delete-overlay org-tags-overlay)
15199 (if rtn
15200 (mapconcat 'identity current ":")
15201 nil))))
15203 (defun org-get-tags-string ()
15204 "Get the TAGS string in the current headline."
15205 (unless (org-at-heading-p t)
15206 (user-error "Not on a heading"))
15207 (save-excursion
15208 (beginning-of-line 1)
15209 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15210 (match-string-no-properties 1)
15211 "")))
15213 (defun org-get-tags ()
15214 "Get the list of tags specified in the current headline."
15215 (org-split-string (org-get-tags-string) ":"))
15217 (defun org-get-buffer-tags ()
15218 "Get a table of all tags used in the buffer, for completion."
15219 (org-with-wide-buffer
15220 (goto-char (point-min))
15221 (let ((tag-re (concat org-outline-regexp-bol
15222 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15223 tags)
15224 (while (re-search-forward tag-re nil t)
15225 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15226 (push tag tags)))
15227 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15229 ;;;; The mapping API
15231 (defvar org-agenda-skip-comment-trees)
15232 (defvar org-agenda-skip-function)
15233 (defun org-map-entries (func &optional match scope &rest skip)
15234 "Call FUNC at each headline selected by MATCH in SCOPE.
15236 FUNC is a function or a lisp form. The function will be called without
15237 arguments, with the cursor positioned at the beginning of the headline.
15238 The return values of all calls to the function will be collected and
15239 returned as a list.
15241 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15242 does not need to preserve point. After evaluation, the cursor will be
15243 moved to the end of the line (presumably of the headline of the
15244 processed entry) and search continues from there. Under some
15245 circumstances, this may not produce the wanted results. For example,
15246 if you have removed (e.g. archived) the current (sub)tree it could
15247 mean that the next entry will be skipped entirely. In such cases, you
15248 can specify the position from where search should continue by making
15249 FUNC set the variable `org-map-continue-from' to the desired buffer
15250 position.
15252 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15253 Only headlines that are matched by this query will be considered during
15254 the iteration. When MATCH is nil or t, all headlines will be
15255 visited by the iteration.
15257 SCOPE determines the scope of this command. It can be any of:
15259 nil The current buffer, respecting the restriction if any
15260 tree The subtree started with the entry at point
15261 region The entries within the active region, if any
15262 region-start-level
15263 The entries within the active region, but only those at
15264 the same level than the first one.
15265 file The current buffer, without restriction
15266 file-with-archives
15267 The current buffer, and any archives associated with it
15268 agenda All agenda files
15269 agenda-with-archives
15270 All agenda files with any archive files associated with them
15271 \(file1 file2 ...)
15272 If this is a list, all files in the list will be scanned
15274 The remaining args are treated as settings for the skipping facilities of
15275 the scanner. The following items can be given here:
15277 archive skip trees with the archive tag
15278 comment skip trees with the COMMENT keyword
15279 function or Emacs Lisp form:
15280 will be used as value for `org-agenda-skip-function', so
15281 whenever the function returns a position, FUNC will not be
15282 called for that entry and search will continue from the
15283 position returned
15285 If your function needs to retrieve the tags including inherited tags
15286 at the *current* entry, you can use the value of the variable
15287 `org-scanner-tags' which will be much faster than getting the value
15288 with `org-get-tags-at'. If your function gets properties with
15289 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15290 to t around the call to `org-entry-properties' to get the same speedup.
15291 Note that if your function moves around to retrieve tags and properties at
15292 a *different* entry, you cannot use these techniques."
15293 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15294 (not (org-region-active-p)))
15295 (let* ((org-agenda-archives-mode nil) ; just to make sure
15296 (org-agenda-skip-archived-trees (memq 'archive skip))
15297 (org-agenda-skip-comment-trees (memq 'comment skip))
15298 (org-agenda-skip-function
15299 (car (org-delete-all '(comment archive) skip)))
15300 (org-tags-match-list-sublevels t)
15301 (start-level (eq scope 'region-start-level))
15302 matcher res
15303 org-todo-keywords-for-agenda
15304 org-done-keywords-for-agenda
15305 org-todo-keyword-alist-for-agenda
15306 org-tag-alist-for-agenda
15307 org--matcher-tags-todo-only)
15309 (cond
15310 ((eq match t) (setq matcher t))
15311 ((eq match nil) (setq matcher t))
15312 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15314 (save-excursion
15315 (save-restriction
15316 (cond ((eq scope 'tree)
15317 (org-back-to-heading t)
15318 (org-narrow-to-subtree)
15319 (setq scope nil))
15320 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15321 (org-region-active-p))
15322 ;; If needed, set start-level to a string like "2"
15323 (when start-level
15324 (save-excursion
15325 (goto-char (region-beginning))
15326 (unless (org-at-heading-p) (outline-next-heading))
15327 (setq start-level (org-current-level))))
15328 (narrow-to-region (region-beginning)
15329 (save-excursion
15330 (goto-char (region-end))
15331 (unless (and (bolp) (org-at-heading-p))
15332 (outline-next-heading))
15333 (point)))
15334 (setq scope nil)))
15336 (if (not scope)
15337 (progn
15338 (org-agenda-prepare-buffers
15339 (and buffer-file-name (list buffer-file-name)))
15340 (setq res
15341 (org-scan-tags
15342 func matcher org--matcher-tags-todo-only start-level)))
15343 ;; Get the right scope
15344 (cond
15345 ((and scope (listp scope) (symbolp (car scope)))
15346 (setq scope (eval scope)))
15347 ((eq scope 'agenda)
15348 (setq scope (org-agenda-files t)))
15349 ((eq scope 'agenda-with-archives)
15350 (setq scope (org-agenda-files t))
15351 (setq scope (org-add-archive-files scope)))
15352 ((eq scope 'file)
15353 (setq scope (and buffer-file-name (list buffer-file-name))))
15354 ((eq scope 'file-with-archives)
15355 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15356 (org-agenda-prepare-buffers scope)
15357 (dolist (file scope)
15358 (with-current-buffer (org-find-base-buffer-visiting file)
15359 (org-with-wide-buffer
15360 (goto-char (point-min))
15361 (setq res
15362 (append
15364 (org-scan-tags
15365 func matcher org--matcher-tags-todo-only)))))))))
15366 res)))
15368 ;;; Properties API
15370 (defconst org-special-properties
15371 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15372 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15373 "The special properties valid in Org mode.
15374 These are properties that are not defined in the property drawer,
15375 but in some other way.")
15377 (defconst org-default-properties
15378 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15379 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15380 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15381 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15382 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15383 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15384 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15385 "Some properties that are used by Org mode for various purposes.
15386 Being in this list makes sure that they are offered for completion.")
15388 (defun org--valid-property-p (property)
15389 "Non nil when string PROPERTY is a valid property name."
15390 (not
15391 (or (equal property "")
15392 (string-match-p "\\s-" property))))
15394 (defun org--update-property-plist (key val props)
15395 "Associate KEY to VAL in alist PROPS.
15396 Modifications are made by side-effect. Return new alist."
15397 (let* ((appending (string= (substring key -1) "+"))
15398 (key (if appending (substring key 0 -1) key))
15399 (old (assoc-string key props t)))
15400 (if (not old) (cons (cons key val) props)
15401 (setcdr old (if appending (concat (cdr old) " " val) val))
15402 props)))
15404 (defun org-get-property-block (&optional beg force)
15405 "Return the (beg . end) range of the body of the property drawer.
15406 BEG is the beginning of the current subtree, or of the part
15407 before the first headline. If it is not given, it will be found.
15408 If the drawer does not exist, create it if FORCE is non-nil, or
15409 return nil."
15410 (org-with-wide-buffer
15411 (when beg (goto-char beg))
15412 (unless (org-before-first-heading-p)
15413 (let ((beg (cond (beg)
15414 ((or (not (featurep 'org-inlinetask))
15415 (org-inlinetask-in-task-p))
15416 (org-back-to-heading t))
15417 (t (org-with-limited-levels (org-back-to-heading t))))))
15418 (forward-line)
15419 (when (looking-at-p org-planning-line-re) (forward-line))
15420 (cond ((looking-at org-property-drawer-re)
15421 (forward-line)
15422 (cons (point) (progn (goto-char (match-end 0))
15423 (line-beginning-position))))
15424 (force
15425 (goto-char beg)
15426 (org-insert-property-drawer)
15427 (let ((pos (save-excursion (search-forward ":END:")
15428 (line-beginning-position))))
15429 (cons pos pos))))))))
15431 (defun org-at-property-p ()
15432 "Non-nil when point is inside a property drawer.
15433 See `org-property-re' for match data, if applicable."
15434 (save-excursion
15435 (beginning-of-line)
15436 (and (looking-at org-property-re)
15437 (let ((property-drawer (save-match-data (org-get-property-block))))
15438 (and property-drawer
15439 (>= (point) (car property-drawer))
15440 (< (point) (cdr property-drawer)))))))
15442 (defun org-property-action ()
15443 "Do an action on properties."
15444 (interactive)
15445 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15446 (let ((c (read-char-exclusive)))
15447 (cl-case c
15448 (?s (call-interactively #'org-set-property))
15449 (?d (call-interactively #'org-delete-property))
15450 (?D (call-interactively #'org-delete-property-globally))
15451 (?c (call-interactively #'org-compute-property-at-point))
15452 (otherwise (user-error "No such property action %c" c)))))
15454 (defun org-inc-effort ()
15455 "Increment the value of the effort property in the current entry."
15456 (interactive)
15457 (org-set-effort nil t))
15459 (defvar org-clock-effort) ; Defined in org-clock.el.
15460 (defvar org-clock-current-task) ; Defined in org-clock.el.
15461 (defun org-set-effort (&optional value increment)
15462 "Set the effort property of the current entry.
15463 With numerical prefix arg, use the nth allowed value, 0 stands for the
15464 10th allowed value.
15466 When INCREMENT is non-nil, set the property to the next allowed value."
15467 (interactive "P")
15468 (when (equal value 0) (setq value 10))
15469 (let* ((completion-ignore-case t)
15470 (prop org-effort-property)
15471 (cur (org-entry-get nil prop))
15472 (allowed (org-property-get-allowed-values nil prop 'table))
15473 (existing (mapcar 'list (org-property-values prop)))
15474 (heading (nth 4 (org-heading-components)))
15476 (val (cond
15477 ((stringp value) value)
15478 ((and allowed (integerp value))
15479 (or (car (nth (1- value) allowed))
15480 (car (org-last allowed))))
15481 ((and allowed increment)
15482 (or (cl-caadr (member (list cur) allowed))
15483 (user-error "Allowed effort values are not set")))
15484 (allowed
15485 (message "Select 1-9,0, [RET%s]: %s"
15486 (if cur (concat "=" cur) "")
15487 (mapconcat 'car allowed " "))
15488 (setq rpl (read-char-exclusive))
15489 (if (equal rpl ?\r)
15491 (setq rpl (- rpl ?0))
15492 (when (equal rpl 0) (setq rpl 10))
15493 (if (and (> rpl 0) (<= rpl (length allowed)))
15494 (car (nth (1- rpl) allowed))
15495 (org-completing-read "Effort: " allowed nil))))
15497 (org-completing-read
15498 (concat "Effort" (and cur (string-match "\\S-" cur)
15499 (concat " [" cur "]"))
15500 ": ")
15501 existing nil nil "" nil cur)))))
15502 (unless (equal (org-entry-get nil prop) val)
15503 (org-entry-put nil prop val))
15504 (org-refresh-property
15505 '((effort . identity)
15506 (effort-minutes . org-duration-to-minutes))
15507 val)
15508 (when (equal heading (bound-and-true-p org-clock-current-task))
15509 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15510 (org-clock-update-mode-line))
15511 (message "%s is now %s" prop val)))
15513 (defun org-entry-properties (&optional pom which)
15514 "Get all properties of the current entry.
15516 When POM is a buffer position, get all properties from the entry
15517 there instead.
15519 This includes the TODO keyword, the tags, time strings for
15520 deadline, scheduled, and clocking, and any additional properties
15521 defined in the entry.
15523 If WHICH is nil or `all', get all properties. If WHICH is
15524 `special' or `standard', only get that subclass. If WHICH is
15525 a string, only get that property.
15527 Return value is an alist. Keys are properties, as upcased
15528 strings."
15529 (org-with-point-at pom
15530 (when (and (derived-mode-p 'org-mode)
15531 (ignore-errors (org-back-to-heading t)))
15532 (catch 'exit
15533 (let* ((beg (point))
15534 (specific (and (stringp which) (upcase which)))
15535 (which (cond ((not specific) which)
15536 ((member specific org-special-properties) 'special)
15537 (t 'standard)))
15538 props)
15539 ;; Get the special properties, like TODO and TAGS.
15540 (when (memq which '(nil all special))
15541 (when (or (not specific) (string= specific "CLOCKSUM"))
15542 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15543 (when clocksum
15544 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15545 props)))
15546 (when specific (throw 'exit props)))
15547 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15548 (let ((clocksumt (get-text-property (point)
15549 :org-clock-minutes-today)))
15550 (when clocksumt
15551 (push (cons "CLOCKSUM_T"
15552 (org-duration-from-minutes clocksumt))
15553 props)))
15554 (when specific (throw 'exit props)))
15555 (when (or (not specific) (string= specific "ITEM"))
15556 (let ((case-fold-search nil))
15557 (when (looking-at org-complex-heading-regexp)
15558 (push (cons "ITEM"
15559 (let ((title (match-string-no-properties 4)))
15560 (if (org-string-nw-p title)
15561 (org-remove-tabs title)
15562 "")))
15563 props)))
15564 (when specific (throw 'exit props)))
15565 (when (or (not specific) (string= specific "TODO"))
15566 (let ((case-fold-search nil))
15567 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15568 (push (cons "TODO" (match-string-no-properties 2)) props)))
15569 (when specific (throw 'exit props)))
15570 (when (or (not specific) (string= specific "PRIORITY"))
15571 (push (cons "PRIORITY"
15572 (if (looking-at org-priority-regexp)
15573 (match-string-no-properties 2)
15574 (char-to-string org-default-priority)))
15575 props)
15576 (when specific (throw 'exit props)))
15577 (when (or (not specific) (string= specific "FILE"))
15578 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15579 props)
15580 (when specific (throw 'exit props)))
15581 (when (or (not specific) (string= specific "TAGS"))
15582 (let ((value (org-string-nw-p (org-get-tags-string))))
15583 (when value (push (cons "TAGS" value) props)))
15584 (when specific (throw 'exit props)))
15585 (when (or (not specific) (string= specific "ALLTAGS"))
15586 (let ((value (org-get-tags-at)))
15587 (when value
15588 (push (cons "ALLTAGS"
15589 (format ":%s:" (mapconcat #'identity value ":")))
15590 props)))
15591 (when specific (throw 'exit props)))
15592 (when (or (not specific) (string= specific "BLOCKED"))
15593 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15594 (when specific (throw 'exit props)))
15595 (when (or (not specific)
15596 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15597 (forward-line)
15598 (when (looking-at-p org-planning-line-re)
15599 (end-of-line)
15600 (let ((bol (line-beginning-position))
15601 ;; Backward compatibility: time keywords used to
15602 ;; be configurable (before 8.3). Make sure we
15603 ;; get the correct keyword.
15604 (key-assoc `(("CLOSED" . ,org-closed-string)
15605 ("DEADLINE" . ,org-deadline-string)
15606 ("SCHEDULED" . ,org-scheduled-string))))
15607 (dolist (pair (if specific (list (assoc specific key-assoc))
15608 key-assoc))
15609 (save-excursion
15610 (when (search-backward (cdr pair) bol t)
15611 (goto-char (match-end 0))
15612 (skip-chars-forward " \t")
15613 (and (looking-at org-ts-regexp-both)
15614 (push (cons (car pair)
15615 (match-string-no-properties 0))
15616 props)))))))
15617 (when specific (throw 'exit props)))
15618 (when (or (not specific)
15619 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15620 (let ((find-ts
15621 (lambda (end ts)
15622 ;; Fix next time-stamp before END. TS is the
15623 ;; list of time-stamps found so far.
15624 (let ((ts ts)
15625 (regexp (cond
15626 ((string= specific "TIMESTAMP")
15627 org-ts-regexp)
15628 ((string= specific "TIMESTAMP_IA")
15629 org-ts-regexp-inactive)
15630 ((assoc "TIMESTAMP_IA" ts)
15631 org-ts-regexp)
15632 ((assoc "TIMESTAMP" ts)
15633 org-ts-regexp-inactive)
15634 (t org-ts-regexp-both))))
15635 (catch 'next
15636 (while (re-search-forward regexp end t)
15637 (backward-char)
15638 (let ((object (org-element-context)))
15639 ;; Accept to match timestamps in node
15640 ;; properties, too.
15641 (when (memq (org-element-type object)
15642 '(node-property timestamp))
15643 (let ((type
15644 (org-element-property :type object)))
15645 (cond
15646 ((and (memq type '(active active-range))
15647 (not (equal specific "TIMESTAMP_IA")))
15648 (unless (assoc "TIMESTAMP" ts)
15649 (push (cons "TIMESTAMP"
15650 (org-element-property
15651 :raw-value object))
15653 (when specific (throw 'exit ts))))
15654 ((and (memq type '(inactive inactive-range))
15655 (not (string= specific "TIMESTAMP")))
15656 (unless (assoc "TIMESTAMP_IA" ts)
15657 (push (cons "TIMESTAMP_IA"
15658 (org-element-property
15659 :raw-value object))
15661 (when specific (throw 'exit ts))))))
15662 ;; Both timestamp types are found,
15663 ;; move to next part.
15664 (when (= (length ts) 2) (throw 'next ts)))))
15665 ts)))))
15666 (goto-char beg)
15667 ;; First look for timestamps within headline.
15668 (let ((ts (funcall find-ts (line-end-position) nil)))
15669 (if (= (length ts) 2) (setq props (nconc ts props))
15670 ;; Then find timestamps in the section, skipping
15671 ;; planning line.
15672 (let ((end (save-excursion (outline-next-heading))))
15673 (forward-line)
15674 (when (looking-at-p org-planning-line-re) (forward-line))
15675 (setq props (nconc (funcall find-ts end ts) props))))))))
15676 ;; Get the standard properties, like :PROP:.
15677 (when (memq which '(nil all standard))
15678 ;; If we are looking after a specific property, delegate
15679 ;; to `org-entry-get', which is faster. However, make an
15680 ;; exception for "CATEGORY", since it can be also set
15681 ;; through keywords (i.e. #+CATEGORY).
15682 (if (and specific (not (equal specific "CATEGORY")))
15683 (let ((value (org-entry-get beg specific nil t)))
15684 (throw 'exit (and value (list (cons specific value)))))
15685 (let ((range (org-get-property-block beg)))
15686 (when range
15687 (let ((end (cdr range)) seen-base)
15688 (goto-char (car range))
15689 ;; Unlike to `org--update-property-plist', we
15690 ;; handle the case where base values is found
15691 ;; after its extension. We also forbid standard
15692 ;; properties to be named as special properties.
15693 (while (re-search-forward org-property-re end t)
15694 (let* ((key (upcase (match-string-no-properties 2)))
15695 (extendp (string-match-p "\\+\\'" key))
15696 (key-base (if extendp (substring key 0 -1) key))
15697 (value (match-string-no-properties 3)))
15698 (cond
15699 ((member-ignore-case key-base org-special-properties))
15700 (extendp
15701 (setq props
15702 (org--update-property-plist key value props)))
15703 ((member key seen-base))
15704 (t (push key seen-base)
15705 (let ((p (assoc-string key props t)))
15706 (if p (setcdr p (concat value " " (cdr p)))
15707 (push (cons key value) props))))))))))))
15708 (unless (assoc "CATEGORY" props)
15709 (push (cons "CATEGORY" (org-get-category beg)) props)
15710 (when (string= specific "CATEGORY") (throw 'exit props)))
15711 ;; Return value.
15712 props)))))
15714 (defun org--property-local-values (property literal-nil)
15715 "Return value for PROPERTY in current entry.
15716 Value is a list whose car is the base value for PROPERTY and cdr
15717 a list of accumulated values. Return nil if neither is found in
15718 the entry. Also return nil when PROPERTY is set to \"nil\",
15719 unless LITERAL-NIL is non-nil."
15720 (let ((range (org-get-property-block)))
15721 (when range
15722 (goto-char (car range))
15723 (let* ((case-fold-search t)
15724 (end (cdr range))
15725 (value
15726 ;; Base value.
15727 (save-excursion
15728 (let ((v (and (re-search-forward
15729 (org-re-property property nil t) end t)
15730 (match-string-no-properties 3))))
15731 (list (if literal-nil v (org-not-nil v)))))))
15732 ;; Find additional values.
15733 (let* ((property+ (org-re-property (concat property "+") nil t)))
15734 (while (re-search-forward property+ end t)
15735 (push (match-string-no-properties 3) value)))
15736 ;; Return final values.
15737 (and (not (equal value '(nil))) (nreverse value))))))
15739 (defun org--property-global-value (property literal-nil)
15740 "Return value for PROPERTY in current buffer.
15741 Return value is a string. Return nil if property is not set
15742 globally. Also return nil when PROPERTY is set to \"nil\",
15743 unless LITERAL-NIL is non-nil."
15744 (let ((global
15745 (cdr (or (assoc-string property org-file-properties t)
15746 (assoc-string property org-global-properties t)
15747 (assoc-string property org-global-properties-fixed t)))))
15748 (if literal-nil global (org-not-nil global))))
15750 (defun org-entry-get (pom property &optional inherit literal-nil)
15751 "Get value of PROPERTY for entry or content at point-or-marker POM.
15753 If INHERIT is non-nil and the entry does not have the property,
15754 then also check higher levels of the hierarchy. If INHERIT is
15755 the symbol `selective', use inheritance only if the setting in
15756 `org-use-property-inheritance' selects PROPERTY for inheritance.
15758 If the property is present but empty, the return value is the
15759 empty string. If the property is not present at all, nil is
15760 returned. In any other case, return the value as a string.
15761 Search is case-insensitive.
15763 If LITERAL-NIL is set, return the string value \"nil\" as
15764 a string, do not interpret it as the list atom nil. This is used
15765 for inheritance when a \"nil\" value can supersede a non-nil
15766 value higher up the hierarchy."
15767 (org-with-point-at pom
15768 (cond
15769 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15770 ;; We need a special property. Use `org-entry-properties' to
15771 ;; retrieve it, but specify the wanted property.
15772 (cdr (assoc-string property (org-entry-properties nil property))))
15773 ((and inherit
15774 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15775 (org-entry-get-with-inheritance property literal-nil))
15777 (let* ((local (org--property-local-values property literal-nil))
15778 (value (and local (mapconcat #'identity (delq nil local) " "))))
15779 (if literal-nil value (org-not-nil value)))))))
15781 (defun org-property-or-variable-value (var &optional inherit)
15782 "Check if there is a property fixing the value of VAR.
15783 If yes, return this value. If not, return the current value of the variable."
15784 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15785 (if (and prop (stringp prop) (string-match "\\S-" prop))
15786 (read prop)
15787 (symbol-value var))))
15789 (defun org-entry-delete (pom property)
15790 "Delete PROPERTY from entry at point-or-marker POM.
15791 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15792 non-nil when a property was removed."
15793 (org-with-point-at pom
15794 (pcase (org-get-property-block)
15795 (`(,begin . ,origin)
15796 (let* ((end (copy-marker origin))
15797 (re (org-re-property
15798 (concat (regexp-quote property) "\\+?") t t)))
15799 (goto-char begin)
15800 (while (re-search-forward re end t)
15801 (delete-region (match-beginning 0) (line-beginning-position 2)))
15802 ;; If drawer is empty, remove it altogether.
15803 (when (= begin end)
15804 (delete-region (line-beginning-position 0)
15805 (line-beginning-position 2)))
15806 ;; Return non-nil if some property was removed.
15807 (prog1 (/= end origin) (set-marker end nil))))
15808 (_ nil))))
15810 ;; Multi-values properties are properties that contain multiple values
15811 ;; These values are assumed to be single words, separated by whitespace.
15812 (defun org-entry-add-to-multivalued-property (pom property value)
15813 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15814 (let* ((old (org-entry-get pom property))
15815 (values (and old (split-string old))))
15816 (setq value (org-entry-protect-space value))
15817 (unless (member value values)
15818 (setq values (append values (list value)))
15819 (org-entry-put pom property (mapconcat #'identity values " ")))))
15821 (defun org-entry-remove-from-multivalued-property (pom property value)
15822 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15823 (let* ((old (org-entry-get pom property))
15824 (values (and old (split-string old))))
15825 (setq value (org-entry-protect-space value))
15826 (when (member value values)
15827 (setq values (delete value values))
15828 (org-entry-put pom property (mapconcat #'identity values " ")))))
15830 (defun org-entry-member-in-multivalued-property (pom property value)
15831 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15832 (let* ((old (org-entry-get pom property))
15833 (values (and old (split-string old))))
15834 (setq value (org-entry-protect-space value))
15835 (member value values)))
15837 (defun org-entry-get-multivalued-property (pom property)
15838 "Return a list of values in a multivalued property."
15839 (let* ((value (org-entry-get pom property))
15840 (values (and value (split-string value))))
15841 (mapcar #'org-entry-restore-space values)))
15843 (defun org-entry-put-multivalued-property (pom property &rest values)
15844 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15845 VALUES should be a list of strings. Spaces will be protected."
15846 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15847 (let* ((value (org-entry-get pom property))
15848 (values (and value (split-string value))))
15849 (mapcar #'org-entry-restore-space values)))
15851 (defun org-entry-protect-space (s)
15852 "Protect spaces and newline in string S."
15853 (while (string-match " " s)
15854 (setq s (replace-match "%20" t t s)))
15855 (while (string-match "\n" s)
15856 (setq s (replace-match "%0A" t t s)))
15859 (defun org-entry-restore-space (s)
15860 "Restore spaces and newline in string S."
15861 (while (string-match "%20" s)
15862 (setq s (replace-match " " t t s)))
15863 (while (string-match "%0A" s)
15864 (setq s (replace-match "\n" t t s)))
15867 (defvar org-entry-property-inherited-from (make-marker)
15868 "Marker pointing to the entry from where a property was inherited.
15869 Each call to `org-entry-get-with-inheritance' will set this marker to the
15870 location of the entry where the inheritance search matched. If there was
15871 no match, the marker will point nowhere.
15872 Note that also `org-entry-get' calls this function, if the INHERIT flag
15873 is set.")
15875 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15876 "Get PROPERTY of entry or content at point, search higher levels if needed.
15877 The search will stop at the first ancestor which has the property defined.
15878 If the value found is \"nil\", return nil to show that the property
15879 should be considered as undefined (this is the meaning of nil here).
15880 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15881 (move-marker org-entry-property-inherited-from nil)
15882 (org-with-wide-buffer
15883 (let (value)
15884 (catch 'exit
15885 (while t
15886 (let ((v (org--property-local-values property literal-nil)))
15887 (when v
15888 (setq value
15889 (concat (mapconcat #'identity (delq nil v) " ")
15890 (and value " ")
15891 value)))
15892 (cond
15893 ((car v)
15894 (org-back-to-heading t)
15895 (move-marker org-entry-property-inherited-from (point))
15896 (throw 'exit nil))
15897 ((org-up-heading-safe))
15899 (let ((global (org--property-global-value property literal-nil)))
15900 (cond ((not global))
15901 (value (setq value (concat global " " value)))
15902 (t (setq value global))))
15903 (throw 'exit nil))))))
15904 (if literal-nil value (org-not-nil value)))))
15906 (defvar org-property-changed-functions nil
15907 "Hook called when the value of a property has changed.
15908 Each hook function should accept two arguments, the name of the property
15909 and the new value.")
15911 (defun org-entry-put (pom property value)
15912 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15914 If the value is nil, it is converted to the empty string. If it
15915 is not a string, an error is raised. Also raise an error on
15916 invalid property names.
15918 PROPERTY can be any regular property (see
15919 `org-special-properties'). It can also be \"TODO\",
15920 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15922 For the last two properties, VALUE may have any of the special
15923 values \"earlier\" and \"later\". The function then increases or
15924 decreases scheduled or deadline date by one day."
15925 (cond ((null value) (setq value ""))
15926 ((not (stringp value)) (error "Properties values should be strings"))
15927 ((not (org--valid-property-p property))
15928 (user-error "Invalid property name: \"%s\"" property)))
15929 (org-with-point-at pom
15930 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15931 (org-back-to-heading t)
15932 (org-with-limited-levels (org-back-to-heading t)))
15933 (let ((beg (point)))
15934 (cond
15935 ((equal property "TODO")
15936 (cond ((not (org-string-nw-p value)) (setq value 'none))
15937 ((not (member value org-todo-keywords-1))
15938 (user-error "\"%s\" is not a valid TODO state" value)))
15939 (org-todo value)
15940 (org-set-tags nil 'align))
15941 ((equal property "PRIORITY")
15942 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15943 (org-set-tags nil 'align))
15944 ((equal property "SCHEDULED")
15945 (forward-line)
15946 (if (and (looking-at-p org-planning-line-re)
15947 (re-search-forward
15948 org-scheduled-time-regexp (line-end-position) t))
15949 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15950 ((string= value "later") (org-timestamp-change 1 'day))
15951 ((string= value "") (org-schedule '(4)))
15952 (t (org-schedule nil value)))
15953 (if (member value '("earlier" "later" ""))
15954 (call-interactively #'org-schedule)
15955 (org-schedule nil value))))
15956 ((equal property "DEADLINE")
15957 (forward-line)
15958 (if (and (looking-at-p org-planning-line-re)
15959 (re-search-forward
15960 org-deadline-time-regexp (line-end-position) t))
15961 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15962 ((string= value "later") (org-timestamp-change 1 'day))
15963 ((string= value "") (org-deadline '(4)))
15964 (t (org-deadline nil value)))
15965 (if (member value '("earlier" "later" ""))
15966 (call-interactively #'org-deadline)
15967 (org-deadline nil value))))
15968 ((member property org-special-properties)
15969 (error "The %s property cannot be set with `org-entry-put'" property))
15971 (let* ((range (org-get-property-block beg 'force))
15972 (end (cdr range))
15973 (case-fold-search t))
15974 (goto-char (car range))
15975 (if (re-search-forward (org-re-property property nil t) end t)
15976 (progn (delete-region (match-beginning 0) (match-end 0))
15977 (goto-char (match-beginning 0)))
15978 (goto-char end)
15979 (insert "\n")
15980 (backward-char))
15981 (insert ":" property ":")
15982 (when value (insert " " value))
15983 (org-indent-line)))))
15984 (run-hook-with-args 'org-property-changed-functions property value)))
15986 (defun org-buffer-property-keys (&optional specials defaults columns)
15987 "Get all property keys in the current buffer.
15989 When SPECIALS is non-nil, also list the special properties that
15990 reflect things like tags and TODO state.
15992 When DEFAULTS is non-nil, also include properties that has
15993 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15994 DESCRIPTION, LOCATION, and LOGGING and others.
15996 When COLUMNS in non-nil, also include property names given in
15997 COLUMN formats in the current buffer."
15998 (let ((case-fold-search t)
15999 (props (append
16000 (and specials org-special-properties)
16001 (and defaults (cons org-effort-property org-default-properties))
16002 nil)))
16003 (org-with-wide-buffer
16004 (goto-char (point-min))
16005 (while (re-search-forward org-property-start-re nil t)
16006 (catch :skip
16007 (let ((range (org-get-property-block)))
16008 (unless range (throw :skip nil))
16009 (goto-char (car range))
16010 (let ((begin (car range))
16011 (end (cdr range)))
16012 ;; Make sure that found property block is not located
16013 ;; before current point, as it would generate an infloop.
16014 ;; It can happen, for example, in the following
16015 ;; situation:
16017 ;; * Headline
16018 ;; :PROPERTIES:
16019 ;; ...
16020 ;; :END:
16021 ;; *************** Inlinetask
16022 ;; #+BEGIN_EXAMPLE
16023 ;; :PROPERTIES:
16024 ;; #+END_EXAMPLE
16026 (if (< begin (point)) (throw :skip nil) (goto-char begin))
16027 (while (< (point) end)
16028 (let ((p (progn (looking-at org-property-re)
16029 (match-string-no-properties 2))))
16030 ;; Only add true property name, not extension symbol.
16031 (push (if (not (string-match-p "\\+\\'" p)) p
16032 (substring p 0 -1))
16033 props))
16034 (forward-line))))
16035 (outline-next-heading)))
16036 (when columns
16037 (goto-char (point-min))
16038 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16039 (let ((element (org-element-at-point)))
16040 (when (memq (org-element-type element) '(keyword node-property))
16041 (let ((value (org-element-property :value element))
16042 (start 0))
16043 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16044 \\(?:{[^}]+}\\)?"
16045 value start)
16046 (setq start (match-end 0))
16047 (let ((p (match-string-no-properties 1 value)))
16048 (unless (member-ignore-case p org-special-properties)
16049 (push p props))))))))))
16050 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16052 (defun org-property-values (key)
16053 "List all non-nil values of property KEY in current buffer."
16054 (org-with-wide-buffer
16055 (goto-char (point-min))
16056 (let ((case-fold-search t)
16057 (re (org-re-property key))
16058 values)
16059 (while (re-search-forward re nil t)
16060 (push (org-entry-get (point) key) values))
16061 (delete-dups values))))
16063 (defun org-insert-property-drawer ()
16064 "Insert a property drawer into the current entry."
16065 (org-with-wide-buffer
16066 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16067 (org-back-to-heading t)
16068 (org-with-limited-levels (org-back-to-heading t)))
16069 (forward-line)
16070 (when (looking-at-p org-planning-line-re) (forward-line))
16071 (unless (looking-at-p org-property-drawer-re)
16072 ;; Make sure we start editing a line from current entry, not from
16073 ;; next one. It prevents extending text properties or overlays
16074 ;; belonging to the latter.
16075 (when (bolp) (backward-char))
16076 (let ((begin (1+ (point)))
16077 (inhibit-read-only t))
16078 (insert "\n:PROPERTIES:\n:END:")
16079 (when (eobp) (insert "\n"))
16080 (org-indent-region begin (point))))))
16082 (defun org-insert-drawer (&optional arg drawer)
16083 "Insert a drawer at point.
16085 When optional argument ARG is non-nil, insert a property drawer.
16087 Optional argument DRAWER, when non-nil, is a string representing
16088 drawer's name. Otherwise, the user is prompted for a name.
16090 If a region is active, insert the drawer around that region
16091 instead.
16093 Point is left between drawer's boundaries."
16094 (interactive "P")
16095 (let* ((drawer (if arg "PROPERTIES"
16096 (or drawer (read-from-minibuffer "Drawer: ")))))
16097 (cond
16098 ;; With C-u, fall back on `org-insert-property-drawer'
16099 (arg (org-insert-property-drawer))
16100 ;; Check validity of suggested drawer's name.
16101 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16102 (user-error "Invalid drawer name"))
16103 ;; With an active region, insert a drawer at point.
16104 ((not (org-region-active-p))
16105 (progn
16106 (unless (bolp) (insert "\n"))
16107 (insert (format ":%s:\n\n:END:\n" drawer))
16108 (forward-line -2)))
16109 ;; Otherwise, insert the drawer at point
16111 (let ((rbeg (region-beginning))
16112 (rend (copy-marker (region-end))))
16113 (unwind-protect
16114 (progn
16115 (goto-char rbeg)
16116 (beginning-of-line)
16117 (when (save-excursion
16118 (re-search-forward org-outline-regexp-bol rend t))
16119 (user-error "Drawers cannot contain headlines"))
16120 ;; Position point at the beginning of the first
16121 ;; non-blank line in region. Insert drawer's opening
16122 ;; there, then indent it.
16123 (org-skip-whitespace)
16124 (beginning-of-line)
16125 (insert ":" drawer ":\n")
16126 (forward-line -1)
16127 (indent-for-tab-command)
16128 ;; Move point to the beginning of the first blank line
16129 ;; after the last non-blank line in region. Insert
16130 ;; drawer's closing, then indent it.
16131 (goto-char rend)
16132 (skip-chars-backward " \r\t\n")
16133 (insert "\n:END:")
16134 (deactivate-mark t)
16135 (indent-for-tab-command)
16136 (unless (eolp) (insert "\n")))
16137 ;; Clear marker, whatever the outcome of insertion is.
16138 (set-marker rend nil)))))))
16140 (defvar org-property-set-functions-alist nil
16141 "Property set function alist.
16142 Each entry should have the following format:
16144 (PROPERTY . READ-FUNCTION)
16146 The read function will be called with the same argument as
16147 `org-completing-read'.")
16149 (defun org-set-property-function (property)
16150 "Get the function that should be used to set PROPERTY.
16151 This is computed according to `org-property-set-functions-alist'."
16152 (or (cdr (assoc property org-property-set-functions-alist))
16153 'org-completing-read))
16155 (defun org-read-property-value (property)
16156 "Read PROPERTY value from user."
16157 (let* ((completion-ignore-case t)
16158 (allowed (org-property-get-allowed-values nil property 'table))
16159 (cur (org-entry-get nil property))
16160 (prompt (concat property " value"
16161 (if (and cur (string-match "\\S-" cur))
16162 (concat " [" cur "]") "") ": "))
16163 (set-function (org-set-property-function property))
16164 (val (if allowed
16165 (funcall set-function prompt allowed nil
16166 (not (get-text-property 0 'org-unrestricted
16167 (caar allowed))))
16168 (funcall set-function prompt
16169 (mapcar 'list (org-property-values property))
16170 nil nil "" nil cur))))
16171 (org-trim val)))
16173 (defvar org-last-set-property nil)
16174 (defvar org-last-set-property-value nil)
16175 (defun org-read-property-name ()
16176 "Read a property name."
16177 (let ((completion-ignore-case t)
16178 (default-prop (or (and (org-at-property-p)
16179 (match-string-no-properties 2))
16180 org-last-set-property)))
16181 (org-completing-read
16182 (concat "Property"
16183 (if default-prop (concat " [" default-prop "]") "")
16184 ": ")
16185 (mapcar #'list (org-buffer-property-keys nil t t))
16186 nil nil nil nil default-prop)))
16188 (defun org-set-property-and-value (use-last)
16189 "Allow to set [PROPERTY]: [value] direction from prompt.
16190 When use-default, don't even ask, just use the last
16191 \"[PROPERTY]: [value]\" string from the history."
16192 (interactive "P")
16193 (let* ((completion-ignore-case t)
16194 (pv (or (and use-last org-last-set-property-value)
16195 (org-completing-read
16196 "Enter a \"[Property]: [value]\" pair: "
16197 nil nil nil nil nil
16198 org-last-set-property-value)))
16199 prop val)
16200 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16201 (setq prop (match-string 1 pv)
16202 val (match-string 2 pv))
16203 (org-set-property prop val))))
16205 (defun org-set-property (property value)
16206 "In the current entry, set PROPERTY to VALUE.
16208 When called interactively, this will prompt for a property name, offering
16209 completion on existing and default properties. And then it will prompt
16210 for a value, offering completion either on allowed values (via an inherited
16211 xxx_ALL property) or on existing values in other instances of this property
16212 in the current file.
16214 Throw an error when trying to set a property with an invalid name."
16215 (interactive (list nil nil))
16216 (let ((property (or property (org-read-property-name))))
16217 ;; `org-entry-put' also makes the following check, but this one
16218 ;; avoids polluting `org-last-set-property' and
16219 ;; `org-last-set-property-value' needlessly.
16220 (unless (org--valid-property-p property)
16221 (user-error "Invalid property name: \"%s\"" property))
16222 (let ((value (or value (org-read-property-value property)))
16223 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16224 (setq org-last-set-property property)
16225 (setq org-last-set-property-value (concat property ": " value))
16226 ;; Possibly postprocess the inserted value:
16227 (when fn (setq value (funcall fn value)))
16228 (unless (equal (org-entry-get nil property) value)
16229 (org-entry-put nil property value)))))
16231 (defun org-find-property (property &optional value)
16232 "Find first entry in buffer that sets PROPERTY.
16234 When optional argument VALUE is non-nil, only consider an entry
16235 if it contains PROPERTY set to this value. If PROPERTY should be
16236 explicitly set to nil, use string \"nil\" for VALUE.
16238 Return position where the entry begins, or nil if there is no
16239 such entry. If narrowing is in effect, only search the visible
16240 part of the buffer."
16241 (save-excursion
16242 (goto-char (point-min))
16243 (let ((case-fold-search t)
16244 (re (org-re-property property nil (not value) value)))
16245 (catch 'exit
16246 (while (re-search-forward re nil t)
16247 (when (if value (org-at-property-p)
16248 (org-entry-get (point) property nil t))
16249 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16251 (defun org-delete-property (property)
16252 "In the current entry, delete PROPERTY."
16253 (interactive
16254 (let* ((completion-ignore-case t)
16255 (cat (org-entry-get (point) "CATEGORY"))
16256 (props0 (org-entry-properties nil 'standard))
16257 (props (if cat props0
16258 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16259 (prop (if (< 1 (length props))
16260 (completing-read "Property: " props nil t)
16261 (caar props))))
16262 (list prop)))
16263 (if (not property)
16264 (message "No property to delete in this entry")
16265 (org-entry-delete nil property)
16266 (message "Property \"%s\" deleted" property)))
16268 (defun org-delete-property-globally (property)
16269 "Remove PROPERTY globally, from all entries.
16270 This function ignores narrowing, if any."
16271 (interactive
16272 (let* ((completion-ignore-case t)
16273 (prop (completing-read
16274 "Globally remove property: "
16275 (mapcar #'list (org-buffer-property-keys)))))
16276 (list prop)))
16277 (org-with-wide-buffer
16278 (goto-char (point-min))
16279 (let ((count 0)
16280 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16281 (while (re-search-forward re nil t)
16282 (when (org-entry-delete (point) property) (cl-incf count)))
16283 (message "Property \"%s\" removed from %d entries" property count))))
16285 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16287 (defun org-compute-property-at-point ()
16288 "Compute the property at point.
16289 This looks for an enclosing column format, extracts the operator and
16290 then applies it to the property in the column format's scope."
16291 (interactive)
16292 (unless (org-at-property-p)
16293 (user-error "Not at a property"))
16294 (let ((prop (match-string-no-properties 2)))
16295 (org-columns-get-format-and-top-level)
16296 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16297 (user-error "No operator defined for property %s" prop))
16298 (org-columns-compute prop)))
16300 (defvar org-property-allowed-value-functions nil
16301 "Hook for functions supplying allowed values for a specific property.
16302 The functions must take a single argument, the name of the property, and
16303 return a flat list of allowed values. If \":ETC\" is one of
16304 the values, this means that these values are intended as defaults for
16305 completion, but that other values should be allowed too.
16306 The functions must return nil if they are not responsible for this
16307 property.")
16309 (defun org-property-get-allowed-values (pom property &optional table)
16310 "Get allowed values for the property PROPERTY.
16311 When TABLE is non-nil, return an alist that can directly be used for
16312 completion."
16313 (let (vals)
16314 (cond
16315 ((equal property "TODO")
16316 (setq vals (org-with-point-at pom
16317 (append org-todo-keywords-1 '("")))))
16318 ((equal property "PRIORITY")
16319 (let ((n org-lowest-priority))
16320 (while (>= n org-highest-priority)
16321 (push (char-to-string n) vals)
16322 (setq n (1- n)))))
16323 ((equal property "CATEGORY"))
16324 ((member property org-special-properties))
16325 ((setq vals (run-hook-with-args-until-success
16326 'org-property-allowed-value-functions property)))
16328 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16329 (when (and vals (string-match "\\S-" vals))
16330 (setq vals (car (read-from-string (concat "(" vals ")"))))
16331 (setq vals (mapcar (lambda (x)
16332 (cond ((stringp x) x)
16333 ((numberp x) (number-to-string x))
16334 ((symbolp x) (symbol-name x))
16335 (t "???")))
16336 vals)))))
16337 (when (member ":ETC" vals)
16338 (setq vals (remove ":ETC" vals))
16339 (org-add-props (car vals) '(org-unrestricted t)))
16340 (if table (mapcar 'list vals) vals)))
16342 (defun org-property-previous-allowed-value (&optional _previous)
16343 "Switch to the next allowed value for this property."
16344 (interactive)
16345 (org-property-next-allowed-value t))
16347 (defun org-property-next-allowed-value (&optional previous)
16348 "Switch to the next allowed value for this property."
16349 (interactive)
16350 (unless (org-at-property-p)
16351 (user-error "Not at a property"))
16352 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16353 (key (match-string 2))
16354 (value (match-string 3))
16355 (allowed (or (org-property-get-allowed-values (point) key)
16356 (and (member value '("[ ]" "[-]" "[X]"))
16357 '("[ ]" "[X]"))))
16358 (heading (save-match-data (nth 4 (org-heading-components))))
16359 nval)
16360 (unless allowed
16361 (user-error "Allowed values for this property have not been defined"))
16362 (when previous (setq allowed (reverse allowed)))
16363 (when (member value allowed)
16364 (setq nval (car (cdr (member value allowed)))))
16365 (setq nval (or nval (car allowed)))
16366 (when (equal nval value)
16367 (user-error "Only one allowed value for this property"))
16368 (org-at-property-p)
16369 (replace-match (concat " :" key ": " nval) t t)
16370 (org-indent-line)
16371 (beginning-of-line 1)
16372 (skip-chars-forward " \t")
16373 (when (equal prop org-effort-property)
16374 (org-refresh-property
16375 '((effort . identity)
16376 (effort-minutes . org-duration-to-minutes))
16377 nval)
16378 (when (string= org-clock-current-task heading)
16379 (setq org-clock-effort nval)
16380 (org-clock-update-mode-line)))
16381 (run-hook-with-args 'org-property-changed-functions key nval)))
16383 (defun org-find-olp (path &optional this-buffer)
16384 "Return a marker pointing to the entry at outline path OLP.
16385 If anything goes wrong, throw an error.
16386 You can wrap this call to catch the error like this:
16388 (condition-case msg
16389 (org-mobile-locate-entry (match-string 4))
16390 (error (nth 1 msg)))
16392 The return value will then be either a string with the error message,
16393 or a marker if everything is OK.
16395 If THIS-BUFFER is set, the outline path does not contain a file,
16396 only headings."
16397 (let* ((file (if this-buffer buffer-file-name (pop path)))
16398 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16399 (level 1)
16400 (lmin 1)
16401 (lmax 1)
16402 end found flevel)
16403 (unless buffer (error "File not found :%s" file))
16404 (with-current-buffer buffer
16405 (unless (derived-mode-p 'org-mode)
16406 (error "Buffer %s needs to be in Org mode" buffer))
16407 (org-with-wide-buffer
16408 (goto-char (point-min))
16409 (dolist (heading path)
16410 (let ((re (format org-complex-heading-regexp-format
16411 (regexp-quote heading)))
16412 (cnt 0))
16413 (while (re-search-forward re end t)
16414 (setq level (- (match-end 1) (match-beginning 1)))
16415 (when (and (>= level lmin) (<= level lmax))
16416 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16417 (when (= cnt 0)
16418 (error "Heading not found on level %d: %s" lmax heading))
16419 (when (> cnt 1)
16420 (error "Heading not unique on level %d: %s" lmax heading))
16421 (goto-char found)
16422 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16423 (setq end (save-excursion (org-end-of-subtree t t)))))
16424 (when (org-at-heading-p)
16425 (point-marker))))))
16427 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16428 "Find node HEADING in BUFFER.
16429 Return a marker to the heading if it was found, or nil if not.
16430 If POS-ONLY is set, return just the position instead of a marker.
16432 The heading text must match exact, but it may have a TODO keyword,
16433 a priority cookie and tags in the standard locations."
16434 (with-current-buffer (or buffer (current-buffer))
16435 (org-with-wide-buffer
16436 (goto-char (point-min))
16437 (let (case-fold-search)
16438 (when (re-search-forward
16439 (format org-complex-heading-regexp-format
16440 (regexp-quote heading)) nil t)
16441 (if pos-only
16442 (match-beginning 0)
16443 (move-marker (make-marker) (match-beginning 0))))))))
16445 (defun org-find-exact-heading-in-directory (heading &optional dir)
16446 "Find Org node headline HEADING in all .org files in directory DIR.
16447 When the target headline is found, return a marker to this location."
16448 (let ((files (directory-files (or dir default-directory)
16449 t "\\`[^.#].*\\.org\\'"))
16450 visiting m buffer)
16451 (catch 'found
16452 (dolist (file files)
16453 (message "trying %s" file)
16454 (setq visiting (org-find-base-buffer-visiting file))
16455 (setq buffer (or visiting (find-file-noselect file)))
16456 (setq m (org-find-exact-headline-in-buffer
16457 heading buffer))
16458 (when (and (not m) (not visiting)) (kill-buffer buffer))
16459 (and m (throw 'found m))))))
16461 (defun org-find-entry-with-id (ident)
16462 "Locate the entry that contains the ID property with exact value IDENT.
16463 IDENT can be a string, a symbol or a number, this function will search for
16464 the string representation of it.
16465 Return the position where this entry starts, or nil if there is no such entry."
16466 (interactive "sID: ")
16467 (let ((id (cond
16468 ((stringp ident) ident)
16469 ((symbolp ident) (symbol-name ident))
16470 ((numberp ident) (number-to-string ident))
16471 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16472 (org-with-wide-buffer (org-find-property "ID" id))))
16474 ;;;; Timestamps
16476 (defvar org-last-changed-timestamp nil)
16477 (defvar org-last-inserted-timestamp nil
16478 "The last time stamp inserted with `org-insert-time-stamp'.")
16480 (defun org-time-stamp (arg &optional inactive)
16481 "Prompt for a date/time and insert a time stamp.
16483 If the user specifies a time like HH:MM or if this command is
16484 called with at least one prefix argument, the time stamp contains
16485 the date and the time. Otherwise, only the date is included.
16487 All parts of a date not specified by the user are filled in from
16488 the timestamp at point, if any, or the current date/time
16489 otherwise.
16491 If there is already a timestamp at the cursor, it is replaced.
16493 With two universal prefix arguments, insert an active timestamp
16494 with the current time without prompting the user.
16496 When called from lisp, the timestamp is inactive if INACTIVE is
16497 non-nil."
16498 (interactive "P")
16499 (let* ((ts (cond
16500 ((org-at-date-range-p t)
16501 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16502 ((org-at-timestamp-p 'lax) (match-string 0))))
16503 ;; Default time is either the timestamp at point or today.
16504 ;; When entering a range, only the range start is considered.
16505 (default-time (if (not ts) (current-time)
16506 (apply #'encode-time (org-parse-time-string ts))))
16507 (default-input (and ts (org-get-compact-tod ts)))
16508 (repeater (and ts
16509 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16510 (match-string 0 ts)))
16511 org-time-was-given
16512 org-end-time-was-given
16513 (time
16514 (and (if (equal arg '(16)) (current-time)
16515 ;; Preserve `this-command' and `last-command'.
16516 (let ((this-command this-command)
16517 (last-command last-command))
16518 (org-read-date
16519 arg 'totime nil nil default-time default-input
16520 inactive))))))
16521 (cond
16522 ((and ts
16523 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16524 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16525 (insert "--")
16526 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16528 ;; Make sure we're on a timestamp. When in the middle of a date
16529 ;; range, move arbitrarily to range end.
16530 (unless (org-at-timestamp-p 'lax)
16531 (skip-chars-forward "-")
16532 (org-at-timestamp-p 'lax))
16533 (replace-match "")
16534 (setq org-last-changed-timestamp
16535 (org-insert-time-stamp
16536 time (or org-time-was-given arg)
16537 inactive nil nil (list org-end-time-was-given)))
16538 (when repeater
16539 (backward-char)
16540 (insert " " repeater)
16541 (setq org-last-changed-timestamp
16542 (concat (substring org-last-inserted-timestamp 0 -1)
16543 " " repeater ">")))
16544 (message "Timestamp updated"))
16545 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16546 (t (org-insert-time-stamp
16547 time (or org-time-was-given arg) inactive nil nil
16548 (list org-end-time-was-given))))))
16550 ;; FIXME: can we use this for something else, like computing time differences?
16551 (defun org-get-compact-tod (s)
16552 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16553 (let* ((t1 (match-string 1 s))
16554 (h1 (string-to-number (match-string 2 s)))
16555 (m1 (string-to-number (match-string 3 s)))
16556 (t2 (and (match-end 4) (match-string 5 s)))
16557 (h2 (and t2 (string-to-number (match-string 6 s))))
16558 (m2 (and t2 (string-to-number (match-string 7 s))))
16559 dh dm)
16560 (if (not t2)
16562 (setq dh (- h2 h1) dm (- m2 m1))
16563 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16564 (concat t1 "+" (number-to-string dh)
16565 (and (/= 0 dm) (format ":%02d" dm)))))))
16567 (defun org-time-stamp-inactive (&optional arg)
16568 "Insert an inactive time stamp.
16569 An inactive time stamp is enclosed in square brackets instead of angle
16570 brackets. It is inactive in the sense that it does not trigger agenda entries,
16571 does not link to the calendar and cannot be changed with the S-cursor keys.
16572 So these are more for recording a certain time/date."
16573 (interactive "P")
16574 (org-time-stamp arg 'inactive))
16576 (defvar org-date-ovl (make-overlay 1 1))
16577 (overlay-put org-date-ovl 'face 'org-date-selected)
16578 (delete-overlay org-date-ovl)
16580 (defvar org-ans1) ; dynamically scoped parameter
16581 (defvar org-ans2) ; dynamically scoped parameter
16583 (defvar org-plain-time-of-day-regexp) ; defined below
16585 (defvar org-overriding-default-time nil) ; dynamically scoped
16586 (defvar org-read-date-overlay nil)
16587 (defvar org-dcst nil) ; dynamically scoped
16588 (defvar org-read-date-history nil)
16589 (defvar org-read-date-final-answer nil)
16590 (defvar org-read-date-analyze-futurep nil)
16591 (defvar org-read-date-analyze-forced-year nil)
16592 (defvar org-read-date-inactive)
16594 (defvar org-read-date-minibuffer-local-map
16595 (let* ((map (make-sparse-keymap)))
16596 (set-keymap-parent map minibuffer-local-map)
16597 (org-defkey map (kbd ".")
16598 (lambda () (interactive)
16599 ;; Are we at the beginning of the prompt?
16600 (if (looking-back "^[^:]+: "
16601 (let ((inhibit-field-text-motion t))
16602 (line-beginning-position)))
16603 (org-eval-in-calendar '(calendar-goto-today))
16604 (insert "."))))
16605 (org-defkey map (kbd "C-.")
16606 (lambda () (interactive)
16607 (org-eval-in-calendar '(calendar-goto-today))))
16608 (org-defkey map [(meta shift left)]
16609 (lambda () (interactive)
16610 (org-eval-in-calendar '(calendar-backward-month 1))))
16611 (org-defkey map [(meta shift right)]
16612 (lambda () (interactive)
16613 (org-eval-in-calendar '(calendar-forward-month 1))))
16614 (org-defkey map [(meta shift up)]
16615 (lambda () (interactive)
16616 (org-eval-in-calendar '(calendar-backward-year 1))))
16617 (org-defkey map [(meta shift down)]
16618 (lambda () (interactive)
16619 (org-eval-in-calendar '(calendar-forward-year 1))))
16620 (org-defkey map [?\e (shift left)]
16621 (lambda () (interactive)
16622 (org-eval-in-calendar '(calendar-backward-month 1))))
16623 (org-defkey map [?\e (shift right)]
16624 (lambda () (interactive)
16625 (org-eval-in-calendar '(calendar-forward-month 1))))
16626 (org-defkey map [?\e (shift up)]
16627 (lambda () (interactive)
16628 (org-eval-in-calendar '(calendar-backward-year 1))))
16629 (org-defkey map [?\e (shift down)]
16630 (lambda () (interactive)
16631 (org-eval-in-calendar '(calendar-forward-year 1))))
16632 (org-defkey map [(shift up)]
16633 (lambda () (interactive)
16634 (org-eval-in-calendar '(calendar-backward-week 1))))
16635 (org-defkey map [(shift down)]
16636 (lambda () (interactive)
16637 (org-eval-in-calendar '(calendar-forward-week 1))))
16638 (org-defkey map [(shift left)]
16639 (lambda () (interactive)
16640 (org-eval-in-calendar '(calendar-backward-day 1))))
16641 (org-defkey map [(shift right)]
16642 (lambda () (interactive)
16643 (org-eval-in-calendar '(calendar-forward-day 1))))
16644 (org-defkey map "!"
16645 (lambda () (interactive)
16646 (org-eval-in-calendar '(diary-view-entries))
16647 (message "")))
16648 (org-defkey map ">"
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-scroll-left 1))))
16651 (org-defkey map "<"
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-scroll-right 1))))
16654 (org-defkey map "\C-v"
16655 (lambda () (interactive)
16656 (org-eval-in-calendar
16657 '(calendar-scroll-left-three-months 1))))
16658 (org-defkey map "\M-v"
16659 (lambda () (interactive)
16660 (org-eval-in-calendar
16661 '(calendar-scroll-right-three-months 1))))
16662 map)
16663 "Keymap for minibuffer commands when using `org-read-date'.")
16665 (defvar org-def)
16666 (defvar org-defdecode)
16667 (defvar org-with-time)
16669 (defvar calendar-setup) ; Dynamically scoped.
16670 (defun org-read-date (&optional with-time to-time from-string prompt
16671 default-time default-input inactive)
16672 "Read a date, possibly a time, and make things smooth for the user.
16673 The prompt will suggest to enter an ISO date, but you can also enter anything
16674 which will at least partially be understood by `parse-time-string'.
16675 Unrecognized parts of the date will default to the current day, month, year,
16676 hour and minute. If this command is called to replace a timestamp at point,
16677 or to enter the second timestamp of a range, the default time is taken
16678 from the existing stamp. Furthermore, the command prefers the future,
16679 so if you are giving a date where the year is not given, and the day-month
16680 combination is already past in the current year, it will assume you
16681 mean next year. For details, see the manual. A few examples:
16683 3-2-5 --> 2003-02-05
16684 feb 15 --> currentyear-02-15
16685 2/15 --> currentyear-02-15
16686 sep 12 9 --> 2009-09-12
16687 12:45 --> today 12:45
16688 22 sept 0:34 --> currentyear-09-22 0:34
16689 12 --> currentyear-currentmonth-12
16690 Fri --> nearest Friday after today
16691 -Tue --> last Tuesday
16692 etc.
16694 Furthermore you can specify a relative date by giving, as the *first* thing
16695 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16696 change in days weeks, months, years.
16697 With a single plus or minus, the date is relative to today. With a double
16698 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16699 +4d --> four days from today
16700 +4 --> same as above
16701 +2w --> two weeks from today
16702 ++5 --> five days from default date
16704 The function understands only English month and weekday abbreviations.
16706 While prompting, a calendar is popped up - you can also select the
16707 date with the mouse (button 1). The calendar shows a period of three
16708 months. To scroll it to other months, use the keys `>' and `<'.
16709 If you don't like the calendar, turn it off with
16710 (setq org-read-date-popup-calendar nil)
16712 With optional argument TO-TIME, the date will immediately be converted
16713 to an internal time.
16714 With an optional argument WITH-TIME, the prompt will suggest to
16715 also insert a time. Note that when WITH-TIME is not set, you can
16716 still enter a time, and this function will inform the calling routine
16717 about this change. The calling routine may then choose to change the
16718 format used to insert the time stamp into the buffer to include the time.
16719 With optional argument FROM-STRING, read from this string instead from
16720 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16721 the time/date that is used for everything that is not specified by the
16722 user."
16723 (require 'parse-time)
16724 (let* ((org-with-time with-time)
16725 (org-time-stamp-rounding-minutes
16726 (if (equal org-with-time '(16))
16727 '(0 0)
16728 org-time-stamp-rounding-minutes))
16729 (org-dcst org-display-custom-times)
16730 (ct (org-current-time))
16731 (org-def (or org-overriding-default-time default-time ct))
16732 (org-defdecode (decode-time org-def))
16733 (cur-frame (selected-frame))
16734 (mouse-autoselect-window nil) ; Don't let the mouse jump
16735 (calendar-setup
16736 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16737 (calendar-move-hook nil)
16738 (calendar-view-diary-initially-flag nil)
16739 (calendar-view-holidays-initially-flag nil)
16740 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16741 ;; Rationalize `org-def' and `org-defdecode', if required.
16742 (when (< (nth 2 org-defdecode) org-extend-today-until)
16743 (setf (nth 2 org-defdecode) -1)
16744 (setf (nth 1 org-defdecode) 59)
16745 (setq org-def (apply #'encode-time org-defdecode))
16746 (setq org-defdecode (decode-time org-def)))
16747 (let* ((timestr (format-time-string
16748 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16749 org-def))
16750 (prompt (concat (if prompt (concat prompt " ") "")
16751 (format "Date+time [%s]: " timestr))))
16752 (cond
16753 (from-string (setq ans from-string))
16754 (org-read-date-popup-calendar
16755 (save-excursion
16756 (save-window-excursion
16757 (calendar)
16758 (when (eq calendar-setup 'calendar-only)
16759 (setq cal-frame
16760 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16761 (select-frame cal-frame))
16762 (org-eval-in-calendar '(setq cursor-type nil) t)
16763 (unwind-protect
16764 (progn
16765 (calendar-forward-day (- (time-to-days org-def)
16766 (calendar-absolute-from-gregorian
16767 (calendar-current-date))))
16768 (org-eval-in-calendar nil t)
16769 (let* ((old-map (current-local-map))
16770 (map (copy-keymap calendar-mode-map))
16771 (minibuffer-local-map
16772 (copy-keymap org-read-date-minibuffer-local-map)))
16773 (org-defkey map (kbd "RET") 'org-calendar-select)
16774 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16775 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16776 (unwind-protect
16777 (progn
16778 (use-local-map map)
16779 (setq org-read-date-inactive inactive)
16780 (add-hook 'post-command-hook 'org-read-date-display)
16781 (setq org-ans0
16782 (read-string prompt
16783 default-input
16784 'org-read-date-history
16785 nil))
16786 ;; org-ans0: from prompt
16787 ;; org-ans1: from mouse click
16788 ;; org-ans2: from calendar motion
16789 (setq ans
16790 (concat org-ans0 " " (or org-ans1 org-ans2))))
16791 (remove-hook 'post-command-hook 'org-read-date-display)
16792 (use-local-map old-map)
16793 (when org-read-date-overlay
16794 (delete-overlay org-read-date-overlay)
16795 (setq org-read-date-overlay nil)))))
16796 (bury-buffer "*Calendar*")
16797 (when cal-frame
16798 (delete-frame cal-frame)
16799 (select-frame-set-input-focus cur-frame))))))
16801 (t ; Naked prompt only
16802 (unwind-protect
16803 (setq ans (read-string prompt default-input
16804 'org-read-date-history timestr))
16805 (when org-read-date-overlay
16806 (delete-overlay org-read-date-overlay)
16807 (setq org-read-date-overlay nil))))))
16809 (setq final (org-read-date-analyze ans org-def org-defdecode))
16811 (when org-read-date-analyze-forced-year
16812 (message "Year was forced into %s"
16813 (if org-read-date-force-compatible-dates
16814 "compatible range (1970-2037)"
16815 "range representable on this machine"))
16816 (ding))
16818 ;; One round trip to get rid of 34th of August and stuff like that....
16819 (setq final (decode-time (apply 'encode-time final)))
16821 (setq org-read-date-final-answer ans)
16823 (if to-time
16824 (apply 'encode-time final)
16825 (if (and (boundp 'org-time-was-given) org-time-was-given)
16826 (format "%04d-%02d-%02d %02d:%02d"
16827 (nth 5 final) (nth 4 final) (nth 3 final)
16828 (nth 2 final) (nth 1 final))
16829 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16831 (defun org-read-date-display ()
16832 "Display the current date prompt interpretation in the minibuffer."
16833 (when org-read-date-display-live
16834 (when org-read-date-overlay
16835 (delete-overlay org-read-date-overlay))
16836 (when (minibufferp (current-buffer))
16837 (save-excursion
16838 (end-of-line 1)
16839 (while (not (equal (buffer-substring
16840 (max (point-min) (- (point) 4)) (point))
16841 " "))
16842 (insert " ")))
16843 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16844 " " (or org-ans1 org-ans2)))
16845 (org-end-time-was-given nil)
16846 (f (org-read-date-analyze ans org-def org-defdecode))
16847 (fmts (if org-dcst
16848 org-time-stamp-custom-formats
16849 org-time-stamp-formats))
16850 (fmt (if (or org-with-time
16851 (and (boundp 'org-time-was-given) org-time-was-given))
16852 (cdr fmts)
16853 (car fmts)))
16854 (txt (format-time-string fmt (apply 'encode-time f)))
16855 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16856 (txt (concat "=> " txt)))
16857 (when (and org-end-time-was-given
16858 (string-match org-plain-time-of-day-regexp txt))
16859 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16860 org-end-time-was-given
16861 (substring txt (match-end 0)))))
16862 (when org-read-date-analyze-futurep
16863 (setq txt (concat txt " (=>F)")))
16864 (setq org-read-date-overlay
16865 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16866 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16868 (defun org-read-date-analyze (ans def defdecode)
16869 "Analyze the combined answer of the date prompt."
16870 ;; FIXME: cleanup and comment
16871 ;; Pass `current-time' result to `decode-time' (instead of calling
16872 ;; without arguments) so that only `current-time' has to be
16873 ;; overridden in tests.
16874 (let ((org-def def)
16875 (org-defdecode defdecode)
16876 (nowdecode (decode-time (current-time)))
16877 delta deltan deltaw deltadef year month day
16878 hour minute second wday pm h2 m2 tl wday1
16879 iso-year iso-weekday iso-week iso-date futurep kill-year)
16880 (setq org-read-date-analyze-futurep nil
16881 org-read-date-analyze-forced-year nil)
16882 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16883 (setq ans "+0"))
16885 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16886 (setq ans (replace-match "" t t ans)
16887 deltan (car delta)
16888 deltaw (nth 1 delta)
16889 deltadef (nth 2 delta)))
16891 ;; Check if there is an iso week date in there. If yes, store the
16892 ;; info and postpone interpreting it until the rest of the parsing
16893 ;; is done.
16894 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16895 (setq iso-year (when (match-end 1)
16896 (org-small-year-to-year
16897 (string-to-number (match-string 1 ans))))
16898 iso-weekday (when (match-end 3)
16899 (string-to-number (match-string 3 ans)))
16900 iso-week (string-to-number (match-string 2 ans)))
16901 (setq ans (replace-match "" t t ans)))
16903 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16904 (when (string-match
16905 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16906 (setq year (if (match-end 2)
16907 (string-to-number (match-string 2 ans))
16908 (progn (setq kill-year t)
16909 (string-to-number (format-time-string "%Y"))))
16910 month (string-to-number (match-string 3 ans))
16911 day (string-to-number (match-string 4 ans)))
16912 (setq year (org-small-year-to-year year))
16913 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16914 t nil ans)))
16916 ;; Help matching dotted european dates
16917 (when (string-match
16918 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16919 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16920 (setq kill-year t)
16921 (string-to-number (format-time-string "%Y")))
16922 day (string-to-number (match-string 1 ans))
16923 month (string-to-number (match-string 2 ans))
16924 ans (replace-match (format "%04d-%02d-%02d" year month day)
16925 t nil ans)))
16927 ;; Help matching american dates, like 5/30 or 5/30/7
16928 (when (string-match
16929 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16930 (setq year (if (match-end 4)
16931 (string-to-number (match-string 4 ans))
16932 (progn (setq kill-year t)
16933 (string-to-number (format-time-string "%Y"))))
16934 month (string-to-number (match-string 1 ans))
16935 day (string-to-number (match-string 2 ans)))
16936 (setq year (org-small-year-to-year year))
16937 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16938 t nil ans)))
16939 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16940 ;; If there is a time with am/pm, and *no* time without it, we convert
16941 ;; so that matching will be successful.
16942 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16943 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16944 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16945 (setq hour (string-to-number (match-string 1 ans))
16946 minute (if (match-end 3)
16947 (string-to-number (match-string 3 ans))
16949 pm (equal ?p
16950 (string-to-char (downcase (match-string 4 ans)))))
16951 (if (and (= hour 12) (not pm))
16952 (setq hour 0)
16953 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16954 (setq ans (replace-match (format "%02d:%02d" hour minute)
16955 t t ans))))
16957 ;; Check if a time range is given as a duration
16958 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16959 (setq hour (string-to-number (match-string 1 ans))
16960 h2 (+ hour (string-to-number (match-string 3 ans)))
16961 minute (string-to-number (match-string 2 ans))
16962 m2 (+ minute (if (match-end 5) (string-to-number
16963 (match-string 5 ans))0)))
16964 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16965 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16966 t t ans)))
16968 ;; Check if there is a time range
16969 (when (boundp 'org-end-time-was-given)
16970 (setq org-time-was-given nil)
16971 (when (and (string-match org-plain-time-of-day-regexp ans)
16972 (match-end 8))
16973 (setq org-end-time-was-given (match-string 8 ans))
16974 (setq ans (concat (substring ans 0 (match-beginning 7))
16975 (substring ans (match-end 7))))))
16977 (setq tl (parse-time-string ans)
16978 day (or (nth 3 tl) (nth 3 org-defdecode))
16979 month
16980 (cond ((nth 4 tl))
16981 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16982 ;; Day was specified. Make sure DAY+MONTH
16983 ;; combination happens in the future.
16984 ((nth 3 tl)
16985 (setq futurep t)
16986 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16987 (nth 4 nowdecode)))
16988 (t (nth 4 org-defdecode)))
16989 year
16990 (cond ((and (not kill-year) (nth 5 tl)))
16991 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16992 ;; Month was guessed in the future and is at least
16993 ;; equal to NOWDECODE's. Fix year accordingly.
16994 (futurep
16995 (if (or (> month (nth 4 nowdecode))
16996 (>= day (nth 3 nowdecode)))
16997 (nth 5 nowdecode)
16998 (1+ (nth 5 nowdecode))))
16999 ;; Month was specified. Make sure MONTH+YEAR
17000 ;; combination happens in the future.
17001 ((nth 4 tl)
17002 (setq futurep t)
17003 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17004 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17005 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17006 (t (nth 5 nowdecode))))
17007 (t (nth 5 org-defdecode)))
17008 hour (or (nth 2 tl) (nth 2 org-defdecode))
17009 minute (or (nth 1 tl) (nth 1 org-defdecode))
17010 second (or (nth 0 tl) 0)
17011 wday (nth 6 tl))
17013 (when (and (eq org-read-date-prefer-future 'time)
17014 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17015 (equal day (nth 3 nowdecode))
17016 (equal month (nth 4 nowdecode))
17017 (equal year (nth 5 nowdecode))
17018 (nth 2 tl)
17019 (or (< (nth 2 tl) (nth 2 nowdecode))
17020 (and (= (nth 2 tl) (nth 2 nowdecode))
17021 (nth 1 tl)
17022 (< (nth 1 tl) (nth 1 nowdecode)))))
17023 (setq day (1+ day)
17024 futurep t))
17026 ;; Special date definitions below
17027 (cond
17028 (iso-week
17029 ;; There was an iso week
17030 (require 'cal-iso)
17031 (setq futurep nil)
17032 (setq year (or iso-year year)
17033 day (or iso-weekday wday 1)
17034 wday nil ; to make sure that the trigger below does not match
17035 iso-date (calendar-gregorian-from-absolute
17036 (calendar-iso-to-absolute
17037 (list iso-week day year))))
17038 ; FIXME: Should we also push ISO weeks into the future?
17039 ; (when (and org-read-date-prefer-future
17040 ; (not iso-year)
17041 ; (< (calendar-absolute-from-gregorian iso-date)
17042 ; (time-to-days (current-time))))
17043 ; (setq year (1+ year)
17044 ; iso-date (calendar-gregorian-from-absolute
17045 ; (calendar-iso-to-absolute
17046 ; (list iso-week day year)))))
17047 (setq month (car iso-date)
17048 year (nth 2 iso-date)
17049 day (nth 1 iso-date)))
17050 (deltan
17051 (setq futurep nil)
17052 (unless deltadef
17053 ;; Pass `current-time' result to `decode-time' (instead of
17054 ;; calling without arguments) so that only `current-time' has
17055 ;; to be overridden in tests.
17056 (let ((now (decode-time (current-time))))
17057 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17058 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17059 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17060 ((equal deltaw "m") (setq month (+ month deltan)))
17061 ((equal deltaw "y") (setq year (+ year deltan)))))
17062 ((and wday (not (nth 3 tl)))
17063 ;; Weekday was given, but no day, so pick that day in the week
17064 ;; on or after the derived date.
17065 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17066 (unless (equal wday wday1)
17067 (setq day (+ day (% (- wday wday1 -7) 7))))))
17068 (when (and (boundp 'org-time-was-given)
17069 (nth 2 tl))
17070 (setq org-time-was-given t))
17071 (when (< year 100) (setq year (+ 2000 year)))
17072 ;; Check of the date is representable
17073 (if org-read-date-force-compatible-dates
17074 (progn
17075 (when (< year 1970)
17076 (setq year 1970 org-read-date-analyze-forced-year t))
17077 (when (> year 2037)
17078 (setq year 2037 org-read-date-analyze-forced-year t)))
17079 (condition-case nil
17080 (ignore (encode-time second minute hour day month year))
17081 (error
17082 (setq year (nth 5 org-defdecode))
17083 (setq org-read-date-analyze-forced-year t))))
17084 (setq org-read-date-analyze-futurep futurep)
17085 (list second minute hour day month year)))
17087 (defvar parse-time-weekdays)
17088 (defun org-read-date-get-relative (s today default)
17089 "Check string S for special relative date string.
17090 TODAY and DEFAULT are internal times, for today and for a default.
17091 Return shift list (N what def-flag)
17092 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17093 N is the number of WHATs to shift.
17094 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17095 the DEFAULT date rather than TODAY."
17096 (require 'parse-time)
17097 (when (and
17098 (string-match
17099 (concat
17100 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17101 "\\([0-9]+\\)?"
17102 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17103 "\\([ \t]\\|$\\)") s)
17104 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17105 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17106 (string-to-char (substring (match-string 1 s) -1))
17107 ?+))
17108 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17109 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17110 (what (if (match-end 3) (match-string 3 s) "d"))
17111 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17112 (date (if rel default today))
17113 (wday (nth 6 (decode-time date)))
17114 delta)
17115 (if wday1
17116 (progn
17117 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17118 (when (= delta 0) (setq delta 7))
17119 (when (= dir ?-)
17120 (setq delta (- delta 7))
17121 (when (= delta 0) (setq delta -7)))
17122 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17123 (list delta "d" rel))
17124 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17126 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17127 "Turn a user-specified date into the internal representation.
17128 The internal representation needed by the calendar is (month day year).
17129 This is a wrapper to handle the brain-dead convention in calendar that
17130 user function argument order change dependent on argument order."
17131 (pcase calendar-date-style
17132 (`american (list arg1 arg2 arg3))
17133 (`european (list arg2 arg1 arg3))
17134 (`iso (list arg2 arg3 arg1))))
17136 (defun org-eval-in-calendar (form &optional keepdate)
17137 "Eval FORM in the calendar window and return to current window.
17138 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17139 (let ((sf (selected-frame))
17140 (sw (selected-window)))
17141 (select-window (get-buffer-window "*Calendar*" t))
17142 (eval form)
17143 (when (and (not keepdate) (calendar-cursor-to-date))
17144 (let* ((date (calendar-cursor-to-date))
17145 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17146 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17147 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17148 (select-window sw)
17149 (select-frame-set-input-focus sf)))
17151 (defun org-calendar-select ()
17152 "Return to `org-read-date' with the date currently selected.
17153 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17154 (interactive)
17155 (when (calendar-cursor-to-date)
17156 (let* ((date (calendar-cursor-to-date))
17157 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17158 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17159 (when (active-minibuffer-window) (exit-minibuffer))))
17161 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17162 "Insert a date stamp for the date given by the internal TIME.
17163 See `format-time-string' for the format of TIME.
17164 WITH-HM means use the stamp format that includes the time of the day.
17165 INACTIVE means use square brackets instead of angular ones, so that the
17166 stamp will not contribute to the agenda.
17167 PRE and POST are optional strings to be inserted before and after the
17168 stamp.
17169 The command returns the inserted time stamp."
17170 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17171 stamp)
17172 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17173 (insert-before-markers (or pre ""))
17174 (when (listp extra)
17175 (setq extra (car extra))
17176 (if (and (stringp extra)
17177 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17178 (setq extra (format "-%02d:%02d"
17179 (string-to-number (match-string 1 extra))
17180 (string-to-number (match-string 2 extra))))
17181 (setq extra nil)))
17182 (when extra
17183 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17184 (insert-before-markers (setq stamp (format-time-string fmt time)))
17185 (insert-before-markers (or post ""))
17186 (setq org-last-inserted-timestamp stamp)))
17188 (defun org-toggle-time-stamp-overlays ()
17189 "Toggle the use of custom time stamp formats."
17190 (interactive)
17191 (setq org-display-custom-times (not org-display-custom-times))
17192 (unless org-display-custom-times
17193 (let ((p (point-min)) (bmp (buffer-modified-p)))
17194 (while (setq p (next-single-property-change p 'display))
17195 (when (and (get-text-property p 'display)
17196 (eq (get-text-property p 'face) 'org-date))
17197 (remove-text-properties
17198 p (setq p (next-single-property-change p 'display))
17199 '(display t))))
17200 (set-buffer-modified-p bmp)))
17201 (org-restart-font-lock)
17202 (setq org-table-may-need-update t)
17203 (if org-display-custom-times
17204 (message "Time stamps are overlaid with custom format")
17205 (message "Time stamp overlays removed")))
17207 (defun org-display-custom-time (beg end)
17208 "Overlay modified time stamp format over timestamp between BEG and END."
17209 (let* ((ts (buffer-substring beg end))
17210 t1 with-hm tf time str (off 0))
17211 (save-match-data
17212 (setq t1 (org-parse-time-string ts t))
17213 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17214 (setq off (- (match-end 0) (match-beginning 0)))))
17215 (setq end (- end off))
17216 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17217 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17218 time (org-fix-decoded-time t1)
17219 str (org-add-props
17220 (format-time-string
17221 (substring tf 1 -1) (apply 'encode-time time))
17222 nil 'mouse-face 'highlight))
17223 (put-text-property beg end 'display str)))
17225 (defun org-fix-decoded-time (time)
17226 "Set 0 instead of nil for the first 6 elements of time.
17227 Don't touch the rest."
17228 (let ((n 0))
17229 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17231 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17232 "Difference between TIMESTAMP-STRING and now in days.
17233 If SECONDS is non-nil, return the difference in seconds."
17234 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17235 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17236 (funcall fdiff (current-time)))))
17238 (defun org-deadline-close-p (timestamp-string &optional ndays)
17239 "Is the time in TIMESTAMP-STRING close to the current date?"
17240 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17241 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17242 (not (org-entry-is-done-p))))
17244 (defun org-get-wdays (ts &optional delay zero-delay)
17245 "Get the deadline lead time appropriate for timestring TS.
17246 When DELAY is non-nil, get the delay time for scheduled items
17247 instead of the deadline lead time. When ZERO-DELAY is non-nil
17248 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17249 don't try to find the delay cookie in the scheduled timestamp."
17250 (let ((tv (if delay org-scheduled-delay-days
17251 org-deadline-warning-days)))
17252 (cond
17253 ((or (and delay (< tv 0))
17254 (and delay zero-delay (<= tv 0))
17255 (and (not delay) (<= tv 0)))
17256 ;; Enforce this value no matter what
17257 (- tv))
17258 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17259 ;; lead time is specified.
17260 (floor (* (string-to-number (match-string 1 ts))
17261 (cdr (assoc (match-string 2 ts)
17262 '(("d" . 1) ("w" . 7)
17263 ("m" . 30.4) ("y" . 365.25)
17264 ("h" . 0.041667)))))))
17265 ;; go for the default.
17266 (t tv))))
17268 (defun org-calendar-select-mouse (ev)
17269 "Return to `org-read-date' with the date currently selected.
17270 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17271 (interactive "e")
17272 (mouse-set-point ev)
17273 (when (calendar-cursor-to-date)
17274 (let* ((date (calendar-cursor-to-date))
17275 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17276 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17277 (when (active-minibuffer-window) (exit-minibuffer))))
17279 (defun org-check-deadlines (ndays)
17280 "Check if there are any deadlines due or past due.
17281 A deadline is considered due if it happens within `org-deadline-warning-days'
17282 days from today's date. If the deadline appears in an entry marked DONE,
17283 it is not shown. A numeric prefix argument NDAYS can be used to test that
17284 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17285 are shown."
17286 (interactive "P")
17287 (let* ((org-warn-days
17288 (cond
17289 ((equal ndays '(4)) 100000)
17290 (ndays (prefix-numeric-value ndays))
17291 (t (abs org-deadline-warning-days))))
17292 (case-fold-search nil)
17293 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17294 (callback
17295 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17296 (message "%d deadlines past-due or due within %d days"
17297 (org-occur regexp nil callback)
17298 org-warn-days)))
17300 (defsubst org-re-timestamp (type)
17301 "Return a regexp for timestamp TYPE.
17302 Allowed values for TYPE are:
17304 all: all timestamps
17305 active: only active timestamps (<...>)
17306 inactive: only inactive timestamps ([...])
17307 scheduled: only scheduled timestamps
17308 deadline: only deadline timestamps
17309 closed: only closed time-stamps
17311 When TYPE is nil, fall back on returning a regexp that matches
17312 both scheduled and deadline timestamps."
17313 (cl-case type
17314 (all org-ts-regexp-both)
17315 (active org-ts-regexp)
17316 (inactive org-ts-regexp-inactive)
17317 (scheduled org-scheduled-time-regexp)
17318 (deadline org-deadline-time-regexp)
17319 (closed org-closed-time-regexp)
17320 (otherwise
17321 (concat "\\<"
17322 (regexp-opt (list org-deadline-string org-scheduled-string))
17323 " *<\\([^>]+\\)>"))))
17325 (defun org-check-before-date (d)
17326 "Check if there are deadlines or scheduled entries before date D."
17327 (interactive (list (org-read-date)))
17328 (let* ((case-fold-search nil)
17329 (regexp (org-re-timestamp org-ts-type))
17330 (ts-type org-ts-type)
17331 (callback
17332 (lambda ()
17333 (let ((match (match-string 1)))
17334 (and (if (memq ts-type '(active inactive all))
17335 (eq (org-element-type (save-excursion
17336 (backward-char)
17337 (org-element-context)))
17338 'timestamp)
17339 (org-at-planning-p))
17340 (time-less-p
17341 (org-time-string-to-time match t)
17342 (org-time-string-to-time d t)))))))
17343 (message "%d entries before %s"
17344 (org-occur regexp nil callback)
17345 d)))
17347 (defun org-check-after-date (d)
17348 "Check if there are deadlines or scheduled entries after date D."
17349 (interactive (list (org-read-date)))
17350 (let* ((case-fold-search nil)
17351 (regexp (org-re-timestamp org-ts-type))
17352 (ts-type org-ts-type)
17353 (callback
17354 (lambda ()
17355 (let ((match (match-string 1)))
17356 (and (if (memq ts-type '(active inactive all))
17357 (eq (org-element-type (save-excursion
17358 (backward-char)
17359 (org-element-context)))
17360 'timestamp)
17361 (org-at-planning-p))
17362 (not (time-less-p
17363 (org-time-string-to-time match t)
17364 (org-time-string-to-time d t))))))))
17365 (message "%d entries after %s"
17366 (org-occur regexp nil callback)
17367 d)))
17369 (defun org-check-dates-range (start-date end-date)
17370 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17371 (interactive (list (org-read-date nil nil nil "Range starts")
17372 (org-read-date nil nil nil "Range end")))
17373 (let ((case-fold-search nil)
17374 (regexp (org-re-timestamp org-ts-type))
17375 (callback
17376 (let ((type org-ts-type))
17377 (lambda ()
17378 (let ((match (match-string 1)))
17379 (and
17380 (if (memq type '(active inactive all))
17381 (eq (org-element-type (save-excursion
17382 (backward-char)
17383 (org-element-context)))
17384 'timestamp)
17385 (org-at-planning-p))
17386 (not (time-less-p
17387 (org-time-string-to-time match t)
17388 (org-time-string-to-time start-date t)))
17389 (time-less-p
17390 (org-time-string-to-time match t)
17391 (org-time-string-to-time end-date t))))))))
17392 (message "%d entries between %s and %s"
17393 (org-occur regexp nil callback) start-date end-date)))
17395 (defun org-evaluate-time-range (&optional to-buffer)
17396 "Evaluate a time range by computing the difference between start and end.
17397 Normally the result is just printed in the echo area, but with prefix arg
17398 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17399 If the time range is actually in a table, the result is inserted into the
17400 next column.
17401 For time difference computation, a year is assumed to be exactly 365
17402 days in order to avoid rounding problems."
17403 (interactive "P")
17405 (org-clock-update-time-maybe)
17406 (save-excursion
17407 (unless (org-at-date-range-p t)
17408 (goto-char (point-at-bol))
17409 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17410 (unless (org-at-date-range-p t)
17411 (user-error "Not at a time-stamp range, and none found in current line")))
17412 (let* ((ts1 (match-string 1))
17413 (ts2 (match-string 2))
17414 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17415 (match-end (match-end 0))
17416 (time1 (org-time-string-to-time ts1))
17417 (time2 (org-time-string-to-time ts2))
17418 (t1 (float-time time1))
17419 (t2 (float-time time2))
17420 (diff (abs (- t2 t1)))
17421 (negative (< (- t2 t1) 0))
17422 ;; (ys (floor (* 365 24 60 60)))
17423 (ds (* 24 60 60))
17424 (hs (* 60 60))
17425 (fy "%dy %dd %02d:%02d")
17426 (fy1 "%dy %dd")
17427 (fd "%dd %02d:%02d")
17428 (fd1 "%dd")
17429 (fh "%02d:%02d")
17430 y d h m align)
17431 (if havetime
17432 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17434 d (floor (/ diff ds)) diff (mod diff ds)
17435 h (floor (/ diff hs)) diff (mod diff hs)
17436 m (floor (/ diff 60)))
17437 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17439 d (floor (+ (/ diff ds) 0.5))
17440 h 0 m 0))
17441 (if (not to-buffer)
17442 (message "%s" (org-make-tdiff-string y d h m))
17443 (if (org-at-table-p)
17444 (progn
17445 (goto-char match-end)
17446 (setq align t)
17447 (and (looking-at " *|") (goto-char (match-end 0))))
17448 (goto-char match-end))
17449 (when (looking-at
17450 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17451 (replace-match ""))
17452 (when negative (insert " -"))
17453 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17454 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17455 (insert " " (format fh h m))))
17456 (when align (org-table-align))
17457 (message "Time difference inserted")))))
17459 (defun org-make-tdiff-string (y d h m)
17460 (let ((fmt "")
17461 (l nil))
17462 (when (> y 0)
17463 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17464 (push y l))
17465 (when (> d 0)
17466 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17467 (push d l))
17468 (when (> h 0)
17469 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17470 (push h l))
17471 (when (> m 0)
17472 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17473 (push m l))
17474 (apply 'format fmt (nreverse l))))
17476 (defun org-time-string-to-time (s &optional zone)
17477 "Convert timestamp string S into internal time.
17478 The optional ZONE is omitted or nil for Emacs local time, t for
17479 Universal Time, ‘wall’ for system wall clock time, or a string as
17480 in the TZ environment variable."
17481 (apply #'encode-time (org-parse-time-string s nil zone)))
17483 (defun org-time-string-to-seconds (s &optional zone)
17484 "Convert a timestamp string S into a number of seconds.
17485 The optional ZONE is omitted or nil for Emacs local time, t for
17486 Universal Time, ‘wall’ for system wall clock time, or a string as
17487 in the TZ environment variable."
17488 (float-time (org-time-string-to-time s zone)))
17490 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17492 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17493 "Convert time stamp S to an absolute day number.
17495 If DAYNR in non-nil, and there is a specifier for a cyclic time
17496 stamp, get the closest date to DAYNR. If PREFER is
17497 `past' (respectively `future') return a date past (respectively
17498 after) or equal to DAYNR.
17500 POS is the location of time stamp S, as a buffer position in
17501 BUFFER.
17503 Diary sexp timestamps are matched against DAYNR, when non-nil.
17504 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17505 signaled."
17506 (cond
17507 ((string-match "\\`%%\\((.*)\\)" s)
17508 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17509 ;; only able to match individual dates. If it fails, raise an
17510 ;; error.
17511 (if (and daynr
17512 (org-diary-sexp-entry
17513 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17514 daynr
17515 (signal 'org-diary-sexp-no-match (list s))))
17516 (daynr (org-closest-date s daynr prefer))
17517 (t (time-to-days
17518 (condition-case errdata
17519 (apply #'encode-time (org-parse-time-string s))
17520 (error (error "Bad timestamp `%s'%s\nError was: %s"
17522 (if (not (and buffer pos)) ""
17523 (format-message " at %d in buffer `%s'" pos buffer))
17524 (cdr errdata))))))))
17526 (defun org-days-to-iso-week (days)
17527 "Return the iso week number."
17528 (require 'cal-iso)
17529 (car (calendar-iso-from-absolute days)))
17531 (defun org-small-year-to-year (year)
17532 "Convert 2-digit years into 4-digit years.
17533 YEAR is expanded into one of the 30 next years, if possible, or
17534 into a past one. Any year larger than 99 is returned unchanged."
17535 (if (>= year 100) year
17536 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17537 (century (/ current 100))
17538 (offset (- year (% current 100))))
17539 (cond ((> offset 30) (+ (* (1- century) 100) year))
17540 ((> offset -70) (+ (* century 100) year))
17541 (t (+ (* (1+ century) 100) year))))))
17543 (defun org-time-from-absolute (d)
17544 "Return the time corresponding to date D.
17545 D may be an absolute day number, or a calendar-type list (month day year)."
17546 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17547 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17549 (defvar org-agenda-current-date)
17550 (defun org-calendar-holiday ()
17551 "List of holidays, for Diary display in Org mode."
17552 (require 'holidays)
17553 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17554 (and hl (mapconcat #'identity hl "; "))))
17556 (defun org-diary-sexp-entry (sexp entry d)
17557 "Process a SEXP diary ENTRY for date D."
17558 (require 'diary-lib)
17559 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17560 ;; dynamically.
17561 (let* ((sexp `(let ((entry ,entry)
17562 (date ',d))
17563 ,(car (read-from-string sexp))))
17564 (result (if calendar-debug-sexp (eval sexp)
17565 (condition-case nil
17566 (eval sexp)
17567 (error
17568 (beep)
17569 (message "Bad sexp at line %d in %s: %s"
17570 (org-current-line)
17571 (buffer-file-name) sexp)
17572 (sleep-for 2))))))
17573 (cond ((stringp result) (split-string result "; "))
17574 ((and (consp result)
17575 (not (consp (cdr result)))
17576 (stringp (cdr result))) (cdr result))
17577 ((and (consp result)
17578 (stringp (car result))) result)
17579 (result entry))))
17581 (defun org-diary-to-ical-string (frombuf)
17582 "Get iCalendar entries from diary entries in buffer FROMBUF.
17583 This uses the icalendar.el library."
17584 (let* ((tmpdir temporary-file-directory)
17585 (tmpfile (make-temp-name
17586 (expand-file-name "orgics" tmpdir)))
17587 buf rtn b e)
17588 (with-current-buffer frombuf
17589 (icalendar-export-region (point-min) (point-max) tmpfile)
17590 (setq buf (find-buffer-visiting tmpfile))
17591 (set-buffer buf)
17592 (goto-char (point-min))
17593 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17594 (setq b (match-beginning 0)))
17595 (goto-char (point-max))
17596 (when (re-search-backward "^END:VEVENT" nil t)
17597 (setq e (match-end 0)))
17598 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17599 (kill-buffer buf)
17600 (delete-file tmpfile)
17601 rtn))
17603 (defun org-closest-date (start current prefer)
17604 "Return closest date to CURRENT starting from START.
17606 CURRENT and START are both time stamps.
17608 When PREFER is `past', return a date that is either CURRENT or
17609 past. When PREFER is `future', return a date that is either
17610 CURRENT or future.
17612 Only time stamps with a repeater are modified. Any other time
17613 stamp stay unchanged. In any case, return value is an absolute
17614 day number."
17615 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17616 ;; No repeater. Do not shift time stamp.
17617 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17618 (let ((value (string-to-number (match-string 1 start)))
17619 (type (match-string 2 start)))
17620 (if (= 0 value)
17621 ;; Repeater with a 0-value is considered as void.
17622 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17623 (let* ((base (org-date-to-gregorian start))
17624 (target (org-date-to-gregorian current))
17625 (sday (calendar-absolute-from-gregorian base))
17626 (cday (calendar-absolute-from-gregorian target))
17627 n1 n2)
17628 ;; If START is already past CURRENT, just return START.
17629 (if (<= cday sday) sday
17630 ;; Compute closest date before (N1) and closest date past
17631 ;; (N2) CURRENT.
17632 (pcase type
17633 ("h"
17634 (let ((missing-hours
17635 (mod (+ (- (* 24 (- cday sday))
17636 (nth 2 (org-parse-time-string start)))
17637 org-extend-today-until)
17638 value)))
17639 (setf n1 (if (= missing-hours 0) cday
17640 (- cday (1+ (/ missing-hours 24)))))
17641 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17642 ((or "d" "w")
17643 (let ((value (if (equal type "w") (* 7 value) value)))
17644 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17645 (setf n2 (+ n1 value))))
17646 ("m"
17647 (let* ((add-months
17648 (lambda (d n)
17649 ;; Add N months to gregorian date D, i.e.,
17650 ;; a list (MONTH DAY YEAR). Return a valid
17651 ;; gregorian date.
17652 (let ((m (+ (nth 0 d) n)))
17653 (list (mod m 12)
17654 (nth 1 d)
17655 (+ (/ m 12) (nth 2 d))))))
17656 (months ; Complete months to TARGET.
17657 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17658 (- (nth 0 target) (nth 0 base))
17659 ;; If START's day is greater than
17660 ;; TARGET's, remove incomplete month.
17661 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17662 value)
17663 value))
17664 (before (funcall add-months base months)))
17665 (setf n1 (calendar-absolute-from-gregorian before))
17666 (setf n2
17667 (calendar-absolute-from-gregorian
17668 (funcall add-months before value)))))
17670 (let* ((d (nth 1 base))
17671 (m (nth 0 base))
17672 (y (nth 2 base))
17673 (years ; Complete years to TARGET.
17674 (* (/ (- (nth 2 target)
17676 ;; If START's month and day are
17677 ;; greater than TARGET's, remove
17678 ;; incomplete year.
17679 (if (or (> (nth 0 target) m)
17680 (and (= (nth 0 target) m)
17681 (> (nth 1 target) d)))
17684 value)
17685 value))
17686 (before (list m d (+ y years))))
17687 (setf n1 (calendar-absolute-from-gregorian before))
17688 (setf n2 (calendar-absolute-from-gregorian
17689 (list m d (+ (nth 2 before) value)))))))
17690 ;; Handle PREFER parameter, if any.
17691 (cond
17692 ((eq prefer 'past) (if (= cday n2) n2 n1))
17693 ((eq prefer 'future) (if (= cday n1) n1 n2))
17694 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17696 (defun org-date-to-gregorian (d)
17697 "Turn any specification of date D into a Gregorian date for the calendar."
17698 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17699 ((and (listp d) (= (length d) 3)) d)
17700 ((stringp d)
17701 (let ((d (org-parse-time-string d)))
17702 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17703 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17705 (defun org-parse-time-string (s &optional nodefault zone)
17706 "Parse the standard Org time string.
17708 This should be a lot faster than the normal `parse-time-string'.
17710 If time is not given, defaults to 0:00. However, with optional
17711 NODEFAULT, hour and minute fields will be nil if not given.
17713 The optional ZONE is omitted or nil for Emacs local time, t for
17714 Universal Time, ‘wall’ for system wall clock time, or a string as
17715 in the TZ environment variable."
17716 (cond ((string-match org-ts-regexp0 s)
17717 (list 0
17718 (when (or (match-beginning 8) (not nodefault))
17719 (string-to-number (or (match-string 8 s) "0")))
17720 (when (or (match-beginning 7) (not nodefault))
17721 (string-to-number (or (match-string 7 s) "0")))
17722 (string-to-number (match-string 4 s))
17723 (string-to-number (match-string 3 s))
17724 (string-to-number (match-string 2 s))
17725 nil nil zone))
17726 ((string-match "^<[^>]+>$" s)
17727 ;; FIXME: `decode-time' needs to be called with ZONE as its
17728 ;; second argument. However, this requires at least Emacs
17729 ;; 25.1. We can do it when we switch to this version as our
17730 ;; minimal requirement.
17731 (decode-time (seconds-to-time (org-matcher-time s))))
17732 (t (error "Not a standard Org time string: %s" s))))
17734 (defun org-timestamp-up (&optional arg)
17735 "Increase the date item at the cursor by one.
17736 If the cursor is on the year, change the year. If it is on the month,
17737 the day or the time, change that.
17738 With prefix ARG, change by that many units."
17739 (interactive "p")
17740 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17742 (defun org-timestamp-down (&optional arg)
17743 "Decrease the date item at the cursor by one.
17744 If the cursor is on the year, change the year. If it is on the month,
17745 the day or the time, change that.
17746 With prefix ARG, change by that many units."
17747 (interactive "p")
17748 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17750 (defun org-timestamp-up-day (&optional arg)
17751 "Increase the date in the time stamp by one day.
17752 With prefix ARG, change that many days."
17753 (interactive "p")
17754 (if (and (not (org-at-timestamp-p 'lax))
17755 (org-at-heading-p))
17756 (org-todo 'up)
17757 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17759 (defun org-timestamp-down-day (&optional arg)
17760 "Decrease the date in the time stamp by one day.
17761 With prefix ARG, change that many days."
17762 (interactive "p")
17763 (if (and (not (org-at-timestamp-p 'lax))
17764 (org-at-heading-p))
17765 (org-todo 'down)
17766 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17768 (defun org-at-timestamp-p (&optional extended)
17769 "Non-nil if point is inside a timestamp.
17771 By default, the function only consider syntactically valid active
17772 timestamps. However, the caller may have a broader definition
17773 for timestamps. As a consequence, optional argument EXTENDED can
17774 be set to the following values
17776 `inactive'
17778 Include also syntactically valid inactive timestamps.
17780 `agenda'
17782 Include timestamps allowed in Agenda, i.e., those in
17783 properties drawers, planning lines and clock lines.
17785 `lax'
17787 Ignore context. The function matches any part of the
17788 document looking like a timestamp. This includes comments,
17789 example blocks...
17791 For backward-compatibility with Org 9.0, every other non-nil
17792 value is equivalent to `inactive'.
17794 When at a timestamp, return the position of the point as a symbol
17795 among `bracket', `after', `year', `month', `hour', `minute',
17796 `day' or a number of character from the last know part of the
17797 time stamp.
17799 When matching, the match groups are the following:
17800 group 1: year
17801 group 2: month
17802 group 3: day number
17803 group 4: day name
17804 group 5: hours, if any
17805 group 6: minutes, if any"
17806 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17807 (pos (point))
17808 (match?
17809 (let ((boundaries (org-in-regexp regexp)))
17810 (save-match-data
17811 (cond ((null boundaries) nil)
17812 ((eq extended 'lax) t)
17814 (or (and (eq extended 'agenda)
17815 (or (org-at-planning-p)
17816 (org-at-property-p)
17817 (and (bound-and-true-p
17818 org-agenda-include-inactive-timestamps)
17819 (org-at-clock-log-p))))
17820 (eq 'timestamp
17821 (save-excursion
17822 (when (= pos (cdr boundaries)) (forward-char -1))
17823 (org-element-type (org-element-context)))))))))))
17824 (cond
17825 ((not match?) nil)
17826 ((= pos (match-beginning 0)) 'bracket)
17827 ;; Distinguish location right before the closing bracket from
17828 ;; right after it.
17829 ((= pos (1- (match-end 0))) 'bracket)
17830 ((= pos (match-end 0)) 'after)
17831 ((org-pos-in-match-range pos 2) 'year)
17832 ((org-pos-in-match-range pos 3) 'month)
17833 ((org-pos-in-match-range pos 7) 'hour)
17834 ((org-pos-in-match-range pos 8) 'minute)
17835 ((or (org-pos-in-match-range pos 4)
17836 (org-pos-in-match-range pos 5)) 'day)
17837 ((and (> pos (or (match-end 8) (match-end 5)))
17838 (< pos (match-end 0)))
17839 (- pos (or (match-end 8) (match-end 5))))
17840 (t 'day))))
17842 (defun org-toggle-timestamp-type ()
17843 "Toggle the type (<active> or [inactive]) of a time stamp."
17844 (interactive)
17845 (when (org-at-timestamp-p 'lax)
17846 (let ((beg (match-beginning 0)) (end (match-end 0))
17847 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17848 (save-excursion
17849 (goto-char beg)
17850 (while (re-search-forward "[][<>]" end t)
17851 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17852 t t)))
17853 (message "Timestamp is now %sactive"
17854 (if (equal (char-after beg) ?<) "" "in")))))
17856 (defun org-at-clock-log-p ()
17857 "Non-nil if point is on a clock log line."
17858 (and (org-match-line org-clock-line-re)
17859 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17861 (defvar org-clock-history) ; defined in org-clock.el
17862 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17863 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17864 "Change the date in the time stamp at point.
17865 The date will be changed by N times WHAT. WHAT can be `day', `month',
17866 `year', `minute', `second'. If WHAT is not given, the cursor position
17867 in the timestamp determines what will be changed.
17868 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17869 (let ((origin (point))
17870 (timestamp? (org-at-timestamp-p 'lax))
17871 origin-cat
17872 with-hm inactive
17873 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17874 extra rem
17875 ts time time0 fixnext clrgx)
17876 (unless timestamp? (user-error "Not at a timestamp"))
17877 (if (and (not what) (eq timestamp? 'bracket))
17878 (org-toggle-timestamp-type)
17879 ;; Point isn't on brackets. Remember the part of the time-stamp
17880 ;; the point was in. Indeed, size of time-stamps may change,
17881 ;; but point must be kept in the same category nonetheless.
17882 (setq origin-cat timestamp?)
17883 (when (and (not what) (not (eq timestamp? 'day))
17884 org-display-custom-times
17885 (get-text-property (point) 'display)
17886 (not (get-text-property (1- (point)) 'display)))
17887 (setq timestamp? 'day))
17888 (setq timestamp? (or what timestamp?)
17889 inactive (= (char-after (match-beginning 0)) ?\[)
17890 ts (match-string 0))
17891 (replace-match "")
17892 (when (string-match
17893 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17895 (setq extra (match-string 1 ts))
17896 (when suppress-tmp-delay
17897 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17898 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17899 (setq with-hm t))
17900 (setq time0 (org-parse-time-string ts))
17901 (when (and updown
17902 (eq timestamp? 'minute)
17903 (not current-prefix-arg))
17904 ;; This looks like s-up and s-down. Change by one rounding step.
17905 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17906 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17907 (setcar (cdr time0) (+ (nth 1 time0)
17908 (if (> n 0) (- rem) (- dm rem))))))
17909 (setq time
17910 (apply #'encode-time
17911 (or (car time0) 0)
17912 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17913 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17914 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17915 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17916 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17917 (nthcdr 6 time0)))
17918 (when (and (memq timestamp? '(hour minute))
17919 extra
17920 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17921 (setq extra (org-modify-ts-extra
17922 extra
17923 (if (eq timestamp? 'hour) 2 5)
17924 n dm)))
17925 (when (integerp timestamp?)
17926 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17927 (when (eq what 'calendar)
17928 (let ((cal-date (org-get-date-from-calendar)))
17929 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17930 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17931 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17932 (setcar time0 (or (car time0) 0))
17933 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17934 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17935 (setq time (apply 'encode-time time0))))
17936 ;; Insert the new time-stamp, and ensure point stays in the same
17937 ;; category as before (i.e. not after the last position in that
17938 ;; category).
17939 (let ((pos (point)))
17940 ;; Stay before inserted string. `save-excursion' is of no use.
17941 (setq org-last-changed-timestamp
17942 (org-insert-time-stamp time with-hm inactive nil nil extra))
17943 (goto-char pos))
17944 (save-match-data
17945 (looking-at org-ts-regexp3)
17946 (goto-char
17947 (pcase origin-cat
17948 ;; `day' category ends before `hour' if any, or at the end
17949 ;; of the day name.
17950 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17951 (`hour (min (match-end 7) origin))
17952 (`minute (min (1- (match-end 8)) origin))
17953 ((pred integerp) (min (1- (match-end 0)) origin))
17954 ;; Point was right after the time-stamp. However, the
17955 ;; time-stamp length might have changed, so refer to
17956 ;; (match-end 0) instead.
17957 (`after (match-end 0))
17958 ;; `year' and `month' have both fixed size: point couldn't
17959 ;; have moved into another part.
17960 (_ origin))))
17961 ;; Update clock if on a CLOCK line.
17962 (org-clock-update-time-maybe)
17963 ;; Maybe adjust the closest clock in `org-clock-history'
17964 (when org-clock-adjust-closest
17965 (if (not (and (org-at-clock-log-p)
17966 (< 1 (length (delq nil (mapcar 'marker-position
17967 org-clock-history))))))
17968 (message "No clock to adjust")
17969 (cond ((save-excursion ; fix previous clock?
17970 (re-search-backward org-ts-regexp0 nil t)
17971 (looking-back (concat org-clock-string " \\[")
17972 (line-beginning-position)))
17973 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17974 ((save-excursion ; fix next clock?
17975 (re-search-backward org-ts-regexp0 nil t)
17976 (looking-at (concat org-ts-regexp0 "\\] =>")))
17977 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17978 (save-window-excursion
17979 ;; Find closest clock to point, adjust the previous/next one in history
17980 (let* ((p (save-excursion (org-back-to-heading t)))
17981 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17982 (clfixnth
17983 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17984 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17985 (if (not clfixpos)
17986 (message "No clock to adjust")
17987 (save-excursion
17988 (org-goto-marker-or-bmk clfixpos)
17989 (org-show-subtree)
17990 (when (re-search-forward clrgx nil t)
17991 (goto-char (match-beginning 1))
17992 (let (org-clock-adjust-closest)
17993 (org-timestamp-change n timestamp? updown))
17994 (message "Clock adjusted in %s for heading: %s"
17995 (file-name-nondirectory (buffer-file-name))
17996 (org-get-heading t t)))))))))
17997 ;; Try to recenter the calendar window, if any.
17998 (when (and org-calendar-follow-timestamp-change
17999 (get-buffer-window "*Calendar*" t)
18000 (memq timestamp? '(day month year)))
18001 (org-recenter-calendar (time-to-days time))))))
18003 (defun org-modify-ts-extra (s pos n dm)
18004 "Change the different parts of the lead-time and repeat fields in timestamp."
18005 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18006 ng h m new rem)
18007 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18008 (cond
18009 ((or (org-pos-in-match-range pos 2)
18010 (org-pos-in-match-range pos 3))
18011 (setq m (string-to-number (match-string 3 s))
18012 h (string-to-number (match-string 2 s)))
18013 (if (org-pos-in-match-range pos 2)
18014 (setq h (+ h n))
18015 (setq n (* dm (with-no-warnings (signum n))))
18016 (unless (= 0 (setq rem (% m dm)))
18017 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18018 (setq m (+ m n)))
18019 (when (< m 0) (setq m (+ m 60) h (1- h)))
18020 (when (> m 59) (setq m (- m 60) h (1+ h)))
18021 (setq h (mod h 24))
18022 (setq ng 1 new (format "-%02d:%02d" h m)))
18023 ((org-pos-in-match-range pos 6)
18024 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18025 ((org-pos-in-match-range pos 5)
18026 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18028 ((org-pos-in-match-range pos 9)
18029 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18030 ((org-pos-in-match-range pos 8)
18031 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18033 (when ng
18034 (setq s (concat
18035 (substring s 0 (match-beginning ng))
18037 (substring s (match-end ng))))))
18040 (defun org-recenter-calendar (d)
18041 "If the calendar is visible, recenter it to date D."
18042 (let ((cwin (get-buffer-window "*Calendar*" t)))
18043 (when cwin
18044 (let ((calendar-move-hook nil))
18045 (with-selected-window cwin
18046 (calendar-goto-date
18047 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18049 (defun org-goto-calendar (&optional arg)
18050 "Go to the Emacs calendar at the current date.
18051 If there is a time stamp in the current line, go to that date.
18052 A prefix ARG can be used to force the current date."
18053 (interactive "P")
18054 (let ((calendar-move-hook nil)
18055 (calendar-view-holidays-initially-flag nil)
18056 (calendar-view-diary-initially-flag nil)
18057 diff)
18058 (when (or (org-at-timestamp-p 'lax)
18059 (org-match-line (concat ".*" org-ts-regexp)))
18060 (let ((d1 (time-to-days (current-time)))
18061 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18062 (setq diff (- d2 d1))))
18063 (calendar)
18064 (calendar-goto-today)
18065 (when (and diff (not arg)) (calendar-forward-day diff))))
18067 (defun org-get-date-from-calendar ()
18068 "Return a list (month day year) of date at point in calendar."
18069 (with-current-buffer "*Calendar*"
18070 (save-match-data
18071 (calendar-cursor-to-date))))
18073 (defun org-date-from-calendar ()
18074 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18075 If there is already a time stamp at the cursor position, update it."
18076 (interactive)
18077 (if (org-at-timestamp-p 'lax)
18078 (org-timestamp-change 0 'calendar)
18079 (let ((cal-date (org-get-date-from-calendar)))
18080 (org-insert-time-stamp
18081 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18083 (defcustom org-effort-durations
18084 `(("min" . 1)
18085 ("h" . 60)
18086 ("d" . ,(* 60 8))
18087 ("w" . ,(* 60 8 5))
18088 ("m" . ,(* 60 8 5 4))
18089 ("y" . ,(* 60 8 5 40)))
18090 "Conversion factor to minutes for an effort modifier.
18092 Each entry has the form (MODIFIER . MINUTES).
18094 In an effort string, a number followed by MODIFIER is multiplied
18095 by the specified number of MINUTES to obtain an effort in
18096 minutes.
18098 For example, if the value of this variable is ((\"hours\" . 60)), then an
18099 effort string \"2hours\" is equivalent to 120 minutes."
18100 :group 'org-agenda
18101 :version "26.1"
18102 :package-version '(Org . "8.3")
18103 :type '(alist :key-type (string :tag "Modifier")
18104 :value-type (number :tag "Minutes")))
18106 (defcustom org-image-actual-width t
18107 "Should we use the actual width of images when inlining them?
18109 When set to t, always use the image width.
18111 When set to a number, use imagemagick (when available) to set
18112 the image's width to this value.
18114 When set to a number in a list, try to get the width from any
18115 #+ATTR.* keyword if it matches a width specification like
18117 #+ATTR_HTML: :width 300px
18119 and fall back on that number if none is found.
18121 When set to nil, try to get the width from an #+ATTR.* keyword
18122 and fall back on the original width if none is found.
18124 This requires Emacs >= 24.1, build with imagemagick support."
18125 :group 'org-appearance
18126 :version "24.4"
18127 :package-version '(Org . "8.0")
18128 :type '(choice
18129 (const :tag "Use the image width" t)
18130 (integer :tag "Use a number of pixels")
18131 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18132 (const :tag "Use #+ATTR* or don't resize" nil)))
18134 (defcustom org-agenda-inhibit-startup nil
18135 "Inhibit startup when preparing agenda buffers.
18136 When this variable is t, the initialization of the Org agenda
18137 buffers is inhibited: e.g. the visibility state is not set, the
18138 tables are not re-aligned, etc."
18139 :type 'boolean
18140 :version "24.3"
18141 :group 'org-agenda)
18143 (defcustom org-agenda-ignore-properties nil
18144 "Avoid updating text properties when building the agenda.
18145 Properties are used to prepare buffers for effort estimates,
18146 appointments, statistics and subtree-local categories.
18147 If you don't use these in the agenda, you can add them to this
18148 list and agenda building will be a bit faster.
18149 The value is a list, with zero or more of the symbols `effort', `appt',
18150 `stats' or `category'."
18151 :type '(set :greedy t
18152 (const effort)
18153 (const appt)
18154 (const stats)
18155 (const category))
18156 :version "26.1"
18157 :package-version '(Org . "8.3")
18158 :group 'org-agenda)
18160 ;;;; Files
18162 (defun org-save-all-org-buffers ()
18163 "Save all Org buffers without user confirmation."
18164 (interactive)
18165 (message "Saving all Org buffers...")
18166 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18167 (when (featurep 'org-id) (org-id-locations-save))
18168 (message "Saving all Org buffers... done"))
18170 (defun org-revert-all-org-buffers ()
18171 "Revert all Org buffers.
18172 Prompt for confirmation when there are unsaved changes.
18173 Be sure you know what you are doing before letting this function
18174 overwrite your changes.
18176 This function is useful in a setup where one tracks org files
18177 with a version control system, to revert on one machine after pulling
18178 changes from another. I believe the procedure must be like this:
18180 1. M-x org-save-all-org-buffers
18181 2. Pull changes from the other machine, resolve conflicts
18182 3. M-x org-revert-all-org-buffers"
18183 (interactive)
18184 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18185 (user-error "Abort"))
18186 (save-excursion
18187 (save-window-excursion
18188 (dolist (b (buffer-list))
18189 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18190 (with-current-buffer b buffer-file-name))
18191 (pop-to-buffer-same-window b)
18192 (revert-buffer t 'no-confirm)))
18193 (when (and (featurep 'org-id) org-id-track-globally)
18194 (org-id-locations-load)))))
18196 ;;;; Agenda files
18198 ;;;###autoload
18199 (defun org-switchb (&optional arg)
18200 "Switch between Org buffers.
18202 With `\\[universal-argument]' prefix, restrict available buffers to files.
18204 With `\\[universal-argument] \\[universal-argument]' \
18205 prefix, restrict available buffers to agenda files."
18206 (interactive "P")
18207 (let ((blist (org-buffer-list
18208 (cond ((equal arg '(4)) 'files)
18209 ((equal arg '(16)) 'agenda)))))
18210 (pop-to-buffer-same-window
18211 (completing-read "Org buffer: "
18212 (mapcar #'list (mapcar #'buffer-name blist))
18213 nil t))))
18215 (defun org-buffer-list (&optional predicate exclude-tmp)
18216 "Return a list of Org buffers.
18217 PREDICATE can be `export', `files' or `agenda'.
18219 export restrict the list to Export buffers.
18220 files restrict the list to buffers visiting Org files.
18221 agenda restrict the list to buffers visiting agenda files.
18223 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18224 (let* ((bfn nil)
18225 (agenda-files (and (eq predicate 'agenda)
18226 (mapcar 'file-truename (org-agenda-files t))))
18227 (filter
18228 (cond
18229 ((eq predicate 'files)
18230 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18231 ((eq predicate 'export)
18232 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18233 ((eq predicate 'agenda)
18234 (lambda (b)
18235 (with-current-buffer b
18236 (and (derived-mode-p 'org-mode)
18237 (setq bfn (buffer-file-name b))
18238 (member (file-truename bfn) agenda-files)))))
18239 (t (lambda (b) (with-current-buffer b
18240 (or (derived-mode-p 'org-mode)
18241 (string-match "\\*Org .*Export"
18242 (buffer-name b)))))))))
18243 (delq nil
18244 (mapcar
18245 (lambda(b)
18246 (if (and (funcall filter b)
18247 (or (not exclude-tmp)
18248 (not (string-match "tmp" (buffer-name b)))))
18250 nil))
18251 (buffer-list)))))
18253 (defun org-agenda-files (&optional unrestricted archives)
18254 "Get the list of agenda files.
18255 Optional UNRESTRICTED means return the full list even if a restriction
18256 is currently in place.
18257 When ARCHIVES is t, include all archive files that are really being
18258 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18259 `org-agenda-archives-mode' is t."
18260 (let ((files
18261 (cond
18262 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18263 ((stringp org-agenda-files) (org-read-agenda-file-list))
18264 ((listp org-agenda-files) org-agenda-files)
18265 (t (error "Invalid value of `org-agenda-files'")))))
18266 (setq files (apply 'append
18267 (mapcar (lambda (f)
18268 (if (file-directory-p f)
18269 (directory-files
18270 f t org-agenda-file-regexp)
18271 (list f)))
18272 files)))
18273 (when org-agenda-skip-unavailable-files
18274 (setq files (delq nil
18275 (mapcar (function
18276 (lambda (file)
18277 (and (file-readable-p file) file)))
18278 files))))
18279 (when (or (eq archives t)
18280 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18281 (setq files (org-add-archive-files files)))
18282 files))
18284 (defun org-agenda-file-p (&optional file)
18285 "Return non-nil, if FILE is an agenda file.
18286 If FILE is omitted, use the file associated with the current
18287 buffer."
18288 (let ((fname (or file (buffer-file-name))))
18289 (and fname
18290 (member (file-truename fname)
18291 (mapcar #'file-truename (org-agenda-files t))))))
18293 (defun org-edit-agenda-file-list ()
18294 "Edit the list of agenda files.
18295 Depending on setup, this either uses customize to edit the variable
18296 `org-agenda-files', or it visits the file that is holding the list. In the
18297 latter case, the buffer is set up in a way that saving it automatically kills
18298 the buffer and restores the previous window configuration."
18299 (interactive)
18300 (if (stringp org-agenda-files)
18301 (let ((cw (current-window-configuration)))
18302 (find-file org-agenda-files)
18303 (setq-local org-window-configuration cw)
18304 (add-hook 'after-save-hook
18305 (lambda ()
18306 (set-window-configuration
18307 (prog1 org-window-configuration
18308 (kill-buffer (current-buffer))))
18309 (org-install-agenda-files-menu)
18310 (message "New agenda file list installed"))
18311 nil 'local)
18312 (message "%s" (substitute-command-keys
18313 "Edit list and finish with \\[save-buffer]")))
18314 (customize-variable 'org-agenda-files)))
18316 (defun org-store-new-agenda-file-list (list)
18317 "Set new value for the agenda file list and save it correctly."
18318 (if (stringp org-agenda-files)
18319 (let ((fe (org-read-agenda-file-list t)) b u)
18320 (while (setq b (find-buffer-visiting org-agenda-files))
18321 (kill-buffer b))
18322 (with-temp-file org-agenda-files
18323 (insert
18324 (mapconcat
18325 (lambda (f) ;; Keep un-expanded entries.
18326 (if (setq u (assoc f fe))
18327 (cdr u)
18329 list "\n")
18330 "\n")))
18331 (let ((org-mode-hook nil) (org-inhibit-startup t)
18332 (org-insert-mode-line-in-empty-file nil))
18333 (setq org-agenda-files list)
18334 (customize-save-variable 'org-agenda-files org-agenda-files))))
18336 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18337 "Read the list of agenda files from a file.
18338 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18339 filenames, used by `org-store-new-agenda-file-list' to write back
18340 un-expanded file names."
18341 (when (file-directory-p org-agenda-files)
18342 (error "`org-agenda-files' cannot be a single directory"))
18343 (when (stringp org-agenda-files)
18344 (with-temp-buffer
18345 (insert-file-contents org-agenda-files)
18346 (mapcar
18347 (lambda (f)
18348 (let ((e (expand-file-name (substitute-in-file-name f)
18349 org-directory)))
18350 (if pair-with-expansion
18351 (cons e f)
18352 e)))
18353 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18355 ;;;###autoload
18356 (defun org-cycle-agenda-files ()
18357 "Cycle through the files in `org-agenda-files'.
18358 If the current buffer visits an agenda file, find the next one in the list.
18359 If the current buffer does not, find the first agenda file."
18360 (interactive)
18361 (let* ((fs (or (org-agenda-files t)
18362 (user-error "No agenda files")))
18363 (files (copy-sequence fs))
18364 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18365 file)
18366 (when tcf
18367 (while (and (setq file (pop files))
18368 (not (equal (file-truename file) tcf)))))
18369 (find-file (car (or files fs)))
18370 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18372 (defun org-agenda-file-to-front (&optional to-end)
18373 "Move/add the current file to the top of the agenda file list.
18374 If the file is not present in the list, it is added to the front. If it is
18375 present, it is moved there. With optional argument TO-END, add/move to the
18376 end of the list."
18377 (interactive "P")
18378 (let ((org-agenda-skip-unavailable-files nil)
18379 (file-alist (mapcar (lambda (x)
18380 (cons (file-truename x) x))
18381 (org-agenda-files t)))
18382 (ctf (file-truename
18383 (or buffer-file-name
18384 (user-error "Please save the current buffer to a file"))))
18385 x had)
18386 (setq x (assoc ctf file-alist) had x)
18388 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18389 (if to-end
18390 (setq file-alist (append (delq x file-alist) (list x)))
18391 (setq file-alist (cons x (delq x file-alist))))
18392 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18393 (org-install-agenda-files-menu)
18394 (message "File %s to %s of agenda file list"
18395 (if had "moved" "added") (if to-end "end" "front"))))
18397 (defun org-remove-file (&optional file)
18398 "Remove current file from the list of files in variable `org-agenda-files'.
18399 These are the files which are being checked for agenda entries.
18400 Optional argument FILE means use this file instead of the current."
18401 (interactive)
18402 (let* ((org-agenda-skip-unavailable-files nil)
18403 (file (or file buffer-file-name
18404 (user-error "Current buffer does not visit a file")))
18405 (true-file (file-truename file))
18406 (afile (abbreviate-file-name file))
18407 (files (delq nil (mapcar
18408 (lambda (x)
18409 (unless (equal true-file
18410 (file-truename x))
18412 (org-agenda-files t)))))
18413 (if (not (= (length files) (length (org-agenda-files t))))
18414 (progn
18415 (org-store-new-agenda-file-list files)
18416 (org-install-agenda-files-menu)
18417 (message "Removed from Org Agenda list: %s" afile))
18418 (message "File was not in list: %s (not removed)" afile))))
18420 (defun org-file-menu-entry (file)
18421 (vector file (list 'find-file file) t))
18423 (defun org-check-agenda-file (file)
18424 "Make sure FILE exists. If not, ask user what to do."
18425 (unless (file-exists-p file)
18426 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18427 (abbreviate-file-name file))
18428 (let ((r (downcase (read-char-exclusive))))
18429 (cond
18430 ((equal r ?r)
18431 (org-remove-file file)
18432 (throw 'nextfile t))
18433 (t (user-error "Abort"))))))
18435 (defun org-get-agenda-file-buffer (file)
18436 "Get an agenda buffer visiting FILE.
18437 If the buffer needs to be created, add it to the list of buffers
18438 which might be released later."
18439 (let ((buf (org-find-base-buffer-visiting file)))
18440 (if buf
18441 buf ; just return it
18442 ;; Make a new buffer and remember it
18443 (setq buf (find-file-noselect file))
18444 (when buf (push buf org-agenda-new-buffers))
18445 buf)))
18447 (defun org-release-buffers (blist)
18448 "Release all buffers in list, asking the user for confirmation when needed.
18449 When a buffer is unmodified, it is just killed. When modified, it is saved
18450 \(if the user agrees) and then killed."
18451 (let (file)
18452 (dolist (buf blist)
18453 (setq file (buffer-file-name buf))
18454 (when (and (buffer-modified-p buf)
18455 file
18456 (y-or-n-p (format "Save file %s? " file)))
18457 (with-current-buffer buf (save-buffer)))
18458 (kill-buffer buf))))
18460 (defun org-agenda-prepare-buffers (files)
18461 "Create buffers for all agenda files, protect archived trees and comments."
18462 (interactive)
18463 (let ((pa '(:org-archived t))
18464 (pc '(:org-comment t))
18465 (pall '(:org-archived t :org-comment t))
18466 (inhibit-read-only t)
18467 (org-inhibit-startup org-agenda-inhibit-startup)
18468 (rea (concat ":" org-archive-tag ":"))
18469 re pos)
18470 (setq org-tag-alist-for-agenda nil
18471 org-tag-groups-alist-for-agenda nil)
18472 (save-excursion
18473 (save-restriction
18474 (dolist (file files)
18475 (catch 'nextfile
18476 (if (bufferp file)
18477 (set-buffer file)
18478 (org-check-agenda-file file)
18479 (set-buffer (org-get-agenda-file-buffer file)))
18480 (widen)
18481 (org-set-regexps-and-options 'tags-only)
18482 (setq pos (point))
18483 (or (memq 'category org-agenda-ignore-properties)
18484 (org-refresh-category-properties))
18485 (or (memq 'stats org-agenda-ignore-properties)
18486 (org-refresh-stats-properties))
18487 (or (memq 'effort org-agenda-ignore-properties)
18488 (org-refresh-effort-properties))
18489 (or (memq 'appt org-agenda-ignore-properties)
18490 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18491 (setq org-todo-keywords-for-agenda
18492 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18493 (setq org-done-keywords-for-agenda
18494 (append org-done-keywords-for-agenda org-done-keywords))
18495 (setq org-todo-keyword-alist-for-agenda
18496 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18497 (setq org-tag-alist-for-agenda
18498 (org-uniquify
18499 (append org-tag-alist-for-agenda
18500 org-current-tag-alist)))
18501 ;; Merge current file's tag groups into global
18502 ;; `org-tag-groups-alist-for-agenda'.
18503 (when org-group-tags
18504 (dolist (alist org-tag-groups-alist)
18505 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18506 (if old
18507 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18508 (push alist org-tag-groups-alist-for-agenda)))))
18509 (org-with-silent-modifications
18510 (save-excursion
18511 (remove-text-properties (point-min) (point-max) pall)
18512 (when org-agenda-skip-archived-trees
18513 (goto-char (point-min))
18514 (while (re-search-forward rea nil t)
18515 (when (org-at-heading-p t)
18516 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18517 (goto-char (point-min))
18518 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18519 (while (re-search-forward re nil t)
18520 (when (save-match-data (org-in-commented-heading-p t))
18521 (add-text-properties
18522 (match-beginning 0) (org-end-of-subtree t) pc)))))
18523 (goto-char pos)))))
18524 (setq org-todo-keywords-for-agenda
18525 (org-uniquify org-todo-keywords-for-agenda))
18526 (setq org-todo-keyword-alist-for-agenda
18527 (org-uniquify org-todo-keyword-alist-for-agenda))))
18530 ;;;; CDLaTeX minor mode
18532 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18533 "Keymap for the minor `org-cdlatex-mode'.")
18535 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18536 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18537 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18538 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18539 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18541 (defvar org-cdlatex-texmathp-advice-is-done nil
18542 "Flag remembering if we have applied the advice to texmathp already.")
18544 (define-minor-mode org-cdlatex-mode
18545 "Toggle the minor `org-cdlatex-mode'.
18546 This mode supports entering LaTeX environment and math in LaTeX fragments
18547 in Org mode.
18548 \\{org-cdlatex-mode-map}"
18549 nil " OCDL" nil
18550 (when org-cdlatex-mode
18551 (require 'cdlatex)
18552 (run-hooks 'cdlatex-mode-hook)
18553 (cdlatex-compute-tables))
18554 (unless org-cdlatex-texmathp-advice-is-done
18555 (setq org-cdlatex-texmathp-advice-is-done t)
18556 (defadvice texmathp (around org-math-always-on activate)
18557 "Always return t in Org buffers.
18558 This is because we want to insert math symbols without dollars even outside
18559 the LaTeX math segments. If Org mode thinks that point is actually inside
18560 an embedded LaTeX fragment, let `texmathp' do its job.
18561 `\\[org-cdlatex-mode-map]'"
18562 (interactive)
18563 (let (p)
18564 (cond
18565 ((not (derived-mode-p 'org-mode)) ad-do-it)
18566 ((eq this-command 'cdlatex-math-symbol)
18567 (setq ad-return-value t
18568 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18570 (let ((p (org-inside-LaTeX-fragment-p)))
18571 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18572 (setq ad-return-value t
18573 texmathp-why '("Org mode embedded math" . 0))
18574 (when p ad-do-it)))))))))
18576 (defun turn-on-org-cdlatex ()
18577 "Unconditionally turn on `org-cdlatex-mode'."
18578 (org-cdlatex-mode 1))
18580 (defun org-try-cdlatex-tab ()
18581 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18582 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18583 - inside a LaTeX fragment, or
18584 - after the first word in a line, where an abbreviation expansion could
18585 insert a LaTeX environment."
18586 (when org-cdlatex-mode
18587 (cond
18588 ;; Before any word on the line: No expansion possible.
18589 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18590 ;; Just after first word on the line: Expand it. Make sure it
18591 ;; cannot happen on headlines, though.
18592 ((save-excursion
18593 (skip-chars-backward "a-zA-Z0-9*")
18594 (skip-chars-backward " \t")
18595 (and (bolp) (not (org-at-heading-p))))
18596 (cdlatex-tab) t)
18597 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18599 (defun org-cdlatex-underscore-caret (&optional _arg)
18600 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18601 Revert to the normal definition outside of these fragments."
18602 (interactive "P")
18603 (if (org-inside-LaTeX-fragment-p)
18604 (call-interactively 'cdlatex-sub-superscript)
18605 (let (org-cdlatex-mode)
18606 (call-interactively (key-binding (vector last-input-event))))))
18608 (defun org-cdlatex-math-modify (&optional _arg)
18609 "Execute `cdlatex-math-modify' in LaTeX fragments.
18610 Revert to the normal definition outside of these fragments."
18611 (interactive "P")
18612 (if (org-inside-LaTeX-fragment-p)
18613 (call-interactively 'cdlatex-math-modify)
18614 (let (org-cdlatex-mode)
18615 (call-interactively (key-binding (vector last-input-event))))))
18617 (defun org-cdlatex-environment-indent (&optional environment item)
18618 "Execute `cdlatex-environment' and indent the inserted environment.
18620 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18622 The inserted environment is indented to current indentation
18623 unless point is at the beginning of the line, in which the
18624 environment remains unintended."
18625 (interactive)
18626 ;; cdlatex-environment always return nil. Therefore, capture output
18627 ;; first and determine if an environment was selected.
18628 (let* ((beg (point-marker))
18629 (end (copy-marker (point) t))
18630 (inserted (progn
18631 (ignore-errors (cdlatex-environment environment item))
18632 (< beg end)))
18633 ;; Figure out how many lines to move forward after the
18634 ;; environment has been inserted.
18635 (lines (when inserted
18636 (save-excursion
18637 (- (cl-loop while (< beg (point))
18638 with x = 0
18639 do (forward-line -1)
18640 (cl-incf x)
18641 finally return x)
18642 (if (progn (goto-char beg)
18643 (and (progn (skip-chars-forward " \t") (eolp))
18644 (progn (skip-chars-backward " \t") (bolp))))
18645 1 0)))))
18646 (env (org-trim (delete-and-extract-region beg end))))
18647 (when inserted
18648 ;; Get indentation of next line unless at column 0.
18649 (let ((ind (if (bolp) 0
18650 (save-excursion
18651 (org-return-indent)
18652 (prog1 (org-get-indentation)
18653 (when (progn (skip-chars-forward " \t") (eolp))
18654 (delete-region beg (point)))))))
18655 (bol (progn (skip-chars-backward " \t") (bolp))))
18656 ;; Insert a newline before environment unless at column zero
18657 ;; to "escape" the current line. Insert a newline if
18658 ;; something is one the same line as \end{ENVIRONMENT}.
18659 (insert
18660 (concat (unless bol "\n") env
18661 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18662 (unless (zerop ind)
18663 (save-excursion
18664 (goto-char beg)
18665 (while (< (point) end)
18666 (unless (eolp) (indent-line-to ind))
18667 (forward-line))))
18668 (goto-char beg)
18669 (forward-line lines)
18670 (indent-line-to ind)))
18671 (set-marker beg nil)
18672 (set-marker end nil)))
18675 ;;;; LaTeX fragments
18677 (defun org-inside-LaTeX-fragment-p ()
18678 "Test if point is inside a LaTeX fragment.
18679 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18680 sequence appearing also before point.
18681 Even though the matchers for math are configurable, this function assumes
18682 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18683 delimiters are skipped when they have been removed by customization.
18684 The return value is nil, or a cons cell with the delimiter and the
18685 position of this delimiter.
18687 This function does a reasonably good job, but can locally be fooled by
18688 for example currency specifications. For example it will assume being in
18689 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18690 fragments that are properly closed, but during editing, we have to live
18691 with the uncertainty caused by missing closing delimiters. This function
18692 looks only before point, not after."
18693 (catch 'exit
18694 (let ((pos (point))
18695 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18696 (lim (save-excursion (org-backward-paragraph) (point)))
18697 dd-on str (start 0) m re)
18698 (goto-char pos)
18699 (when dodollar
18700 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18701 re (nth 1 (assoc "$" org-latex-regexps)))
18702 (while (string-match re str start)
18703 (cond
18704 ((= (match-end 0) (length str))
18705 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18706 ((= (match-end 0) (- (length str) 5))
18707 (throw 'exit nil))
18708 (t (setq start (match-end 0))))))
18709 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18710 (goto-char pos)
18711 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18712 (and (match-beginning 2) (throw 'exit nil))
18713 ;; count $$
18714 (while (re-search-backward "\\$\\$" lim t)
18715 (setq dd-on (not dd-on)))
18716 (goto-char pos)
18717 (when dd-on (cons "$$" m))))))
18719 (defun org-inside-latex-macro-p ()
18720 "Is point inside a LaTeX macro or its arguments?"
18721 (save-match-data
18722 (org-in-regexp
18723 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18725 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18726 "Build an overlay between BEG and END using IMAGE file.
18727 Argument IMAGETYPE is the extension of the displayed image,
18728 as a string. It defaults to \"png\"."
18729 (let ((ov (make-overlay beg end))
18730 (imagetype (or (intern imagetype) 'png)))
18731 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18732 (overlay-put ov 'evaporate t)
18733 (overlay-put ov
18734 'modification-hooks
18735 (list (lambda (o _flag _beg _end &optional _l)
18736 (delete-overlay o))))
18737 (overlay-put ov
18738 'display
18739 (list 'image :type imagetype :file image :ascent 'center))))
18741 (defun org--list-latex-overlays (&optional beg end)
18742 "List all Org LaTeX overlays in current buffer.
18743 Limit to overlays between BEG and END when those are provided."
18744 (cl-remove-if-not
18745 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18746 (overlays-in (or beg (point-min)) (or end (point-max)))))
18748 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18749 "Remove all overlays with LaTeX fragment images in current buffer.
18750 When optional arguments BEG and END are non-nil, remove all
18751 overlays between them instead. Return a non-nil value when some
18752 overlays were removed, nil otherwise."
18753 (let ((overlays (org--list-latex-overlays beg end)))
18754 (mapc #'delete-overlay overlays)
18755 overlays))
18757 (defun org-toggle-latex-fragment (&optional arg)
18758 "Preview the LaTeX fragment at point, or all locally or globally.
18760 If the cursor is on a LaTeX fragment, create the image and overlay
18761 it over the source code, if there is none. Remove it otherwise.
18762 If there is no fragment at point, display all fragments in the
18763 current section.
18765 With prefix ARG, preview or clear image for all fragments in the
18766 current subtree or in the whole buffer when used before the first
18767 headline. With a prefix ARG `\\[universal-argument] \
18768 \\[universal-argument]' preview or clear images
18769 for all fragments in the buffer."
18770 (interactive "P")
18771 (when (display-graphic-p)
18772 (catch 'exit
18773 (save-excursion
18774 (let (beg end msg)
18775 (cond
18776 ((or (equal arg '(16))
18777 (and (equal arg '(4))
18778 (org-with-limited-levels (org-before-first-heading-p))))
18779 (if (org-remove-latex-fragment-image-overlays)
18780 (progn (message "LaTeX fragments images removed from buffer")
18781 (throw 'exit nil))
18782 (setq msg "Creating images for buffer...")))
18783 ((equal arg '(4))
18784 (org-with-limited-levels (org-back-to-heading t))
18785 (setq beg (point))
18786 (setq end (progn (org-end-of-subtree t) (point)))
18787 (if (org-remove-latex-fragment-image-overlays beg end)
18788 (progn
18789 (message "LaTeX fragment images removed from subtree")
18790 (throw 'exit nil))
18791 (setq msg "Creating images for subtree...")))
18792 ((let ((datum (org-element-context)))
18793 (when (memq (org-element-type datum)
18794 '(latex-environment latex-fragment))
18795 (setq beg (org-element-property :begin datum))
18796 (setq end (org-element-property :end datum))
18797 (if (org-remove-latex-fragment-image-overlays beg end)
18798 (progn (message "LaTeX fragment image removed")
18799 (throw 'exit nil))
18800 (setq msg "Creating image...")))))
18802 (org-with-limited-levels
18803 (setq beg (if (org-at-heading-p) (line-beginning-position)
18804 (outline-previous-heading)
18805 (point)))
18806 (setq end (progn (outline-next-heading) (point)))
18807 (if (org-remove-latex-fragment-image-overlays beg end)
18808 (progn
18809 (message "LaTeX fragment images removed from section")
18810 (throw 'exit nil))
18811 (setq msg "Creating images for section...")))))
18812 (let ((file (buffer-file-name (buffer-base-buffer))))
18813 (org-format-latex
18814 (concat org-preview-latex-image-directory "org-ltximg")
18815 beg end
18816 ;; Emacs cannot overlay images from remote hosts. Create
18817 ;; it in `temporary-file-directory' instead.
18818 (if (or (not file) (file-remote-p file))
18819 temporary-file-directory
18820 default-directory)
18821 'overlays msg 'forbuffer org-preview-latex-default-process))
18822 (message (concat msg "done")))))))
18824 (defun org-format-latex
18825 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18826 "Replace LaTeX fragments with links to an image.
18828 The function takes care of creating the replacement image.
18830 Only consider fragments between BEG and END when those are
18831 provided.
18833 When optional argument OVERLAYS is non-nil, display the image on
18834 top of the fragment instead of replacing it.
18836 PROCESSING-TYPE is the conversion method to use, as a symbol.
18838 Some of the options can be changed using the variable
18839 `org-format-latex-options', which see."
18840 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18841 (unless (eq processing-type 'verbatim)
18842 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18843 (cnt 0)
18844 checkdir-flag)
18845 (goto-char (or beg (point-min)))
18846 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18847 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18848 (overlay-recenter (or end (point-max))))
18849 (while (re-search-forward math-regexp end t)
18850 (unless (and overlays
18851 (eq (get-char-property (point) 'org-overlay-type)
18852 'org-latex-overlay))
18853 (let* ((context (org-element-context))
18854 (type (org-element-type context)))
18855 (when (memq type '(latex-environment latex-fragment))
18856 (let ((block-type (eq type 'latex-environment))
18857 (value (org-element-property :value context))
18858 (beg (org-element-property :begin context))
18859 (end (save-excursion
18860 (goto-char (org-element-property :end context))
18861 (skip-chars-backward " \r\t\n")
18862 (point))))
18863 (cond
18864 ((eq processing-type 'mathjax)
18865 ;; Prepare for MathJax processing.
18866 (if (not (string-match "\\`\\$\\$?" value))
18867 (goto-char end)
18868 (delete-region beg end)
18869 (if (string= (match-string 0 value) "$$")
18870 (insert "\\[" (substring value 2 -2) "\\]")
18871 (insert "\\(" (substring value 1 -1) "\\)"))))
18872 ((assq processing-type org-preview-latex-process-alist)
18873 ;; Process to an image.
18874 (cl-incf cnt)
18875 (goto-char beg)
18876 (let* ((processing-info
18877 (cdr (assq processing-type org-preview-latex-process-alist)))
18878 (face (face-at-point))
18879 ;; Get the colors from the face at point.
18881 (let ((color (plist-get org-format-latex-options
18882 :foreground)))
18883 (if (and forbuffer (eq color 'auto))
18884 (face-attribute face :foreground nil 'default)
18885 color)))
18887 (let ((color (plist-get org-format-latex-options
18888 :background)))
18889 (if (and forbuffer (eq color 'auto))
18890 (face-attribute face :background nil 'default)
18891 color)))
18892 (hash (sha1 (prin1-to-string
18893 (list org-format-latex-header
18894 org-latex-default-packages-alist
18895 org-latex-packages-alist
18896 org-format-latex-options
18897 forbuffer value fg bg))))
18898 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18899 (absprefix (expand-file-name prefix dir))
18900 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18901 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18902 (sep (and block-type "\n\n"))
18903 (link (concat sep "[[file:" linkfile "]]" sep))
18904 (options
18905 (org-combine-plists
18906 org-format-latex-options
18907 `(:foreground ,fg :background ,bg))))
18908 (when msg (message msg cnt))
18909 (unless checkdir-flag ; Ensure the directory exists.
18910 (setq checkdir-flag t)
18911 (let ((todir (file-name-directory absprefix)))
18912 (unless (file-directory-p todir)
18913 (make-directory todir t))))
18914 (unless (file-exists-p movefile)
18915 (org-create-formula-image
18916 value movefile options forbuffer processing-type))
18917 (if overlays
18918 (progn
18919 (dolist (o (overlays-in beg end))
18920 (when (eq (overlay-get o 'org-overlay-type)
18921 'org-latex-overlay)
18922 (delete-overlay o)))
18923 (org--format-latex-make-overlay beg end movefile imagetype)
18924 (goto-char end))
18925 (delete-region beg end)
18926 (insert
18927 (org-add-props link
18928 (list 'org-latex-src
18929 (replace-regexp-in-string "\"" "" value)
18930 'org-latex-src-embed-type
18931 (if block-type 'paragraph 'character)))))))
18932 ((eq processing-type 'mathml)
18933 ;; Process to MathML.
18934 (unless (org-format-latex-mathml-available-p)
18935 (user-error "LaTeX to MathML converter not configured"))
18936 (cl-incf cnt)
18937 (when msg (message msg cnt))
18938 (goto-char beg)
18939 (delete-region beg end)
18940 (insert (org-format-latex-as-mathml
18941 value block-type prefix dir)))
18943 (error "Unknown conversion process %s for LaTeX fragments"
18944 processing-type)))))))))))
18946 (defun org-create-math-formula (latex-frag &optional mathml-file)
18947 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18948 Use `org-latex-to-mathml-convert-command'. If the conversion is
18949 sucessful, return the portion between \"<math...> </math>\"
18950 elements otherwise return nil. When MATHML-FILE is specified,
18951 write the results in to that file. When invoked as an
18952 interactive command, prompt for LATEX-FRAG, with initial value
18953 set to the current active region and echo the results for user
18954 inspection."
18955 (interactive (list (let ((frag (when (org-region-active-p)
18956 (buffer-substring-no-properties
18957 (region-beginning) (region-end)))))
18958 (read-string "LaTeX Fragment: " frag nil frag))))
18959 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18960 (let* ((tmp-in-file
18961 (let ((file (file-relative-name
18962 (make-temp-name (expand-file-name "ltxmathml-in")))))
18963 (write-region latex-frag nil file)
18964 file))
18965 (tmp-out-file (file-relative-name
18966 (make-temp-name (expand-file-name "ltxmathml-out"))))
18967 (cmd (format-spec
18968 org-latex-to-mathml-convert-command
18969 `((?j . ,(and org-latex-to-mathml-jar-file
18970 (shell-quote-argument
18971 (expand-file-name
18972 org-latex-to-mathml-jar-file))))
18973 (?I . ,(shell-quote-argument tmp-in-file))
18974 (?i . ,latex-frag)
18975 (?o . ,(shell-quote-argument tmp-out-file)))))
18976 mathml shell-command-output)
18977 (when (called-interactively-p 'any)
18978 (unless (org-format-latex-mathml-available-p)
18979 (user-error "LaTeX to MathML converter not configured")))
18980 (message "Running %s" cmd)
18981 (setq shell-command-output (shell-command-to-string cmd))
18982 (setq mathml
18983 (when (file-readable-p tmp-out-file)
18984 (with-current-buffer (find-file-noselect tmp-out-file t)
18985 (goto-char (point-min))
18986 (when (re-search-forward
18987 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18988 (regexp-quote
18989 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18990 nil t)
18991 (prog1 (match-string 0) (kill-buffer))))))
18992 (cond
18993 (mathml
18994 (setq mathml
18995 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18996 (when mathml-file
18997 (write-region mathml nil mathml-file))
18998 (when (called-interactively-p 'any)
18999 (message mathml)))
19000 ((message "LaTeX to MathML conversion failed")
19001 (message shell-command-output)))
19002 (delete-file tmp-in-file)
19003 (when (file-exists-p tmp-out-file)
19004 (delete-file tmp-out-file))
19005 mathml))
19007 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19008 prefix &optional dir)
19009 "Use `org-create-math-formula' but check local cache first."
19010 (let* ((absprefix (expand-file-name prefix dir))
19011 (print-length nil) (print-level nil)
19012 (formula-id (concat
19013 "formula-"
19014 (sha1
19015 (prin1-to-string
19016 (list latex-frag
19017 org-latex-to-mathml-convert-command)))))
19018 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19019 (formula-cache-dir (file-name-directory formula-cache)))
19021 (unless (file-directory-p formula-cache-dir)
19022 (make-directory formula-cache-dir t))
19024 (unless (file-exists-p formula-cache)
19025 (org-create-math-formula latex-frag formula-cache))
19027 (if (file-exists-p formula-cache)
19028 ;; Successful conversion. Return the link to MathML file.
19029 (org-add-props
19030 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19031 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19032 'org-latex-src-embed-type (if latex-frag-type
19033 'paragraph 'character)))
19034 ;; Failed conversion. Return the LaTeX fragment verbatim
19035 latex-frag)))
19037 (defun org--get-display-dpi ()
19038 "Get the DPI of the display.
19039 The function assumes that the display has the same pixel width in
19040 the horizontal and vertical directions."
19041 (if (display-graphic-p)
19042 (round (/ (display-pixel-height)
19043 (/ (display-mm-height) 25.4)))
19044 (error "Attempt to calculate the dpi of a non-graphic display")))
19046 (defun org-create-formula-image
19047 (string tofile options buffer &optional processing-type)
19048 "Create an image from LaTeX source using external processes.
19050 The LaTeX STRING is saved to a temporary LaTeX file, then
19051 converted to an image file by process PROCESSING-TYPE defined in
19052 `org-preview-latex-process-alist'. A nil value defaults to
19053 `org-preview-latex-default-process'.
19055 The generated image file is eventually moved to TOFILE.
19057 The OPTIONS argument controls the size, foreground color and
19058 background color of the generated image.
19060 When BUFFER non-nil, this function is used for LaTeX previewing.
19061 Otherwise, it is used to deal with LaTeX snippets showed in
19062 a HTML file."
19063 (let* ((processing-type (or processing-type
19064 org-preview-latex-default-process))
19065 (processing-info
19066 (cdr (assq processing-type org-preview-latex-process-alist)))
19067 (programs (plist-get processing-info :programs))
19068 (error-message (or (plist-get processing-info :message) ""))
19069 (use-xcolor (plist-get processing-info :use-xcolor))
19070 (image-input-type (plist-get processing-info :image-input-type))
19071 (image-output-type (plist-get processing-info :image-output-type))
19072 (post-clean (or (plist-get processing-info :post-clean)
19073 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19074 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19075 (latex-header
19076 (or (plist-get processing-info :latex-header)
19077 (org-latex-make-preamble
19078 (org-export-get-environment (org-export-get-backend 'latex))
19079 org-format-latex-header
19080 'snippet)))
19081 (latex-compiler (plist-get processing-info :latex-compiler))
19082 (image-converter (plist-get processing-info :image-converter))
19083 (tmpdir temporary-file-directory)
19084 (texfilebase (make-temp-name
19085 (expand-file-name "orgtex" tmpdir)))
19086 (texfile (concat texfilebase ".tex"))
19087 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19088 '(1.0 . 1.0)))
19089 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19090 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19091 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19092 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19093 "Black"))
19094 (bg (or (plist-get options (if buffer :background :html-background))
19095 "Transparent"))
19096 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19097 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19098 (dolist (program programs)
19099 (org-check-external-command program error-message))
19100 (if use-xcolor
19101 (progn (if (eq fg 'default)
19102 (setq fg (org-latex-color :foreground))
19103 (setq fg (org-latex-color-format fg)))
19104 (if (eq bg 'default)
19105 (setq bg (org-latex-color :background))
19106 (setq bg (org-latex-color-format
19107 (if (string= bg "Transparent") "white" bg))))
19108 (with-temp-file texfile
19109 (insert latex-header)
19110 (insert "\n\\begin{document}\n"
19111 "\\definecolor{fg}{rgb}{" fg "}\n"
19112 "\\definecolor{bg}{rgb}{" bg "}\n"
19113 "\n\\pagecolor{bg}\n"
19114 "\n{\\color{fg}\n"
19115 string
19116 "\n}\n"
19117 "\n\\end{document}\n")))
19118 (if (eq fg 'default)
19119 (setq fg (org-dvipng-color :foreground))
19120 (unless (string= fg "Transparent")
19121 (setq fg (org-dvipng-color-format fg))))
19122 (if (eq bg 'default)
19123 (setq bg (org-dvipng-color :background))
19124 (unless (string= bg "Transparent")
19125 (setq bg (org-dvipng-color-format bg))))
19126 (with-temp-file texfile
19127 (insert latex-header)
19128 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19130 (let* ((err-msg (format "Please adjust `%s' part of \
19131 `org-preview-latex-process-alist'."
19132 processing-type))
19133 (image-input-file
19134 (org-compile-file
19135 texfile latex-compiler image-input-type err-msg log-buf))
19136 (image-output-file
19137 (org-compile-file
19138 image-input-file image-converter image-output-type err-msg log-buf
19139 `((?F . ,(shell-quote-argument fg))
19140 (?B . ,(shell-quote-argument bg))
19141 (?D . ,(shell-quote-argument (format "%s" dpi)))
19142 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19143 (copy-file image-output-file tofile 'replace)
19144 (dolist (e post-clean)
19145 (when (file-exists-p (concat texfilebase e))
19146 (delete-file (concat texfilebase e))))
19147 image-output-file)))
19149 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19150 "Fill a LaTeX header template TPL.
19151 In the template, the following place holders will be recognized:
19153 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19154 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19155 [PACKAGES] \\usepackage statements for PKG
19156 [NO-PACKAGES] do not include PKG
19157 [EXTRA] the string EXTRA
19158 [NO-EXTRA] do not include EXTRA
19160 For backward compatibility, if both the positive and the negative place
19161 holder is missing, the positive one (without the \"NO-\") will be
19162 assumed to be present at the end of the template.
19163 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19164 EXTRA is a string.
19165 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19166 (let (rpl (end ""))
19167 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19168 (setq rpl (if (or (match-end 1) (not def-pkg))
19169 "" (org-latex-packages-to-string def-pkg snippets-p t))
19170 tpl (replace-match rpl t t tpl))
19171 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19173 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19174 (setq rpl (if (or (match-end 1) (not pkg))
19175 "" (org-latex-packages-to-string pkg snippets-p t))
19176 tpl (replace-match rpl t t tpl))
19177 (when pkg (setq end
19178 (concat end "\n"
19179 (org-latex-packages-to-string pkg snippets-p)))))
19181 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19182 (setq rpl (if (or (match-end 1) (not extra))
19183 "" (concat extra "\n"))
19184 tpl (replace-match rpl t t tpl))
19185 (when (and extra (string-match "\\S-" extra))
19186 (setq end (concat end "\n" extra))))
19188 (if (string-match "\\S-" end)
19189 (concat tpl "\n" end)
19190 tpl)))
19192 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19193 "Turn an alist of packages into a string with the \\usepackage macros."
19194 (setq pkg (mapconcat (lambda(p)
19195 (cond
19196 ((stringp p) p)
19197 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19198 (format "%% Package %s omitted" (cadr p)))
19199 ((equal "" (car p))
19200 (format "\\usepackage{%s}" (cadr p)))
19202 (format "\\usepackage[%s]{%s}"
19203 (car p) (cadr p)))))
19205 "\n"))
19206 (if newline (concat pkg "\n") pkg))
19208 (defun org-dvipng-color (attr)
19209 "Return a RGB color specification for dvipng."
19210 (org-dvipng-color-format (face-attribute 'default attr nil)))
19212 (defun org-dvipng-color-format (color-name)
19213 "Convert COLOR-NAME to a RGB color value for dvipng."
19214 (apply #'format "rgb %s %s %s"
19215 (mapcar 'org-normalize-color
19216 (color-values color-name))))
19218 (defun org-latex-color (attr)
19219 "Return a RGB color for the LaTeX color package."
19220 (org-latex-color-format (face-attribute 'default attr nil)))
19222 (defun org-latex-color-format (color-name)
19223 "Convert COLOR-NAME to a RGB color value."
19224 (apply #'format "%s,%s,%s"
19225 (mapcar 'org-normalize-color
19226 (color-values color-name))))
19228 (defun org-normalize-color (value)
19229 "Return string to be used as color value for an RGB component."
19230 (format "%g" (/ value 65535.0)))
19234 ;; Image display
19236 (defvar-local org-inline-image-overlays nil)
19238 (defun org-toggle-inline-images (&optional include-linked)
19239 "Toggle the display of inline images.
19240 INCLUDE-LINKED is passed to `org-display-inline-images'."
19241 (interactive "P")
19242 (if org-inline-image-overlays
19243 (progn
19244 (org-remove-inline-images)
19245 (when (called-interactively-p 'interactive)
19246 (message "Inline image display turned off")))
19247 (org-display-inline-images include-linked)
19248 (when (called-interactively-p 'interactive)
19249 (message (if org-inline-image-overlays
19250 (format "%d images displayed inline"
19251 (length org-inline-image-overlays))
19252 "No images to display inline")))))
19254 (defun org-redisplay-inline-images ()
19255 "Refresh the display of inline images."
19256 (interactive)
19257 (if (not org-inline-image-overlays)
19258 (org-toggle-inline-images)
19259 (org-toggle-inline-images)
19260 (org-toggle-inline-images)))
19262 (defun org-display-inline-images (&optional include-linked refresh beg end)
19263 "Display inline images.
19265 An inline image is a link which follows either of these
19266 conventions:
19268 1. Its path is a file with an extension matching return value
19269 from `image-file-name-regexp' and it has no contents.
19271 2. Its description consists in a single link of the previous
19272 type.
19274 When optional argument INCLUDE-LINKED is non-nil, also links with
19275 a text description part will be inlined. This can be nice for
19276 a quick look at those images, but it does not reflect what
19277 exported files will look like.
19279 When optional argument REFRESH is non-nil, refresh existing
19280 images between BEG and END. This will create new image displays
19281 only if necessary. BEG and END default to the buffer
19282 boundaries."
19283 (interactive "P")
19284 (when (display-graphic-p)
19285 (unless refresh
19286 (org-remove-inline-images)
19287 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19288 (org-with-wide-buffer
19289 (goto-char (or beg (point-min)))
19290 (let* ((case-fold-search t)
19291 (file-extension-re (image-file-name-regexp))
19292 (link-abbrevs (mapcar #'car
19293 (append org-link-abbrev-alist-local
19294 org-link-abbrev-alist)))
19295 ;; Check absolute, relative file names and explicit
19296 ;; "file:" links. Also check link abbreviations since
19297 ;; some might expand to "file" links.
19298 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19299 (and link-abbrevs
19300 (format "\\|\\(?:%s:\\)"
19301 (regexp-opt link-abbrevs))))))
19302 (while (re-search-forward file-types-re end t)
19303 (let ((link (save-match-data (org-element-context))))
19304 ;; Check if we're at an inline image, i.e., an image file
19305 ;; link without a description (unless INCLUDE-LINKED is
19306 ;; non-nil).
19307 (when (and (equal "file" (org-element-property :type link))
19308 (or include-linked
19309 (null (org-element-contents link)))
19310 (string-match-p file-extension-re
19311 (org-element-property :path link)))
19312 (let ((file (expand-file-name
19313 (org-link-unescape
19314 (org-element-property :path link)))))
19315 (when (file-exists-p file)
19316 (let ((width
19317 ;; Apply `org-image-actual-width' specifications.
19318 (cond
19319 ((not (image-type-available-p 'imagemagick)) nil)
19320 ((eq org-image-actual-width t) nil)
19321 ((listp org-image-actual-width)
19323 ;; First try to find a width among
19324 ;; attributes associated to the paragraph
19325 ;; containing link.
19326 (let ((paragraph
19327 (let ((e link))
19328 (while (and (setq e (org-element-property
19329 :parent e))
19330 (not (eq (org-element-type e)
19331 'paragraph))))
19332 e)))
19333 (when paragraph
19334 (save-excursion
19335 (goto-char (org-element-property :begin paragraph))
19336 (when
19337 (re-search-forward
19338 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19339 (org-element-property
19340 :post-affiliated paragraph)
19342 (string-to-number (match-string 1))))))
19343 ;; Otherwise, fall-back to provided number.
19344 (car org-image-actual-width)))
19345 ((numberp org-image-actual-width)
19346 org-image-actual-width)))
19347 (old (get-char-property-and-overlay
19348 (org-element-property :begin link)
19349 'org-image-overlay)))
19350 (if (and (car-safe old) refresh)
19351 (image-refresh (overlay-get (cdr old) 'display))
19352 (let ((image (create-image file
19353 (and width 'imagemagick)
19355 :width width)))
19356 (when image
19357 (let ((ov (make-overlay
19358 (org-element-property :begin link)
19359 (progn
19360 (goto-char
19361 (org-element-property :end link))
19362 (skip-chars-backward " \t")
19363 (point)))))
19364 (overlay-put ov 'display image)
19365 (overlay-put ov 'face 'default)
19366 (overlay-put ov 'org-image-overlay t)
19367 (overlay-put
19368 ov 'modification-hooks
19369 (list 'org-display-inline-remove-overlay))
19370 (push ov org-inline-image-overlays)))))))))))))))
19372 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19373 "Remove inline-display overlay if a corresponding region is modified."
19374 (let ((inhibit-modification-hooks t))
19375 (when (and ov after)
19376 (delete ov org-inline-image-overlays)
19377 (delete-overlay ov))))
19379 (defun org-remove-inline-images ()
19380 "Remove inline display of images."
19381 (interactive)
19382 (mapc #'delete-overlay org-inline-image-overlays)
19383 (setq org-inline-image-overlays nil))
19385 ;;;; Key bindings
19387 (defun org-remap (map &rest commands)
19388 "In MAP, remap the functions given in COMMANDS.
19389 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19390 (let (new old)
19391 (while commands
19392 (setq old (pop commands) new (pop commands))
19393 (org-defkey map (vector 'remap old) new))))
19395 ;; Outline functions from `outline-mode-prefix-map'
19396 ;; that can be remapped in Org:
19397 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19398 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19399 (define-key org-mode-map [remap outline-forward-same-level]
19400 'org-forward-heading-same-level)
19401 (define-key org-mode-map [remap outline-backward-same-level]
19402 'org-backward-heading-same-level)
19403 (define-key org-mode-map [remap outline-show-branches]
19404 'org-kill-note-or-show-branches)
19405 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19406 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19407 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19408 (define-key org-mode-map [remap outline-next-visible-heading]
19409 'org-next-visible-heading)
19410 (define-key org-mode-map [remap outline-previous-visible-heading]
19411 'org-previous-visible-heading)
19412 (define-key org-mode-map [remap show-children] 'org-show-children)
19414 ;; Outline functions from `outline-mode-prefix-map' that can not
19415 ;; be remapped in Org:
19417 ;; - the column "key binding" shows whether the Outline function is still
19418 ;; available in Org mode on the same key that it has been bound to in
19419 ;; Outline mode:
19420 ;; - "overridden": key used for a different functionality in Org mode
19421 ;; - else: key still bound to the same Outline function in Org mode
19423 ;; | Outline function | key binding | Org replacement |
19424 ;; |------------------------------------+-------------+--------------------------|
19425 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19426 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19427 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19428 ;; | `show-entry' | overridden | no replacement |
19429 ;; | `show-branches' | `C-c C-k' | still same function |
19430 ;; | `show-subtree' | overridden | visibility cycling |
19431 ;; | `show-all' | overridden | no replacement |
19432 ;; | `hide-subtree' | overridden | visibility cycling |
19433 ;; | `hide-body' | overridden | no replacement |
19434 ;; | `hide-entry' | overridden | visibility cycling |
19435 ;; | `hide-leaves' | overridden | no replacement |
19436 ;; | `hide-sublevels' | overridden | no replacement |
19437 ;; | `hide-other' | overridden | no replacement |
19439 ;; Make `C-c C-x' a prefix key
19440 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19442 ;; TAB key with modifiers
19443 (org-defkey org-mode-map "\C-i" 'org-cycle)
19444 (org-defkey org-mode-map [(tab)] 'org-cycle)
19445 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19446 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19448 ;; The following line is necessary under Suse GNU/Linux
19449 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19450 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19451 (define-key org-mode-map [backtab] 'org-shifttab)
19453 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19454 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19455 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19457 ;; Cursor keys with modifiers
19458 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19459 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19460 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19461 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19463 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19464 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19465 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19466 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19467 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19468 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19470 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19471 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19472 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19473 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19475 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19476 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19477 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19478 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19480 ;; Babel keys
19481 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19482 (dolist (pair org-babel-key-bindings)
19483 (define-key org-babel-map (car pair) (cdr pair)))
19485 ;;; Extra keys for tty access.
19486 ;; We only set them when really needed because otherwise the
19487 ;; menus don't show the simple keys
19489 (when (or org-use-extra-keys (not window-system))
19490 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19491 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19492 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19493 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19494 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19495 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19496 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19497 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19498 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19499 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19500 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19501 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19502 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19503 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19504 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19505 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19506 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19507 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19508 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19509 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19510 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19511 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19512 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19513 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19514 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19515 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19516 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19517 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19519 ;; All the other keys
19520 (org-remap org-mode-map
19521 'self-insert-command 'org-self-insert-command
19522 'delete-char 'org-delete-char
19523 'delete-backward-char 'org-delete-backward-char)
19524 (org-defkey org-mode-map "|" 'org-force-self-insert)
19526 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19527 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19528 (if (boundp 'narrow-map)
19529 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19530 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19531 (if (boundp 'narrow-map)
19532 (org-defkey narrow-map "b" 'org-narrow-to-block)
19533 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19534 (if (boundp 'narrow-map)
19535 (org-defkey narrow-map "e" 'org-narrow-to-element)
19536 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19537 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19538 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19539 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19540 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19541 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19542 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19543 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19544 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19545 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19546 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19547 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19548 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19549 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19550 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19551 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19552 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19553 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19554 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19555 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19556 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19557 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19558 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19559 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19560 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19561 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19562 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19563 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19564 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19565 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19566 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19567 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19568 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19569 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19570 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19571 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19572 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19573 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19574 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19575 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19576 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19577 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19578 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19579 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19580 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19581 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19582 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19583 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19584 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19585 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19586 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19587 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19588 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19589 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19590 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19591 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19592 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19593 (org-defkey org-mode-map "\C-c^" 'org-sort)
19594 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19595 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19596 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19597 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19598 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19599 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19600 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19601 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19602 (org-defkey org-mode-map "\C-m" 'org-return)
19603 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19604 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19605 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19606 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19607 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19608 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19609 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19610 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19611 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19612 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19613 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19614 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19615 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19616 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19617 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19618 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19619 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19620 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19621 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19622 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19623 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19624 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19625 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19626 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19627 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19629 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19630 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19631 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19633 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19634 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19635 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19636 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19637 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19638 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19639 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19640 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19641 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19642 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19643 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19644 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19645 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19646 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19647 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19648 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19649 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19650 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19651 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19652 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19653 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19654 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19656 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19657 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19658 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19659 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19660 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19662 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19664 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19666 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19667 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19669 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19672 (defconst org-speed-commands-default
19674 ("Outline Navigation")
19675 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19676 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19677 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19678 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19679 ("F" . org-next-block)
19680 ("B" . org-previous-block)
19681 ("u" . (org-speed-move-safe 'outline-up-heading))
19682 ("j" . org-goto)
19683 ("g" . (org-refile t))
19684 ("Outline Visibility")
19685 ("c" . org-cycle)
19686 ("C" . org-shifttab)
19687 (" " . org-display-outline-path)
19688 ("s" . org-narrow-to-subtree)
19689 ("=" . org-columns)
19690 ("Outline Structure Editing")
19691 ("U" . org-metaup)
19692 ("D" . org-metadown)
19693 ("r" . org-metaright)
19694 ("l" . org-metaleft)
19695 ("R" . org-shiftmetaright)
19696 ("L" . org-shiftmetaleft)
19697 ("i" . (progn (forward-char 1) (call-interactively
19698 'org-insert-heading-respect-content)))
19699 ("^" . org-sort)
19700 ("w" . org-refile)
19701 ("a" . org-archive-subtree-default-with-confirmation)
19702 ("@" . org-mark-subtree)
19703 ("#" . org-toggle-comment)
19704 ("Clock Commands")
19705 ("I" . org-clock-in)
19706 ("O" . org-clock-out)
19707 ("Meta Data Editing")
19708 ("t" . org-todo)
19709 ("," . (org-priority))
19710 ("0" . (org-priority ?\ ))
19711 ("1" . (org-priority ?A))
19712 ("2" . (org-priority ?B))
19713 ("3" . (org-priority ?C))
19714 (":" . org-set-tags-command)
19715 ("e" . org-set-effort)
19716 ("E" . org-inc-effort)
19717 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19718 (org-entry-put (point) "APPT_WARNTIME" m)))
19719 ("Agenda Views etc")
19720 ("v" . org-agenda)
19721 ("/" . org-sparse-tree)
19722 ("Misc")
19723 ("o" . org-open-at-point)
19724 ("?" . org-speed-command-help)
19725 ("<" . (org-agenda-set-restriction-lock 'subtree))
19726 (">" . (org-agenda-remove-restriction-lock))
19728 "The default speed commands.")
19730 (defun org-print-speed-command (e)
19731 (if (> (length (car e)) 1)
19732 (progn
19733 (princ "\n")
19734 (princ (car e))
19735 (princ "\n")
19736 (princ (make-string (length (car e)) ?-))
19737 (princ "\n"))
19738 (princ (car e))
19739 (princ " ")
19740 (if (symbolp (cdr e))
19741 (princ (symbol-name (cdr e)))
19742 (prin1 (cdr e)))
19743 (princ "\n")))
19745 (defun org-speed-command-help ()
19746 "Show the available speed commands."
19747 (interactive)
19748 (if (not org-use-speed-commands)
19749 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19750 (with-output-to-temp-buffer "*Help*"
19751 (princ "User-defined Speed commands\n===========================\n")
19752 (mapc #'org-print-speed-command org-speed-commands-user)
19753 (princ "\n")
19754 (princ "Built-in Speed commands\n=======================\n")
19755 (mapc #'org-print-speed-command org-speed-commands-default))
19756 (with-current-buffer "*Help*"
19757 (setq truncate-lines t))))
19759 (defun org-speed-move-safe (cmd)
19760 "Execute CMD, but make sure that the cursor always ends up in a headline.
19761 If not, return to the original position and throw an error."
19762 (interactive)
19763 (let ((pos (point)))
19764 (call-interactively cmd)
19765 (unless (and (bolp) (org-at-heading-p))
19766 (goto-char pos)
19767 (error "Boundary reached while executing %s" cmd))))
19769 (defvar org-self-insert-command-undo-counter 0)
19771 (defvar org-table-auto-blank-field) ; defined in org-table.el
19772 (defvar org-speed-command nil)
19774 (defun org-speed-command-activate (keys)
19775 "Hook for activating single-letter speed commands.
19776 `org-speed-commands-default' specifies a minimal command set.
19777 Use `org-speed-commands-user' for further customization."
19778 (when (or (and (bolp) (looking-at org-outline-regexp))
19779 (and (functionp org-use-speed-commands)
19780 (funcall org-use-speed-commands)))
19781 (cdr (assoc keys (append org-speed-commands-user
19782 org-speed-commands-default)))))
19784 (defun org-babel-speed-command-activate (keys)
19785 "Hook for activating single-letter code block commands."
19786 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19787 (cdr (assoc keys org-babel-key-bindings))))
19789 (defcustom org-speed-command-hook
19790 '(org-speed-command-activate org-babel-speed-command-activate)
19791 "Hook for activating speed commands at strategic locations.
19792 Hook functions are called in sequence until a valid handler is
19793 found.
19795 Each hook takes a single argument, a user-pressed command key
19796 which is also a `self-insert-command' from the global map.
19798 Within the hook, examine the cursor position and the command key
19799 and return nil or a valid handler as appropriate. Handler could
19800 be one of an interactive command, a function, or a form.
19802 Set `org-use-speed-commands' to non-nil value to enable this
19803 hook. The default setting is `org-speed-command-activate'."
19804 :group 'org-structure
19805 :version "24.1"
19806 :type 'hook)
19808 (defun org-self-insert-command (N)
19809 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19810 If the cursor is in a table looking at whitespace, the whitespace is
19811 overwritten, and the table is not marked as requiring realignment."
19812 (interactive "p")
19813 (org-check-before-invisible-edit 'insert)
19814 (cond
19815 ((and org-use-speed-commands
19816 (let ((kv (this-command-keys-vector)))
19817 (setq org-speed-command
19818 (run-hook-with-args-until-success
19819 'org-speed-command-hook
19820 (make-string 1 (aref kv (1- (length kv))))))))
19821 (cond
19822 ((commandp org-speed-command)
19823 (setq this-command org-speed-command)
19824 (call-interactively org-speed-command))
19825 ((functionp org-speed-command)
19826 (funcall org-speed-command))
19827 ((and org-speed-command (listp org-speed-command))
19828 (eval org-speed-command))
19829 (t (let (org-use-speed-commands)
19830 (call-interactively 'org-self-insert-command)))))
19831 ((and
19832 (org-at-table-p)
19833 (eq N 1)
19834 (not (org-region-active-p))
19835 (progn
19836 ;; Check if we blank the field, and if that triggers align.
19837 (and (featurep 'org-table) org-table-auto-blank-field
19838 (memq last-command
19839 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19840 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19841 ;; Got extra space, this field does not determine
19842 ;; column width.
19843 (let (org-table-may-need-update) (org-table-blank-field))
19844 ;; No extra space, this field may determine column
19845 ;; width.
19846 (org-table-blank-field)))
19848 (looking-at "[^|\n]* \\( \\)|"))
19849 ;; There is room for insertion without re-aligning the table.
19850 (delete-region (match-beginning 1) (match-end 1))
19851 (self-insert-command N))
19853 (setq org-table-may-need-update t)
19854 (self-insert-command N)
19855 (org-fix-tags-on-the-fly)
19856 (when org-self-insert-cluster-for-undo
19857 (if (not (eq last-command 'org-self-insert-command))
19858 (setq org-self-insert-command-undo-counter 1)
19859 (if (>= org-self-insert-command-undo-counter 20)
19860 (setq org-self-insert-command-undo-counter 1)
19861 (and (> org-self-insert-command-undo-counter 0)
19862 buffer-undo-list (listp buffer-undo-list)
19863 (not (cadr buffer-undo-list)) ; remove nil entry
19864 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19865 (setq org-self-insert-command-undo-counter
19866 (1+ org-self-insert-command-undo-counter))))))))
19868 (defun org-check-before-invisible-edit (kind)
19869 "Check is editing if kind KIND would be dangerous with invisible text around.
19870 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19871 ;; First, try to get out of here as quickly as possible, to reduce overhead
19872 (when (and org-catch-invisible-edits
19873 (or (not (boundp 'visible-mode)) (not visible-mode))
19874 (or (get-char-property (point) 'invisible)
19875 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19876 ;; OK, we need to take a closer look. Do not consider
19877 ;; invisibility obtained through text properties (e.g., link
19878 ;; fontification), as it cannot be toggled.
19879 (let* ((invisible-at-point
19880 (pcase (get-char-property-and-overlay (point) 'invisible)
19881 (`(,_ . ,(and (pred overlayp) o)) o)))
19882 ;; Assume that point cannot land in the middle of an
19883 ;; overlay, or between two overlays.
19884 (invisible-before-point
19885 (and (not invisible-at-point)
19886 (not (bobp))
19887 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19888 (`(,_ . ,(and (pred overlayp) o)) o))))
19889 (border-and-ok-direction
19891 ;; Check if we are acting predictably before invisible
19892 ;; text.
19893 (and invisible-at-point
19894 (memq kind '(insert delete-backward)))
19895 ;; Check if we are acting predictably after invisible text
19896 ;; This works not well, and I have turned it off. It seems
19897 ;; better to always show and stop after invisible text.
19898 ;; (and (not invisible-at-point) invisible-before-point
19899 ;; (memq kind '(insert delete)))
19901 (when (or invisible-at-point invisible-before-point)
19902 (when (eq org-catch-invisible-edits 'error)
19903 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19904 (if (and org-custom-properties-overlays
19905 (y-or-n-p "Display invisible properties in this buffer? "))
19906 (org-toggle-custom-properties-visibility)
19907 ;; Make the area visible
19908 (save-excursion
19909 (when invisible-before-point
19910 (goto-char
19911 (previous-single-char-property-change (point) 'invisible)))
19912 ;; Remove whatever overlay is currently making yet-to-be
19913 ;; edited text invisible. Also remove nested invisibility
19914 ;; related overlays.
19915 (delete-overlay (or invisible-at-point invisible-before-point))
19916 (let ((origin (if invisible-at-point (point) (1- (point)))))
19917 (while (pcase (get-char-property-and-overlay origin 'invisible)
19918 (`(,_ . ,(and (pred overlayp) o))
19919 (delete-overlay o)
19920 t)))))
19921 (cond
19922 ((eq org-catch-invisible-edits 'show)
19923 ;; That's it, we do the edit after showing
19924 (message
19925 "Unfolding invisible region around point before editing")
19926 (sit-for 1))
19927 ((and (eq org-catch-invisible-edits 'smart)
19928 border-and-ok-direction)
19929 (message "Unfolding invisible region around point before editing"))
19931 ;; Don't do the edit, make the user repeat it in full visibility
19932 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19934 (defun org-fix-tags-on-the-fly ()
19935 "Align tags in headline at point.
19936 Unlike to `org-set-tags', it ignores region and sorting."
19937 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19938 (org-at-heading-p))
19939 (let ((org-ignore-region t)
19940 (org-tags-sort-function nil))
19941 (org-set-tags nil t))))
19943 (defun org-delete-backward-char (N)
19944 "Like `delete-backward-char', insert whitespace at field end in tables.
19945 When deleting backwards, in tables this function will insert whitespace in
19946 front of the next \"|\" separator, to keep the table aligned. The table will
19947 still be marked for re-alignment if the field did fill the entire column,
19948 because, in this case the deletion might narrow the column."
19949 (interactive "p")
19950 (save-match-data
19951 (org-check-before-invisible-edit 'delete-backward)
19952 (if (and (org-at-table-p)
19953 (eq N 1)
19954 (not (org-region-active-p))
19955 (string-match "|" (buffer-substring (point-at-bol) (point)))
19956 (looking-at ".*?|"))
19957 (let ((pos (point))
19958 (noalign (looking-at "[^|\n\r]* |"))
19959 (c org-table-may-need-update))
19960 (backward-delete-char N)
19961 (unless overwrite-mode
19962 (skip-chars-forward "^|")
19963 (insert " ")
19964 (goto-char (1- pos)))
19965 ;; noalign: if there were two spaces at the end, this field
19966 ;; does not determine the width of the column.
19967 (when noalign (setq org-table-may-need-update c)))
19968 (backward-delete-char N)
19969 (org-fix-tags-on-the-fly))))
19971 (defun org-delete-char (N)
19972 "Like `delete-char', but insert whitespace at field end in tables.
19973 When deleting characters, in tables this function will insert whitespace in
19974 front of the next \"|\" separator, to keep the table aligned. The table will
19975 still be marked for re-alignment if the field did fill the entire column,
19976 because, in this case the deletion might narrow the column."
19977 (interactive "p")
19978 (save-match-data
19979 (org-check-before-invisible-edit 'delete)
19980 (if (and (org-at-table-p)
19981 (not (bolp))
19982 (not (= (char-after) ?|))
19983 (eq N 1))
19984 (if (looking-at ".*?|")
19985 (let ((pos (point))
19986 (noalign (looking-at "[^|\n\r]* |"))
19987 (c org-table-may-need-update))
19988 (replace-match
19989 (concat (substring (match-string 0) 1 -1) " |") nil t)
19990 (goto-char pos)
19991 ;; noalign: if there were two spaces at the end, this field
19992 ;; does not determine the width of the column.
19993 (when noalign (setq org-table-may-need-update c)))
19994 (delete-char N))
19995 (delete-char N)
19996 (org-fix-tags-on-the-fly))))
19998 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19999 (put 'org-self-insert-command 'delete-selection
20000 (lambda ()
20001 (not (run-hook-with-args-until-success
20002 'self-insert-uses-region-functions))))
20003 (put 'orgtbl-self-insert-command 'delete-selection
20004 (lambda ()
20005 (not (run-hook-with-args-until-success
20006 'self-insert-uses-region-functions))))
20007 (put 'org-delete-char 'delete-selection 'supersede)
20008 (put 'org-delete-backward-char 'delete-selection 'supersede)
20009 (put 'org-yank 'delete-selection 'yank)
20011 ;; Make `flyspell-mode' delay after some commands
20012 (put 'org-self-insert-command 'flyspell-delayed t)
20013 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20014 (put 'org-delete-char 'flyspell-delayed t)
20015 (put 'org-delete-backward-char 'flyspell-delayed t)
20017 ;; Make pabbrev-mode expand after Org mode commands
20018 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20019 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20021 (defun org-transpose-words ()
20022 "Transpose words for Org.
20023 This uses the `org-mode-transpose-word-syntax-table' syntax
20024 table, which interprets characters in `org-emphasis-alist' as
20025 word constituents."
20026 (interactive)
20027 (with-syntax-table org-mode-transpose-word-syntax-table
20028 (call-interactively 'transpose-words)))
20029 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20031 (defvar org-ctrl-c-ctrl-c-hook nil
20032 "Hook for functions attaching themselves to `C-c C-c'.
20034 This can be used to add additional functionality to the C-c C-c
20035 key which executes context-dependent commands. This hook is run
20036 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20037 run after the last test.
20039 Each function will be called with no arguments. The function
20040 must check if the context is appropriate for it to act. If yes,
20041 it should do its thing and then return a non-nil value. If the
20042 context is wrong, just do nothing and return nil.")
20044 (defvar org-ctrl-c-ctrl-c-final-hook nil
20045 "Hook for functions attaching themselves to `C-c C-c'.
20047 This can be used to add additional functionality to the C-c C-c
20048 key which executes context-dependent commands. This hook is run
20049 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20050 before the first test.
20052 Each function will be called with no arguments. The function
20053 must check if the context is appropriate for it to act. If yes,
20054 it should do its thing and then return a non-nil value. If the
20055 context is wrong, just do nothing and return nil.")
20057 (defvar org-tab-first-hook nil
20058 "Hook for functions to attach themselves to TAB.
20059 See `org-ctrl-c-ctrl-c-hook' for more information.
20060 This hook runs as the first action when TAB is pressed, even before
20061 `org-cycle' messes around with the `outline-regexp' to cater for
20062 inline tasks and plain list item folding.
20063 If any function in this hook returns t, any other actions that
20064 would have been caused by TAB (such as table field motion or visibility
20065 cycling) will not occur.")
20067 (defvar org-tab-after-check-for-table-hook nil
20068 "Hook for functions to attach themselves to TAB.
20069 See `org-ctrl-c-ctrl-c-hook' for more information.
20070 This hook runs after it has been established that the cursor is not in a
20071 table, but before checking if the cursor is in a headline or if global cycling
20072 should be done.
20073 If any function in this hook returns t, not other actions like visibility
20074 cycling will be done.")
20076 (defvar org-tab-after-check-for-cycling-hook nil
20077 "Hook for functions to attach themselves to TAB.
20078 See `org-ctrl-c-ctrl-c-hook' for more information.
20079 This hook runs after it has been established that not table field motion and
20080 not visibility should be done because of current context. This is probably
20081 the place where a package like yasnippets can hook in.")
20083 (defvar org-tab-before-tab-emulation-hook nil
20084 "Hook for functions to attach themselves to TAB.
20085 See `org-ctrl-c-ctrl-c-hook' for more information.
20086 This hook runs after every other options for TAB have been exhausted, but
20087 before indentation and \t insertion takes place.")
20089 (defvar org-metaleft-hook nil
20090 "Hook for functions attaching themselves to `M-left'.
20091 See `org-ctrl-c-ctrl-c-hook' for more information.")
20092 (defvar org-metaright-hook nil
20093 "Hook for functions attaching themselves to `M-right'.
20094 See `org-ctrl-c-ctrl-c-hook' for more information.")
20095 (defvar org-metaup-hook nil
20096 "Hook for functions attaching themselves to `M-up'.
20097 See `org-ctrl-c-ctrl-c-hook' for more information.")
20098 (defvar org-metadown-hook nil
20099 "Hook for functions attaching themselves to `M-down'.
20100 See `org-ctrl-c-ctrl-c-hook' for more information.")
20101 (defvar org-shiftmetaleft-hook nil
20102 "Hook for functions attaching themselves to `M-S-left'.
20103 See `org-ctrl-c-ctrl-c-hook' for more information.")
20104 (defvar org-shiftmetaright-hook nil
20105 "Hook for functions attaching themselves to `M-S-right'.
20106 See `org-ctrl-c-ctrl-c-hook' for more information.")
20107 (defvar org-shiftmetaup-hook nil
20108 "Hook for functions attaching themselves to `M-S-up'.
20109 See `org-ctrl-c-ctrl-c-hook' for more information.")
20110 (defvar org-shiftmetadown-hook nil
20111 "Hook for functions attaching themselves to `M-S-down'.
20112 See `org-ctrl-c-ctrl-c-hook' for more information.")
20113 (defvar org-metareturn-hook nil
20114 "Hook for functions attaching themselves to `M-RET'.
20115 See `org-ctrl-c-ctrl-c-hook' for more information.")
20116 (defvar org-shiftup-hook nil
20117 "Hook for functions attaching themselves to `S-up'.
20118 See `org-ctrl-c-ctrl-c-hook' for more information.")
20119 (defvar org-shiftup-final-hook nil
20120 "Hook for functions attaching themselves to `S-up'.
20121 This one runs after all other options except shift-select have been excluded.
20122 See `org-ctrl-c-ctrl-c-hook' for more information.")
20123 (defvar org-shiftdown-hook nil
20124 "Hook for functions attaching themselves to `S-down'.
20125 See `org-ctrl-c-ctrl-c-hook' for more information.")
20126 (defvar org-shiftdown-final-hook nil
20127 "Hook for functions attaching themselves to `S-down'.
20128 This one runs after all other options except shift-select have been excluded.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.")
20130 (defvar org-shiftleft-hook nil
20131 "Hook for functions attaching themselves to `S-left'.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-shiftleft-final-hook nil
20134 "Hook for functions attaching themselves to `S-left'.
20135 This one runs after all other options except shift-select have been excluded.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftright-hook nil
20138 "Hook for functions attaching themselves to `S-right'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftright-final-hook nil
20141 "Hook for functions attaching themselves to `S-right'.
20142 This one runs after all other options except shift-select have been excluded.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20145 (defun org-modifier-cursor-error ()
20146 "Throw an error, a modified cursor command was applied in wrong context."
20147 (user-error "This command is active in special context like tables, headlines or items"))
20149 (defun org-shiftselect-error ()
20150 "Throw an error because Shift-Cursor command was applied in wrong context."
20151 (if (and (boundp 'shift-select-mode) shift-select-mode)
20152 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20153 (user-error "This command works only in special context like headlines or timestamps")))
20155 (defun org-call-for-shift-select (cmd)
20156 (let ((this-command-keys-shift-translated t))
20157 (call-interactively cmd)))
20159 (defun org-shifttab (&optional arg)
20160 "Global visibility cycling or move to previous table field.
20161 Call `org-table-previous-field' within a table.
20162 When ARG is nil, cycle globally through visibility states.
20163 When ARG is a numeric prefix, show contents of this level."
20164 (interactive "P")
20165 (cond
20166 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20167 ((integerp arg)
20168 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20169 (message "Content view to level: %d" arg)
20170 (org-content (prefix-numeric-value arg2))
20171 (org-cycle-show-empty-lines t)
20172 (setq org-cycle-global-status 'overview)))
20173 (t (call-interactively 'org-global-cycle))))
20175 (defun org-shiftmetaleft ()
20176 "Promote subtree or delete table column.
20177 Calls `org-promote-subtree', `org-outdent-item-tree', or
20178 `org-table-delete-column', depending on context. See the
20179 individual commands for more information."
20180 (interactive)
20181 (cond
20182 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20183 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20184 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20185 ((if (not (org-region-active-p)) (org-at-item-p)
20186 (save-excursion (goto-char (region-beginning))
20187 (org-at-item-p)))
20188 (call-interactively 'org-outdent-item-tree))
20189 (t (org-modifier-cursor-error))))
20191 (defun org-shiftmetaright ()
20192 "Demote subtree or insert table column.
20193 Calls `org-demote-subtree', `org-indent-item-tree', or
20194 `org-table-insert-column', depending on context. See the
20195 individual commands for more information."
20196 (interactive)
20197 (cond
20198 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20199 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20200 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20201 ((if (not (org-region-active-p)) (org-at-item-p)
20202 (save-excursion (goto-char (region-beginning))
20203 (org-at-item-p)))
20204 (call-interactively 'org-indent-item-tree))
20205 (t (org-modifier-cursor-error))))
20207 (defun org-shiftmetaup (&optional _arg)
20208 "Drag the line at point up.
20209 In a table, kill the current row.
20210 On a clock timestamp, update the value of the timestamp like `S-<up>'
20211 but also adjust the previous clocked item in the clock history.
20212 Everywhere else, drag the line at point up."
20213 (interactive "P")
20214 (cond
20215 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20216 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20217 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20218 (call-interactively 'org-timestamp-up)))
20219 (t (call-interactively 'org-drag-line-backward))))
20221 (defun org-shiftmetadown (&optional _arg)
20222 "Drag the line at point down.
20223 In a table, insert an empty row at the current line.
20224 On a clock timestamp, update the value of the timestamp like `S-<down>'
20225 but also adjust the previous clocked item in the clock history.
20226 Everywhere else, drag the line at point down."
20227 (interactive "P")
20228 (cond
20229 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20230 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20231 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20232 (call-interactively 'org-timestamp-down)))
20233 (t (call-interactively 'org-drag-line-forward))))
20235 (defsubst org-hidden-tree-error ()
20236 (user-error
20237 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20239 (defun org-metaleft (&optional _arg)
20240 "Promote heading, list item at point or move table column left.
20242 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20243 depending on context. With no specific context, calls the Emacs
20244 default `backward-word'. See the individual commands for more
20245 information.
20247 This function runs the hook `org-metaleft-hook' as a first step,
20248 and returns at first non-nil value."
20249 (interactive "P")
20250 (cond
20251 ((run-hook-with-args-until-success 'org-metaleft-hook))
20252 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20253 ((org-with-limited-levels
20254 (or (org-at-heading-p)
20255 (and (org-region-active-p)
20256 (save-excursion
20257 (goto-char (region-beginning))
20258 (org-at-heading-p)))))
20259 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20260 (call-interactively 'org-do-promote))
20261 ;; At an inline task.
20262 ((org-at-heading-p)
20263 (call-interactively 'org-inlinetask-promote))
20264 ((or (org-at-item-p)
20265 (and (org-region-active-p)
20266 (save-excursion
20267 (goto-char (region-beginning))
20268 (org-at-item-p))))
20269 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20270 (call-interactively 'org-outdent-item))
20271 (t (call-interactively 'backward-word))))
20273 (defun org-metaright (&optional _arg)
20274 "Demote heading, list item at point or move table column right.
20276 In front of a drawer or a block keyword, indent it correctly.
20278 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20279 `org-indent-drawer' or `org-indent-block' depending on context.
20280 With no specific context, calls the Emacs default `forward-word'.
20281 See the individual commands for more information.
20283 This function runs the hook `org-metaright-hook' as a first step,
20284 and returns at first non-nil value."
20285 (interactive "P")
20286 (cond
20287 ((run-hook-with-args-until-success 'org-metaright-hook))
20288 ((org-at-table-p) (call-interactively 'org-table-move-column))
20289 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20290 ((org-at-block-p) (call-interactively 'org-indent-block))
20291 ((org-with-limited-levels
20292 (or (org-at-heading-p)
20293 (and (org-region-active-p)
20294 (save-excursion
20295 (goto-char (region-beginning))
20296 (org-at-heading-p)))))
20297 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20298 (call-interactively 'org-do-demote))
20299 ;; At an inline task.
20300 ((org-at-heading-p)
20301 (call-interactively 'org-inlinetask-demote))
20302 ((or (org-at-item-p)
20303 (and (org-region-active-p)
20304 (save-excursion
20305 (goto-char (region-beginning))
20306 (org-at-item-p))))
20307 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20308 (call-interactively 'org-indent-item))
20309 (t (call-interactively 'forward-word))))
20311 (defun org-check-for-hidden (what)
20312 "Check if there are hidden headlines/items in the current visual line.
20313 WHAT can be either `headlines' or `items'. If the current line is
20314 an outline or item heading and it has a folded subtree below it,
20315 this function returns t, nil otherwise."
20316 (let ((re (cond
20317 ((eq what 'headlines) org-outline-regexp-bol)
20318 ((eq what 'items) (org-item-beginning-re))
20319 (t (error "This should not happen"))))
20320 beg end)
20321 (save-excursion
20322 (catch 'exit
20323 (unless (org-region-active-p)
20324 (setq beg (point-at-bol))
20325 (beginning-of-line 2)
20326 (while (and (not (eobp)) ;; this is like `next-line'
20327 (get-char-property (1- (point)) 'invisible))
20328 (beginning-of-line 2))
20329 (setq end (point))
20330 (goto-char beg)
20331 (goto-char (point-at-eol))
20332 (setq end (max end (point)))
20333 (while (re-search-forward re end t)
20334 (when (get-char-property (match-beginning 0) 'invisible)
20335 (throw 'exit t))))
20336 nil))))
20338 (defun org-metaup (&optional _arg)
20339 "Move subtree up or move table row up.
20340 Calls `org-move-subtree-up' or `org-table-move-row' or
20341 `org-move-item-up', depending on context. See the individual commands
20342 for more information."
20343 (interactive "P")
20344 (cond
20345 ((run-hook-with-args-until-success 'org-metaup-hook))
20346 ((org-region-active-p)
20347 (let* ((a (min (region-beginning) (region-end)))
20348 (b (1- (max (region-beginning) (region-end))))
20349 (c (save-excursion (goto-char a)
20350 (move-beginning-of-line 0)))
20351 (d (save-excursion (goto-char a)
20352 (move-end-of-line 0) (point))))
20353 (transpose-regions a b c d)
20354 (goto-char c)))
20355 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20356 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20357 ((org-at-item-p) (call-interactively 'org-move-item-up))
20358 (t (org-drag-element-backward))))
20360 (defun org-metadown (&optional _arg)
20361 "Move subtree down or move table row down.
20362 Calls `org-move-subtree-down' or `org-table-move-row' or
20363 `org-move-item-down', depending on context. See the individual
20364 commands for more information."
20365 (interactive "P")
20366 (cond
20367 ((run-hook-with-args-until-success 'org-metadown-hook))
20368 ((org-region-active-p)
20369 (let* ((a (min (region-beginning) (region-end)))
20370 (b (max (region-beginning) (region-end)))
20371 (c (save-excursion (goto-char b)
20372 (move-beginning-of-line 1)))
20373 (d (save-excursion (goto-char b)
20374 (move-end-of-line 1) (1+ (point)))))
20375 (transpose-regions a b c d)
20376 (goto-char d)))
20377 ((org-at-table-p) (call-interactively 'org-table-move-row))
20378 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20379 ((org-at-item-p) (call-interactively 'org-move-item-down))
20380 (t (org-drag-element-forward))))
20382 (defun org-shiftup (&optional arg)
20383 "Increase item in timestamp or increase priority of current headline.
20384 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20385 depending on context. See the individual commands for more information."
20386 (interactive "P")
20387 (cond
20388 ((run-hook-with-args-until-success 'org-shiftup-hook))
20389 ((and org-support-shift-select (org-region-active-p))
20390 (org-call-for-shift-select 'previous-line))
20391 ((org-at-timestamp-p 'lax)
20392 (call-interactively (if org-edit-timestamp-down-means-later
20393 'org-timestamp-down 'org-timestamp-up)))
20394 ((and (not (eq org-support-shift-select 'always))
20395 org-enable-priority-commands
20396 (org-at-heading-p))
20397 (call-interactively 'org-priority-up))
20398 ((and (not org-support-shift-select) (org-at-item-p))
20399 (call-interactively 'org-previous-item))
20400 ((org-clocktable-try-shift 'up arg))
20401 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20402 (org-support-shift-select
20403 (org-call-for-shift-select 'previous-line))
20404 (t (org-shiftselect-error))))
20406 (defun org-shiftdown (&optional arg)
20407 "Decrease item in timestamp or decrease priority of current headline.
20408 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20409 depending on context. See the individual commands for more information."
20410 (interactive "P")
20411 (cond
20412 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20413 ((and org-support-shift-select (org-region-active-p))
20414 (org-call-for-shift-select 'next-line))
20415 ((org-at-timestamp-p 'lax)
20416 (call-interactively (if org-edit-timestamp-down-means-later
20417 'org-timestamp-up 'org-timestamp-down)))
20418 ((and (not (eq org-support-shift-select 'always))
20419 org-enable-priority-commands
20420 (org-at-heading-p))
20421 (call-interactively 'org-priority-down))
20422 ((and (not org-support-shift-select) (org-at-item-p))
20423 (call-interactively 'org-next-item))
20424 ((org-clocktable-try-shift 'down arg))
20425 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20426 (org-support-shift-select
20427 (org-call-for-shift-select 'next-line))
20428 (t (org-shiftselect-error))))
20430 (defun org-shiftright (&optional arg)
20431 "Cycle the thing at point or in the current line, depending on context.
20432 Depending on context, this does one of the following:
20434 - switch a timestamp at point one day into the future
20435 - on a headline, switch to the next TODO keyword.
20436 - on an item, switch entire list to the next bullet type
20437 - on a property line, switch to the next allowed value
20438 - on a clocktable definition line, move time block into the future"
20439 (interactive "P")
20440 (cond
20441 ((run-hook-with-args-until-success 'org-shiftright-hook))
20442 ((and org-support-shift-select (org-region-active-p))
20443 (org-call-for-shift-select 'forward-char))
20444 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20445 ((and (not (eq org-support-shift-select 'always))
20446 (org-at-heading-p))
20447 (let ((org-inhibit-logging
20448 (not org-treat-S-cursor-todo-selection-as-state-change))
20449 (org-inhibit-blocking
20450 (not org-treat-S-cursor-todo-selection-as-state-change)))
20451 (org-call-with-arg 'org-todo 'right)))
20452 ((or (and org-support-shift-select
20453 (not (eq org-support-shift-select 'always))
20454 (org-at-item-bullet-p))
20455 (and (not org-support-shift-select) (org-at-item-p)))
20456 (org-call-with-arg 'org-cycle-list-bullet nil))
20457 ((and (not (eq org-support-shift-select 'always))
20458 (org-at-property-p))
20459 (call-interactively 'org-property-next-allowed-value))
20460 ((org-clocktable-try-shift 'right arg))
20461 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20462 (org-support-shift-select
20463 (org-call-for-shift-select 'forward-char))
20464 (t (org-shiftselect-error))))
20466 (defun org-shiftleft (&optional arg)
20467 "Cycle the thing at point or in the current line, depending on context.
20468 Depending on context, this does one of the following:
20470 - switch a timestamp at point one day into the past
20471 - on a headline, switch to the previous TODO keyword.
20472 - on an item, switch entire list to the previous bullet type
20473 - on a property line, switch to the previous allowed value
20474 - on a clocktable definition line, move time block into the past"
20475 (interactive "P")
20476 (cond
20477 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20478 ((and org-support-shift-select (org-region-active-p))
20479 (org-call-for-shift-select 'backward-char))
20480 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20481 ((and (not (eq org-support-shift-select 'always))
20482 (org-at-heading-p))
20483 (let ((org-inhibit-logging
20484 (not org-treat-S-cursor-todo-selection-as-state-change))
20485 (org-inhibit-blocking
20486 (not org-treat-S-cursor-todo-selection-as-state-change)))
20487 (org-call-with-arg 'org-todo 'left)))
20488 ((or (and org-support-shift-select
20489 (not (eq org-support-shift-select 'always))
20490 (org-at-item-bullet-p))
20491 (and (not org-support-shift-select) (org-at-item-p)))
20492 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20493 ((and (not (eq org-support-shift-select 'always))
20494 (org-at-property-p))
20495 (call-interactively 'org-property-previous-allowed-value))
20496 ((org-clocktable-try-shift 'left arg))
20497 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20498 (org-support-shift-select
20499 (org-call-for-shift-select 'backward-char))
20500 (t (org-shiftselect-error))))
20502 (defun org-shiftcontrolright ()
20503 "Switch to next TODO set."
20504 (interactive)
20505 (cond
20506 ((and org-support-shift-select (org-region-active-p))
20507 (org-call-for-shift-select 'forward-word))
20508 ((and (not (eq org-support-shift-select 'always))
20509 (org-at-heading-p))
20510 (org-call-with-arg 'org-todo 'nextset))
20511 (org-support-shift-select
20512 (org-call-for-shift-select 'forward-word))
20513 (t (org-shiftselect-error))))
20515 (defun org-shiftcontrolleft ()
20516 "Switch to previous TODO set."
20517 (interactive)
20518 (cond
20519 ((and org-support-shift-select (org-region-active-p))
20520 (org-call-for-shift-select 'backward-word))
20521 ((and (not (eq org-support-shift-select 'always))
20522 (org-at-heading-p))
20523 (org-call-with-arg 'org-todo 'previousset))
20524 (org-support-shift-select
20525 (org-call-for-shift-select 'backward-word))
20526 (t (org-shiftselect-error))))
20528 (defun org-shiftcontrolup (&optional n)
20529 "Change timestamps synchronously up in CLOCK log lines.
20530 Optional argument N tells to change by that many units."
20531 (interactive "P")
20532 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20533 (let (org-support-shift-select)
20534 (org-clock-timestamps-up n))
20535 (user-error "Not at a clock log")))
20537 (defun org-shiftcontroldown (&optional n)
20538 "Change timestamps synchronously down in CLOCK log lines.
20539 Optional argument N tells to change by that many units."
20540 (interactive "P")
20541 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20542 (let (org-support-shift-select)
20543 (org-clock-timestamps-down n))
20544 (user-error "Not at a clock log")))
20546 (defun org-increase-number-at-point (&optional inc)
20547 "Increment the number at point.
20548 With an optional prefix numeric argument INC, increment using
20549 this numeric value."
20550 (interactive "p")
20551 (if (not (number-at-point))
20552 (user-error "Not on a number")
20553 (unless inc (setq inc 1))
20554 (let ((pos (point))
20555 (beg (skip-chars-backward "-+^/*0-9eE."))
20556 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20557 (setq nap (buffer-substring-no-properties
20558 (+ pos beg) (+ pos beg end)))
20559 (delete-region (+ pos beg) (+ pos beg end))
20560 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20561 (when (org-at-table-p)
20562 (org-table-align)
20563 (org-table-end-of-field 1))))
20565 (defun org-decrease-number-at-point (&optional inc)
20566 "Decrement the number at point.
20567 With an optional prefix numeric argument INC, decrement using
20568 this numeric value."
20569 (interactive "p")
20570 (org-increase-number-at-point (- (or inc 1))))
20572 (defun org-ctrl-c-ret ()
20573 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20574 (interactive)
20575 (cond
20576 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20577 (t (call-interactively 'org-insert-heading))))
20579 (defun org-find-visible ()
20580 (let ((s (point)))
20581 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20582 (get-char-property s 'invisible)))
20584 (defun org-find-invisible ()
20585 (let ((s (point)))
20586 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20587 (not (get-char-property s 'invisible))))
20590 (defun org-copy-visible (beg end)
20591 "Copy the visible parts of the region."
20592 (interactive "r")
20593 (let ((result ""))
20594 (while (/= beg end)
20595 (when (get-char-property beg 'invisible)
20596 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20597 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20598 (setq result (concat result (buffer-substring beg next)))
20599 (setq beg next)))
20600 (kill-new result)))
20602 (defun org-copy-special ()
20603 "Copy region in table or copy current subtree.
20604 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20605 context. See the individual commands for more information."
20606 (interactive)
20607 (call-interactively
20608 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20610 (defun org-cut-special ()
20611 "Cut region in table or cut current subtree.
20612 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20613 context. See the individual commands for more information."
20614 (interactive)
20615 (call-interactively
20616 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20618 (defun org-paste-special (arg)
20619 "Paste rectangular region into table, or past subtree relative to level.
20620 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20621 See the individual commands for more information."
20622 (interactive "P")
20623 (if (org-at-table-p)
20624 (org-table-paste-rectangle)
20625 (org-paste-subtree arg)))
20627 (defun org-edit-special (&optional arg)
20628 "Call a special editor for the element at point.
20629 When at a table, call the formula editor with `org-table-edit-formulas'.
20630 When in a source code block, call `org-edit-src-code'.
20631 When in a fixed-width region, call `org-edit-fixed-width-region'.
20632 When in an export block, call `org-edit-export-block'.
20633 When in a LaTeX environment, call `org-edit-latex-environment'.
20634 When at an #+INCLUDE keyword, visit the included file.
20635 When at a footnote reference, call `org-edit-footnote-reference'
20636 On a link, call `ffap' to visit the link at point.
20637 Otherwise, return a user error."
20638 (interactive "P")
20639 (let ((element (org-element-at-point)))
20640 (barf-if-buffer-read-only)
20641 (pcase (org-element-type element)
20642 (`src-block
20643 (if (not arg) (org-edit-src-code)
20644 (let* ((info (org-babel-get-src-block-info))
20645 (lang (nth 0 info))
20646 (params (nth 2 info))
20647 (session (cdr (assq :session params))))
20648 (if (not session) (org-edit-src-code)
20649 ;; At a src-block with a session and function called with
20650 ;; an ARG: switch to the buffer related to the inferior
20651 ;; process.
20652 (switch-to-buffer
20653 (funcall (intern (concat "org-babel-prep-session:" lang))
20654 session params))))))
20655 (`keyword
20656 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20657 (org-open-link-from-string
20658 (format "[[%s]]"
20659 (expand-file-name
20660 (let ((value (org-element-property :value element)))
20661 (cond ((org-file-url-p value)
20662 (user-error "The file is specified as a URL, cannot be edited"))
20663 ((not (org-string-nw-p value))
20664 (user-error "No file to edit"))
20665 ((string-match "\\`\"\\(.*?\\)\"" value)
20666 (match-string 1 value))
20667 ((string-match "\\`[^ \t\"]\\S-*" value)
20668 (match-string 0 value))
20669 (t (user-error "No valid file specified")))))))
20670 (user-error "No special environment to edit here")))
20671 (`table
20672 (if (eq (org-element-property :type element) 'table.el)
20673 (org-edit-table.el)
20674 (call-interactively 'org-table-edit-formulas)))
20675 ;; Only Org tables contain `table-row' type elements.
20676 (`table-row (call-interactively 'org-table-edit-formulas))
20677 (`example-block (org-edit-src-code))
20678 (`export-block (org-edit-export-block))
20679 (`fixed-width (org-edit-fixed-width-region))
20680 (`latex-environment (org-edit-latex-environment))
20682 ;; No notable element at point. Though, we may be at a link or
20683 ;; a footnote reference, which are objects. Thus, scan deeper.
20684 (let ((context (org-element-context element)))
20685 (pcase (org-element-type context)
20686 (`footnote-reference (org-edit-footnote-reference))
20687 (`inline-src-block (org-edit-inline-src-code))
20688 (`link (call-interactively #'ffap))
20689 (_ (user-error "No special environment to edit here"))))))))
20691 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20692 (defun org-ctrl-c-ctrl-c (&optional arg)
20693 "Set tags in headline, or update according to changed information at point.
20695 This command does many different things, depending on context:
20697 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20698 this is what we do.
20700 - If the cursor is on a statistics cookie, update it.
20702 - If the cursor is in a headline, prompt for tags and insert them
20703 into the current line, aligned to `org-tags-column'. When called
20704 with prefix arg, realign all tags in the current buffer.
20706 - If the cursor is in one of the special #+KEYWORD lines, this
20707 triggers scanning the buffer for these lines and updating the
20708 information.
20710 - If the cursor is inside a table, realign the table. This command
20711 works even if the automatic table editor has been turned off.
20713 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20714 the entire table.
20716 - If the cursor is at a footnote reference or definition, jump to
20717 the corresponding definition or references, respectively.
20719 - If the cursor is a the beginning of a dynamic block, update it.
20721 - If the current buffer is a capture buffer, close note and file it.
20723 - If the cursor is on a <<<target>>>, update radio targets and
20724 corresponding links in this buffer.
20726 - If the cursor is on a numbered item in a plain list, renumber the
20727 ordered list.
20729 - If the cursor is on a checkbox, toggle it.
20731 - If the cursor is on a code block, evaluate it. The variable
20732 `org-confirm-babel-evaluate' can be used to control prompting
20733 before code block evaluation, by default every code block
20734 evaluation requires confirmation. Code block evaluation can be
20735 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20736 (interactive "P")
20737 (cond
20738 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20739 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20740 (org-remove-occur-highlights)
20741 (message "Temporary highlights/overlays removed from current buffer"))
20742 ((and (local-variable-p 'org-finish-function)
20743 (fboundp org-finish-function))
20744 (funcall org-finish-function))
20745 ((org-babel-hash-at-point))
20746 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20748 (let* ((context
20749 (org-element-lineage
20750 (org-element-context)
20751 ;; Limit to supported contexts.
20752 '(babel-call clock dynamic-block footnote-definition
20753 footnote-reference inline-babel-call inline-src-block
20754 inlinetask item keyword node-property paragraph
20755 plain-list planning property-drawer radio-target
20756 src-block statistics-cookie table table-cell table-row
20757 timestamp)
20759 (type (org-element-type context)))
20760 ;; For convenience: at the first line of a paragraph on the same
20761 ;; line as an item, apply function on that item instead.
20762 (when (eq type 'paragraph)
20763 (let ((parent (org-element-property :parent context)))
20764 (when (and (eq (org-element-type parent) 'item)
20765 (= (line-beginning-position)
20766 (org-element-property :begin parent)))
20767 (setq context parent)
20768 (setq type 'item))))
20769 ;; Act according to type of element or object at point.
20771 ;; Do nothing on a blank line, except if it is contained in
20772 ;; a src block. Hence, we first check if point is in such
20773 ;; a block and then if it is at a blank line.
20774 (pcase type
20775 ((or `inline-src-block `src-block)
20776 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20777 (org-babel-eval-wipe-error-buffer)
20778 (org-babel-execute-src-block
20779 current-prefix-arg (org-babel-get-src-block-info nil context))))
20780 ((guard (org-match-line "[ \t]*$"))
20781 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20782 (user-error
20783 (substitute-command-keys
20784 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20785 ((or `babel-call `inline-babel-call)
20786 (let ((info (org-babel-lob-get-info context)))
20787 (when info (org-babel-execute-src-block nil info))))
20788 (`clock (org-clock-update-time-maybe))
20789 (`dynamic-block
20790 (save-excursion
20791 (goto-char (org-element-property :post-affiliated context))
20792 (org-update-dblock)))
20793 (`footnote-definition
20794 (goto-char (org-element-property :post-affiliated context))
20795 (call-interactively 'org-footnote-action))
20796 (`footnote-reference (call-interactively #'org-footnote-action))
20797 ((or `headline `inlinetask)
20798 (save-excursion (goto-char (org-element-property :begin context))
20799 (call-interactively #'org-set-tags)))
20800 (`item
20801 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20802 ;; unconditionally, whereas `C-u' will toggle its presence.
20803 ;; Without a universal argument, if the item has a checkbox,
20804 ;; toggle it. Otherwise repair the list.
20805 (let* ((box (org-element-property :checkbox context))
20806 (struct (org-element-property :structure context))
20807 (old-struct (copy-tree struct))
20808 (parents (org-list-parents-alist struct))
20809 (prevs (org-list-prevs-alist struct))
20810 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20811 (org-list-set-checkbox
20812 (org-element-property :begin context) struct
20813 (cond ((equal arg '(16)) "[-]")
20814 ((and (not box) (equal arg '(4))) "[ ]")
20815 ((or (not box) (equal arg '(4))) nil)
20816 ((eq box 'on) "[ ]")
20817 (t "[X]")))
20818 ;; Mimic `org-list-write-struct' but with grabbing a return
20819 ;; value from `org-list-struct-fix-box'.
20820 (org-list-struct-fix-ind struct parents 2)
20821 (org-list-struct-fix-item-end struct)
20822 (org-list-struct-fix-bul struct prevs)
20823 (org-list-struct-fix-ind struct parents)
20824 (let ((block-item
20825 (org-list-struct-fix-box struct parents prevs orderedp)))
20826 (if (and box (equal struct old-struct))
20827 (if (equal arg '(16))
20828 (message "Checkboxes already reset")
20829 (user-error "Cannot toggle this checkbox: %s"
20830 (if (eq box 'on)
20831 "all subitems checked"
20832 "unchecked subitems")))
20833 (org-list-struct-apply-struct struct old-struct)
20834 (org-update-checkbox-count-maybe))
20835 (when block-item
20836 (message "Checkboxes were removed due to empty box at line %d"
20837 (org-current-line block-item))))))
20838 (`keyword
20839 (let ((org-inhibit-startup-visibility-stuff t)
20840 (org-startup-align-all-tables nil))
20841 (when (boundp 'org-table-coordinate-overlays)
20842 (mapc #'delete-overlay org-table-coordinate-overlays)
20843 (setq org-table-coordinate-overlays nil))
20844 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20845 (message "Local setup has been refreshed"))
20846 (`plain-list
20847 ;; At a plain list, with a double C-u argument, set
20848 ;; checkboxes of each item to "[-]", whereas a single one
20849 ;; will toggle their presence according to the state of the
20850 ;; first item in the list. Without an argument, repair the
20851 ;; list.
20852 (let* ((begin (org-element-property :contents-begin context))
20853 (beginm (move-marker (make-marker) begin))
20854 (struct (org-element-property :structure context))
20855 (old-struct (copy-tree struct))
20856 (first-box (save-excursion
20857 (goto-char begin)
20858 (looking-at org-list-full-item-re)
20859 (match-string-no-properties 3)))
20860 (new-box (cond ((equal arg '(16)) "[-]")
20861 ((equal arg '(4)) (unless first-box "[ ]"))
20862 ((equal first-box "[X]") "[ ]")
20863 (t "[X]"))))
20864 (cond
20865 (arg
20866 (dolist (pos
20867 (org-list-get-all-items
20868 begin struct (org-list-prevs-alist struct)))
20869 (org-list-set-checkbox pos struct new-box)))
20870 ((and first-box (eq (point) begin))
20871 ;; For convenience, when point is at bol on the first
20872 ;; item of the list and no argument is provided, simply
20873 ;; toggle checkbox of that item, if any.
20874 (org-list-set-checkbox begin struct new-box)))
20875 (org-list-write-struct
20876 struct (org-list-parents-alist struct) old-struct)
20877 (org-update-checkbox-count-maybe)
20878 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20879 ((or `property-drawer `node-property)
20880 (call-interactively #'org-property-action))
20881 (`radio-target
20882 (call-interactively #'org-update-radio-target-regexp))
20883 (`statistics-cookie
20884 (call-interactively #'org-update-statistics-cookies))
20885 ((or `table `table-cell `table-row)
20886 ;; At a table, recalculate every field and align it. Also
20887 ;; send the table if necessary. If the table has
20888 ;; a `table.el' type, just give up. At a table row or cell,
20889 ;; maybe recalculate line but always align table.
20890 (if (eq (org-element-property :type context) 'table.el)
20891 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20892 Use `\\[org-edit-special]' to edit table.el tables"))
20893 (if (or (eq type 'table)
20894 ;; Check if point is at a TBLFM line.
20895 (and (eq type 'table-row)
20896 (= (point) (org-element-property :end context))))
20897 (save-excursion
20898 (if (org-at-TBLFM-p)
20899 (progn (require 'org-table)
20900 (org-table-calc-current-TBLFM))
20901 (goto-char (org-element-property :contents-begin context))
20902 (org-call-with-arg 'org-table-recalculate (or arg t))
20903 (orgtbl-send-table 'maybe)))
20904 (org-table-maybe-eval-formula)
20905 (cond (arg (call-interactively #'org-table-recalculate))
20906 ((org-table-maybe-recalculate-line))
20907 (t (org-table-align))))))
20908 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20909 (org-timestamp-change 0 'day))
20910 ((and `nil (guard (org-at-heading-p)))
20911 ;; When point is on an unsupported object type, we can miss
20912 ;; the fact that it also is at a heading. Handle it here.
20913 (call-interactively #'org-set-tags))
20914 ((guard
20915 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20917 (user-error
20918 (substitute-command-keys
20919 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20921 (defun org-mode-restart ()
20922 (interactive)
20923 (let ((indent-status (bound-and-true-p org-indent-mode)))
20924 (funcall major-mode)
20925 (hack-local-variables)
20926 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20927 (org-indent-mode -1))
20928 (org-reset-file-cache))
20929 (message "%s restarted" major-mode))
20931 (defun org-kill-note-or-show-branches ()
20932 "Abort storing current note, or call `outline-show-branches'."
20933 (interactive)
20934 (if (not org-finish-function)
20935 (progn
20936 (outline-hide-subtree)
20937 (call-interactively 'outline-show-branches))
20938 (let ((org-note-abort t))
20939 (funcall org-finish-function))))
20941 (defun org-delete-indentation (&optional arg)
20942 "Join current line to previous and fix whitespace at join.
20944 If previous line is a headline add to headline title. Otherwise
20945 the function calls `delete-indentation'.
20947 With a non-nil optional argument, join it to the following one."
20948 (interactive "*P")
20949 (if (save-excursion
20950 (beginning-of-line (if arg 1 0))
20951 (let ((case-fold-search nil))
20952 (looking-at org-complex-heading-regexp)))
20953 ;; At headline.
20954 (let ((tags-column (when (match-beginning 5)
20955 (save-excursion (goto-char (match-beginning 5))
20956 (current-column))))
20957 (string (concat " " (progn (when arg (forward-line 1))
20958 (org-trim (delete-and-extract-region
20959 (line-beginning-position)
20960 (line-end-position)))))))
20961 (unless (bobp) (delete-region (point) (1- (point))))
20962 (goto-char (or (match-end 4)
20963 (match-beginning 5)
20964 (match-end 0)))
20965 (skip-chars-backward " \t")
20966 (save-excursion (insert string))
20967 ;; Adjust alignment of tags.
20968 (cond
20969 ((not tags-column)) ;no tags
20970 (org-auto-align-tags (org-set-tags nil t))
20971 (t (org--align-tags-here tags-column)))) ;preserve tags column
20972 (delete-indentation arg)))
20974 (defun org-open-line (n)
20975 "Insert a new row in tables, call `open-line' elsewhere.
20976 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20977 As a special case, when a document starts with a table, allow to
20978 call `open-line' on the very first character."
20979 (interactive "*p")
20980 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20981 (org-table-insert-row)
20982 (open-line n)))
20984 (defun org-return (&optional indent)
20985 "Goto next table row or insert a newline.
20987 Calls `org-table-next-row' or `newline', depending on context.
20989 When optional INDENT argument is non-nil, call
20990 `newline-and-indent' instead of `newline'.
20992 When `org-return-follows-link' is non-nil and point is on
20993 a timestamp or a link, call `org-open-at-point'. However, it
20994 will not happen if point is in a table or on a \"dead\"
20995 object (e.g., within a comment). In these case, you need to use
20996 `org-open-at-point' directly."
20997 (interactive)
20998 (let ((context (if org-return-follows-link (org-element-context)
20999 (org-element-at-point))))
21000 (cond
21001 ;; In a table, call `org-table-next-row'.
21002 ((or (and (eq (org-element-type context) 'table)
21003 (>= (point) (org-element-property :contents-begin context))
21004 (< (point) (org-element-property :contents-end context)))
21005 (org-element-lineage context '(table-row table-cell) t))
21006 (org-table-justify-field-maybe)
21007 (call-interactively #'org-table-next-row))
21008 ;; On a link or a timestamp, call `org-open-at-point' if
21009 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21010 ;; locations, e.g., in a comment, as `org-open-at-point'.
21011 ((and org-return-follows-link
21012 (or (org-in-regexp org-ts-regexp-both nil t)
21013 (org-in-regexp org-tsr-regexp-both nil t)
21014 (org-in-regexp org-any-link-re nil t)))
21015 (call-interactively #'org-open-at-point))
21016 ;; Insert newline in heading, but preserve tags.
21017 ((and (not (bolp))
21018 (save-excursion (beginning-of-line)
21019 (let ((case-fold-search nil))
21020 (looking-at org-complex-heading-regexp))))
21021 ;; At headline. Split line. However, if point is on keyword,
21022 ;; priority cookie or tags, do not break any of them: add
21023 ;; a newline after the headline instead.
21024 (let ((tags-column (and (match-beginning 5)
21025 (save-excursion (goto-char (match-beginning 5))
21026 (current-column))))
21027 (string
21028 (when (and (match-end 4) (org-point-in-group (point) 4))
21029 (delete-and-extract-region (point) (match-end 4)))))
21030 ;; Adjust tag alignment.
21031 (cond
21032 ((not (and tags-column string)))
21033 (org-auto-align-tags (org-set-tags nil t))
21034 (t (org--align-tags-here tags-column))) ;preserve tags column
21035 (end-of-line)
21036 (org-show-entry)
21037 (if indent (newline-and-indent) (newline))
21038 (when string (save-excursion (insert (org-trim string))))))
21039 ;; In a list, make sure indenting keeps trailing text within.
21040 ((and indent
21041 (not (eolp))
21042 (org-element-lineage context '(item)))
21043 (let ((trailing-data
21044 (delete-and-extract-region (point) (line-end-position))))
21045 (newline-and-indent)
21046 (save-excursion (insert trailing-data))))
21047 (t (if indent (newline-and-indent) (newline))))))
21049 (defun org-return-indent ()
21050 "Goto next table row or insert a newline and indent.
21051 Calls `org-table-next-row' or `newline-and-indent', depending on
21052 context. See the individual commands for more information."
21053 (interactive)
21054 (org-return t))
21056 (defun org-ctrl-c-tab (&optional _arg)
21057 "Toggle columns width in a table, or show children.
21058 Call `org-table-toggle-column-width' if point is in a table.
21059 Otherwise, call `org-show-children'."
21060 (interactive "p")
21061 (call-interactively
21062 (if (org-at-table-p) #'org-table-toggle-column-width
21063 #'org-show-children)))
21065 (defun org-ctrl-c-star ()
21066 "Compute table, or change heading status of lines.
21067 Calls `org-table-recalculate' or `org-toggle-heading',
21068 depending on context."
21069 (interactive)
21070 (cond
21071 ((org-at-table-p)
21072 (call-interactively 'org-table-recalculate))
21074 ;; Convert all lines in region to list items
21075 (call-interactively 'org-toggle-heading))))
21077 (defun org-ctrl-c-minus ()
21078 "Insert separator line in table or modify bullet status of line.
21079 Also turns a plain line or a region of lines into list items.
21080 Calls `org-table-insert-hline', `org-toggle-item', or
21081 `org-cycle-list-bullet', depending on context."
21082 (interactive)
21083 (cond
21084 ((org-at-table-p)
21085 (call-interactively 'org-table-insert-hline))
21086 ((org-region-active-p)
21087 (call-interactively 'org-toggle-item))
21088 ((org-in-item-p)
21089 (call-interactively 'org-cycle-list-bullet))
21091 (call-interactively 'org-toggle-item))))
21093 (defun org-toggle-heading (&optional nstars)
21094 "Convert headings to normal text, or items or text to headings.
21095 If there is no active region, only convert the current line.
21097 With a `\\[universal-argument]' prefix, convert the whole list at
21098 point into heading.
21100 In a region:
21102 - If the first non blank line is a headline, remove the stars
21103 from all headlines in the region.
21105 - If it is a normal line, turn each and every normal line (i.e.,
21106 not an heading or an item) in the region into headings. If you
21107 want to convert only the first line of this region, use one
21108 universal prefix argument.
21110 - If it is a plain list item, turn all plain list items into headings.
21112 When converting a line into a heading, the number of stars is chosen
21113 such that the lines become children of the current entry. However,
21114 when a numeric prefix argument is given, its value determines the
21115 number of stars to add."
21116 (interactive "P")
21117 (let ((skip-blanks
21118 (function
21119 ;; Return beginning of first non-blank line, starting from
21120 ;; line at POS.
21121 (lambda (pos)
21122 (save-excursion
21123 (goto-char pos)
21124 (while (org-at-comment-p) (forward-line))
21125 (skip-chars-forward " \r\t\n")
21126 (point-at-bol)))))
21127 beg end toggled)
21128 ;; Determine boundaries of changes. If a universal prefix has
21129 ;; been given, put the list in a region. If region ends at a bol,
21130 ;; do not consider the last line to be in the region.
21132 (when (and current-prefix-arg (org-at-item-p))
21133 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21134 (org-mark-element))
21136 (if (org-region-active-p)
21137 (setq beg (funcall skip-blanks (region-beginning))
21138 end (copy-marker (save-excursion
21139 (goto-char (region-end))
21140 (if (bolp) (point) (point-at-eol)))))
21141 (setq beg (funcall skip-blanks (point-at-bol))
21142 end (copy-marker (point-at-eol))))
21143 ;; Ensure inline tasks don't count as headings.
21144 (org-with-limited-levels
21145 (save-excursion
21146 (goto-char beg)
21147 (cond
21148 ;; Case 1. Started at an heading: de-star headings.
21149 ((org-at-heading-p)
21150 (while (< (point) end)
21151 (when (org-at-heading-p t)
21152 (looking-at org-outline-regexp) (replace-match "")
21153 (setq toggled t))
21154 (forward-line)))
21155 ;; Case 2. Started at an item: change items into headlines.
21156 ;; One star will be added by `org-list-to-subtree'.
21157 ((org-at-item-p)
21158 (while (< (point) end)
21159 (when (org-at-item-p)
21160 ;; Pay attention to cases when region ends before list.
21161 (let* ((struct (org-list-struct))
21162 (list-end
21163 (min (org-list-get-bottom-point struct) (1+ end))))
21164 (save-restriction
21165 (narrow-to-region (point) list-end)
21166 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21167 (setq toggled t))
21168 (forward-line)))
21169 ;; Case 3. Started at normal text: make every line an heading,
21170 ;; skipping headlines and items.
21171 (t (let* ((stars
21172 (make-string
21173 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21174 (add-stars
21175 (cond (nstars "") ; stars from prefix only
21176 ((equal stars "") "*") ; before first heading
21177 (org-odd-levels-only "**") ; inside heading, odd
21178 (t "*"))) ; inside heading, oddeven
21179 (rpl (concat stars add-stars " "))
21180 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21181 (while (< (point) (if (equal nstars '(4)) lend end))
21182 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21183 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21184 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21185 (forward-line)))))))
21186 (unless toggled (message "Cannot toggle heading from here"))))
21188 (defun org-meta-return (&optional arg)
21189 "Insert a new heading or wrap a region in a table.
21190 Calls `org-insert-heading', `org-insert-item' or
21191 `org-table-wrap-region', depending on context. When called with
21192 an argument, unconditionally call `org-insert-heading'."
21193 (interactive "P")
21194 (org-check-before-invisible-edit 'insert)
21195 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21196 (call-interactively (cond (arg #'org-insert-heading)
21197 ((org-at-table-p) #'org-table-wrap-region)
21198 ((org-in-item-p) #'org-insert-item)
21199 (t #'org-insert-heading)))))
21201 ;;; Menu entries
21203 (defsubst org-in-subtree-not-table-p ()
21204 "Are we in a subtree and not in a table?"
21205 (and (not (org-before-first-heading-p))
21206 (not (org-at-table-p))))
21208 ;; Define the Org mode menus
21209 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21210 '("Tbl"
21211 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21212 ["Next Field" org-cycle (org-at-table-p)]
21213 ["Previous Field" org-shifttab (org-at-table-p)]
21214 ["Next Row" org-return (org-at-table-p)]
21215 "--"
21216 ["Blank Field" org-table-blank-field (org-at-table-p)]
21217 ["Edit Field" org-table-edit-field (org-at-table-p)]
21218 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21219 "--"
21220 ("Column"
21221 ["Move Column Left" org-metaleft (org-at-table-p)]
21222 ["Move Column Right" org-metaright (org-at-table-p)]
21223 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21224 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21225 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21226 ("Row"
21227 ["Move Row Up" org-metaup (org-at-table-p)]
21228 ["Move Row Down" org-metadown (org-at-table-p)]
21229 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21230 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21231 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21232 "--"
21233 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21234 ("Rectangle"
21235 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21236 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21237 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21238 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21239 "--"
21240 ("Calculate"
21241 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21242 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21243 ["Edit Formulas" org-edit-special (org-at-table-p)]
21244 "--"
21245 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21246 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21247 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21248 "--"
21249 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21250 "--"
21251 ["Sum Column/Rectangle" org-table-sum
21252 (or (org-at-table-p) (org-region-active-p))]
21253 ["Which Column?" org-table-current-column (org-at-table-p)])
21254 ["Debug Formulas"
21255 org-table-toggle-formula-debugger
21256 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21257 ["Show Col/Row Numbers"
21258 org-table-toggle-coordinate-overlays
21259 :style toggle
21260 :selected (bound-and-true-p org-table-overlay-coordinates)]
21261 "--"
21262 ["Create" org-table-create (not (org-at-table-p))]
21263 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21264 ["Import from File" org-table-import (not (org-at-table-p))]
21265 ["Export to File" org-table-export (org-at-table-p)]
21266 "--"
21267 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21268 "--"
21269 ("Plot"
21270 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21271 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21273 (easy-menu-define org-org-menu org-mode-map "Org menu"
21274 '("Org"
21275 ("Show/Hide"
21276 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21277 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21278 ["Sparse Tree..." org-sparse-tree t]
21279 ["Reveal Context" org-reveal t]
21280 ["Show All" outline-show-all t]
21281 "--"
21282 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21283 "--"
21284 ["New Heading" org-insert-heading t]
21285 ("Navigate Headings"
21286 ["Up" outline-up-heading t]
21287 ["Next" outline-next-visible-heading t]
21288 ["Previous" outline-previous-visible-heading t]
21289 ["Next Same Level" outline-forward-same-level t]
21290 ["Previous Same Level" outline-backward-same-level t]
21291 "--"
21292 ["Jump" org-goto t])
21293 ("Edit Structure"
21294 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21295 "--"
21296 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21297 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21298 "--"
21299 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21300 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21301 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21302 "--"
21303 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21304 "--"
21305 ["Copy visible text" org-copy-visible t]
21306 "--"
21307 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21308 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21309 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21310 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21311 "--"
21312 ["Sort Region/Children" org-sort t]
21313 "--"
21314 ["Convert to odd levels" org-convert-to-odd-levels t]
21315 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21316 ("Editing"
21317 ["Emphasis..." org-emphasize t]
21318 ["Edit Source Example" org-edit-special t]
21319 "--"
21320 ["Footnote new/jump" org-footnote-action t]
21321 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21322 ("Archive"
21323 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21324 "--"
21325 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21326 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21327 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21329 "--"
21330 ("Hyperlinks"
21331 ["Store Link (Global)" org-store-link t]
21332 ["Find existing link to here" org-occur-link-in-agenda-files t]
21333 ["Insert Link" org-insert-link t]
21334 ["Follow Link" org-open-at-point t]
21335 "--"
21336 ["Next link" org-next-link t]
21337 ["Previous link" org-previous-link t]
21338 "--"
21339 ["Descriptive Links"
21340 org-toggle-link-display
21341 :style radio
21342 :selected org-descriptive-links
21344 ["Literal Links"
21345 org-toggle-link-display
21346 :style radio
21347 :selected (not org-descriptive-links)])
21348 "--"
21349 ("TODO Lists"
21350 ["TODO/DONE/-" org-todo t]
21351 ("Select keyword"
21352 ["Next keyword" org-shiftright (org-at-heading-p)]
21353 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21354 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21355 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21356 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21357 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21358 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21359 "--"
21360 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21361 :selected org-enforce-todo-dependencies :style toggle :active t]
21362 "Settings for tree at point"
21363 ["Do Children sequentially" org-toggle-ordered-property :style radio
21364 :selected (org-entry-get nil "ORDERED")
21365 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21366 ["Do Children parallel" org-toggle-ordered-property :style radio
21367 :selected (not (org-entry-get nil "ORDERED"))
21368 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21369 "--"
21370 ["Set Priority" org-priority t]
21371 ["Priority Up" org-shiftup t]
21372 ["Priority Down" org-shiftdown t]
21373 "--"
21374 ["Get news from all feeds" org-feed-update-all t]
21375 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21376 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21377 ("TAGS and Properties"
21378 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21379 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21380 "--"
21381 ["Set property" org-set-property (not (org-before-first-heading-p))]
21382 ["Column view of properties" org-columns t]
21383 ["Insert Column View DBlock" org-columns-insert-dblock t])
21384 ("Dates and Scheduling"
21385 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21386 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21387 ("Change Date"
21388 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21389 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21390 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21391 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21392 ["Compute Time Range" org-evaluate-time-range t]
21393 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21394 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21395 "--"
21396 ["Custom time format" org-toggle-time-stamp-overlays
21397 :style radio :selected org-display-custom-times]
21398 "--"
21399 ["Goto Calendar" org-goto-calendar t]
21400 ["Date from Calendar" org-date-from-calendar t]
21401 "--"
21402 ["Start/Restart Timer" org-timer-start t]
21403 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21404 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21405 ["Insert Timer String" org-timer t]
21406 ["Insert Timer Item" org-timer-item t])
21407 ("Logging work"
21408 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21409 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21410 ["Clock out" org-clock-out t]
21411 ["Clock cancel" org-clock-cancel t]
21412 "--"
21413 ["Mark as default task" org-clock-mark-default-task t]
21414 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21415 ["Goto running clock" org-clock-goto t]
21416 "--"
21417 ["Display times" org-clock-display t]
21418 ["Create clock table" org-clock-report t]
21419 "--"
21420 ["Record DONE time"
21421 (progn (setq org-log-done (not org-log-done))
21422 (message "Switching to %s will %s record a timestamp"
21423 (car org-done-keywords)
21424 (if org-log-done "automatically" "not")))
21425 :style toggle :selected org-log-done])
21426 "--"
21427 ["Agenda Command..." org-agenda t]
21428 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21429 ("File List for Agenda")
21430 ("Special views current file"
21431 ["TODO Tree" org-show-todo-tree t]
21432 ["Check Deadlines" org-check-deadlines t]
21433 ["Tags/Property tree" org-match-sparse-tree t])
21434 "--"
21435 ["Export/Publish..." org-export-dispatch t]
21436 ("LaTeX"
21437 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21438 :selected org-cdlatex-mode]
21439 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21440 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21441 ["Modify math symbol" org-cdlatex-math-modify
21442 (org-inside-LaTeX-fragment-p)]
21443 ["Insert citation" org-reftex-citation t])
21444 "--"
21445 ("MobileOrg"
21446 ["Push Files and Views" org-mobile-push t]
21447 ["Get Captured and Flagged" org-mobile-pull t]
21448 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21449 "--"
21450 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21451 "--"
21452 ("Documentation"
21453 ["Show Version" org-version t]
21454 ["Info Documentation" org-info t])
21455 ("Customize"
21456 ["Browse Org Group" org-customize t]
21457 "--"
21458 ["Expand This Menu" org-create-customize-menu
21459 (fboundp 'customize-menu-create)])
21460 ["Send bug report" org-submit-bug-report t]
21461 "--"
21462 ("Refresh/Reload"
21463 ["Refresh setup current buffer" org-mode-restart t]
21464 ["Reload Org (after update)" org-reload t]
21465 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21468 (defun org-info (&optional node)
21469 "Read documentation for Org in the info system.
21470 With optional NODE, go directly to that node."
21471 (interactive)
21472 (info (format "(org)%s" (or node ""))))
21474 ;;;###autoload
21475 (defun org-submit-bug-report ()
21476 "Submit a bug report on Org via mail.
21478 Don't hesitate to report any problems or inaccurate documentation.
21480 If you don't have setup sending mail from (X)Emacs, please copy the
21481 output buffer into your mail program, as it gives us important
21482 information about your Org version and configuration."
21483 (interactive)
21484 (require 'reporter)
21485 (defvar reporter-prompt-for-summary-p)
21486 (org-load-modules-maybe)
21487 (org-require-autoloaded-modules)
21488 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21489 (reporter-submit-bug-report
21490 "emacs-orgmode@gnu.org"
21491 (org-version nil 'full)
21492 (let (list)
21493 (save-window-excursion
21494 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21495 (delete-other-windows)
21496 (erase-buffer)
21497 (insert "You are about to submit a bug report to the Org mailing list.
21499 We would like to add your full Org and Outline configuration to the
21500 bug report. This greatly simplifies the work of the maintainer and
21501 other experts on the mailing list.
21503 HOWEVER, some variables you have customized may contain private
21504 information. The names of customers, colleagues, or friends, might
21505 appear in the form of file names, tags, todo states, or search strings.
21506 If you answer yes to the prompt, you might want to check and remove
21507 such private information before sending the email.")
21508 (add-text-properties (point-min) (point-max) '(face org-warning))
21509 (when (yes-or-no-p "Include your Org configuration ")
21510 (mapatoms
21511 (lambda (v)
21512 (and (boundp v)
21513 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21514 (or (and (symbol-value v)
21515 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21516 (and
21517 (get v 'custom-type) (get v 'standard-value)
21518 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21519 (push v list)))))
21520 (kill-buffer (get-buffer "*Warn about privacy*"))
21521 list))
21522 nil nil
21523 "Remember to cover the basics, that is, what you expected to happen and
21524 what in fact did happen. You don't know how to make a good report? See
21526 http://orgmode.org/manual/Feedback.html#Feedback
21528 Your bug report will be posted to the Org mailing list.
21529 ------------------------------------------------------------------------")
21530 (save-excursion
21531 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21532 (replace-match "\\1Bug: \\3 [\\2]")))))
21535 (defun org-install-agenda-files-menu ()
21536 (let ((bl (buffer-list)))
21537 (save-excursion
21538 (while bl
21539 (set-buffer (pop bl))
21540 (when (derived-mode-p 'org-mode) (setq bl nil)))
21541 (when (derived-mode-p 'org-mode)
21542 (easy-menu-change
21543 '("Org") "File List for Agenda"
21544 (append
21545 (list
21546 ["Edit File List" (org-edit-agenda-file-list) t]
21547 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21548 ["Remove Current File from List" org-remove-file t]
21549 ["Cycle through agenda files" org-cycle-agenda-files t]
21550 ["Occur in all agenda files" org-occur-in-agenda-files t]
21551 "--")
21552 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21554 ;;;; Documentation
21556 (defun org-require-autoloaded-modules ()
21557 (interactive)
21558 (mapc #'require
21559 '(org-agenda org-archive org-attach org-clock org-colview org-id
21560 org-table org-timer)))
21562 ;;;###autoload
21563 (defun org-reload (&optional uncompiled)
21564 "Reload all org lisp files.
21565 With prefix arg UNCOMPILED, load the uncompiled versions."
21566 (interactive "P")
21567 (require 'loadhist)
21568 (let* ((org-dir (org-find-library-dir "org"))
21569 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21570 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21571 (remove-re (format "\\`%s\\'"
21572 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21573 (feats (delete-dups
21574 (mapcar 'file-name-sans-extension
21575 (mapcar 'file-name-nondirectory
21576 (delq nil
21577 (mapcar 'feature-file
21578 features))))))
21579 (lfeat (append
21580 (sort
21581 (setq feats
21582 (delq nil (mapcar
21583 (lambda (f)
21584 (if (and (string-match feature-re f)
21585 (not (string-match remove-re f)))
21586 f nil))
21587 feats)))
21588 'string-lessp)
21589 (list "org-version" "org")))
21590 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21591 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21592 load-uncore load-misses)
21593 (setq load-misses
21594 (delq 't
21595 (mapcar (lambda (f)
21596 (or (org-load-noerror-mustsuffix (concat org-dir f))
21597 (and (string= org-dir contrib-dir)
21598 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21599 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21600 (add-to-list 'load-uncore f 'append)
21603 lfeat)))
21604 (when load-uncore
21605 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21606 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21607 (if load-misses
21608 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21609 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21610 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21612 ;;;###autoload
21613 (defun org-customize ()
21614 "Call the customize function with org as argument."
21615 (interactive)
21616 (org-load-modules-maybe)
21617 (org-require-autoloaded-modules)
21618 (customize-browse 'org))
21620 (defun org-create-customize-menu ()
21621 "Create a full customization menu for Org mode, insert it into the menu."
21622 (interactive)
21623 (org-load-modules-maybe)
21624 (org-require-autoloaded-modules)
21625 (if (fboundp 'customize-menu-create)
21626 (progn
21627 (easy-menu-change
21628 '("Org") "Customize"
21629 `(["Browse Org group" org-customize t]
21630 "--"
21631 ,(customize-menu-create 'org)
21632 ["Set" Custom-set t]
21633 ["Save" Custom-save t]
21634 ["Reset to Current" Custom-reset-current t]
21635 ["Reset to Saved" Custom-reset-saved t]
21636 ["Reset to Standard Settings" Custom-reset-standard t]))
21637 (message "\"Org\"-menu now contains full customization menu"))
21638 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21640 ;;;; Miscellaneous stuff
21642 ;;; Generally useful functions
21644 (defun org-get-at-eol (property n)
21645 "Get text property PROPERTY at the end of line less N characters."
21646 (get-text-property (- (point-at-eol) n) property))
21648 (defun org-find-text-property-in-string (prop s)
21649 "Return the first non-nil value of property PROP in string S."
21650 (or (get-text-property 0 prop s)
21651 (get-text-property (or (next-single-property-change 0 prop s) 0)
21652 prop s)))
21654 (defun org-display-warning (message)
21655 "Display the given MESSAGE as a warning."
21656 (display-warning 'org message :warning))
21658 (defun org-eval (form)
21659 "Eval FORM and return result."
21660 (condition-case error
21661 (eval form)
21662 (error (format "%%![Error: %s]" error))))
21664 (defun org-in-clocktable-p ()
21665 "Check if the cursor is in a clocktable."
21666 (let ((pos (point)) start)
21667 (save-excursion
21668 (end-of-line 1)
21669 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21670 (setq start (match-beginning 0))
21671 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21672 (>= (match-end 0) pos)
21673 start))))
21675 (defun org-in-verbatim-emphasis ()
21676 (save-match-data
21677 (and (org-in-regexp org-verbatim-re 2)
21678 (>= (point) (match-beginning 3))
21679 (<= (point) (match-end 4)))))
21681 (defun org-overlay-display (ovl text &optional face evap)
21682 "Make overlay OVL display TEXT with face FACE."
21683 (overlay-put ovl 'display text)
21684 (if face (overlay-put ovl 'face face))
21685 (if evap (overlay-put ovl 'evaporate t)))
21687 (defun org-overlay-before-string (ovl text &optional face evap)
21688 "Make overlay OVL display TEXT with face FACE."
21689 (if face (org-add-props text nil 'face face))
21690 (overlay-put ovl 'before-string text)
21691 (if evap (overlay-put ovl 'evaporate t)))
21693 (defun org-find-overlays (prop &optional pos delete)
21694 "Find all overlays specifying PROP at POS or point.
21695 If DELETE is non-nil, delete all those overlays."
21696 (let (found)
21697 (dolist (ov (overlays-at (or pos (point))) found)
21698 (cond ((not (overlay-get ov prop)))
21699 (delete (delete-overlay ov))
21700 (t (push ov found))))))
21702 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21703 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21704 (if (and marker (marker-buffer marker)
21705 (buffer-live-p (marker-buffer marker)))
21706 (progn
21707 (pop-to-buffer-same-window (marker-buffer marker))
21708 (when (or (> marker (point-max)) (< marker (point-min)))
21709 (widen))
21710 (goto-char marker)
21711 (org-show-context 'org-goto))
21712 (if bookmark
21713 (bookmark-jump bookmark)
21714 (error "Cannot find location"))))
21716 (defun org-quote-csv-field (s)
21717 "Quote field for inclusion in CSV material."
21718 (if (string-match "[\",]" s)
21719 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21722 (defun org-force-self-insert (N)
21723 "Needed to enforce self-insert under remapping."
21724 (interactive "p")
21725 (self-insert-command N))
21727 (defun org-shorten-string (s maxlength)
21728 "Shorten string S so that it is no longer than MAXLENGTH characters.
21729 If the string is shorter or has length MAXLENGTH, just return the
21730 original string. If it is longer, the functions finds a space in the
21731 string, breaks this string off at that locations and adds three dots
21732 as ellipsis. Including the ellipsis, the string will not be longer
21733 than MAXLENGTH. If finding a good breaking point in the string does
21734 not work, the string is just chopped off in the middle of a word
21735 if necessary."
21736 (if (<= (length s) maxlength)
21738 (let* ((n (max (- maxlength 4) 1))
21739 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21740 (if (string-match re s)
21741 (concat (match-string 1 s) "...")
21742 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21744 (defun org-get-indentation (&optional line)
21745 "Get the indentation of the current line, interpreting tabs.
21746 When LINE is given, assume it represents a line and compute its indentation."
21747 (if line
21748 (when (string-match "^ *" (org-remove-tabs line))
21749 (match-end 0))
21750 (save-excursion
21751 (beginning-of-line 1)
21752 (skip-chars-forward " \t")
21753 (current-column))))
21755 (defun org-get-string-indentation (s)
21756 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21757 (let ((n -1) (i 0) (w tab-width) c)
21758 (catch 'exit
21759 (while (< (setq n (1+ n)) (length s))
21760 (setq c (aref s n))
21761 (cond ((= c ?\ ) (setq i (1+ i)))
21762 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21763 (t (throw 'exit t)))))
21766 (defun org-remove-tabs (s &optional width)
21767 "Replace tabulators in S with spaces.
21768 Assumes that s is a single line, starting in column 0."
21769 (setq width (or width tab-width))
21770 (while (string-match "\t" s)
21771 (setq s (replace-match
21772 (make-string
21773 (- (* width (/ (+ (match-beginning 0) width) width))
21774 (match-beginning 0)) ?\ )
21775 t t s)))
21778 (defun org-fix-indentation (line ind)
21779 "Fix indentation in LINE.
21780 IND is a cons cell with target and minimum indentation.
21781 If the current indentation in LINE is smaller than the minimum,
21782 leave it alone. If it is larger than ind, set it to the target."
21783 (let* ((l (org-remove-tabs line))
21784 (i (org-get-indentation l))
21785 (i1 (car ind)) (i2 (cdr ind)))
21786 (when (>= i i2) (setq l (substring line i2)))
21787 (if (> i1 0)
21788 (concat (make-string i1 ?\ ) l)
21789 l)))
21791 (defun org-remove-indentation (code &optional n)
21792 "Remove maximum common indentation in string CODE and return it.
21793 N may optionally be the number of columns to remove. Return CODE
21794 as-is if removal failed."
21795 (with-temp-buffer
21796 (insert code)
21797 (if (org-do-remove-indentation n) (buffer-string) code)))
21799 (defun org-do-remove-indentation (&optional n)
21800 "Remove the maximum common indentation from the buffer.
21801 When optional argument N is a positive integer, remove exactly
21802 that much characters from indentation, if possible. Return nil
21803 if it fails."
21804 (catch :exit
21805 (goto-char (point-min))
21806 ;; Find maximum common indentation, if not specified.
21807 (let ((n (or n
21808 (let ((min-ind (point-max)))
21809 (save-excursion
21810 (while (re-search-forward "^[ \t]*\\S-" nil t)
21811 (let ((ind (1- (current-column))))
21812 (if (zerop ind) (throw :exit nil)
21813 (setq min-ind (min min-ind ind))))))
21814 min-ind))))
21815 (if (zerop n) (throw :exit nil)
21816 ;; Remove exactly N indentation, but give up if not possible.
21817 (while (not (eobp))
21818 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21819 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21820 ((< ind n) (throw :exit nil))
21821 (t (indent-line-to (- ind n))))
21822 (forward-line)))
21823 ;; Signal success.
21824 t))))
21826 (defun org-fill-template (template alist)
21827 "Find each %key of ALIST in TEMPLATE and replace it."
21828 (let ((case-fold-search nil))
21829 (dolist (entry (sort (copy-sequence alist)
21830 (lambda (a b) (< (length (car a)) (length (car b))))))
21831 (setq template
21832 (replace-regexp-in-string
21833 (concat "%" (regexp-quote (car entry)))
21834 (or (cdr entry) "") template t t)))
21835 template))
21837 (defun org-base-buffer (buffer)
21838 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21839 (if (not buffer)
21840 buffer
21841 (or (buffer-base-buffer buffer)
21842 buffer)))
21844 (defun org-wrap (string &optional width lines)
21845 "Wrap string to either a number of lines, or a width in characters.
21846 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21847 that costs. If there is a word longer than WIDTH, the text is actually
21848 wrapped to the length of that word.
21849 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21850 many lines, whatever width that takes.
21851 The return value is a list of lines, without newlines at the end."
21852 (let* ((words (split-string string))
21853 (maxword (apply 'max (mapcar 'org-string-width words)))
21854 w ll)
21855 (cond (width
21856 (org-do-wrap words (max maxword width)))
21857 (lines
21858 (setq w maxword)
21859 (setq ll (org-do-wrap words maxword))
21860 (if (<= (length ll) lines)
21862 (setq ll words)
21863 (while (> (length ll) lines)
21864 (setq w (1+ w))
21865 (setq ll (org-do-wrap words w)))
21866 ll))
21867 (t (error "Cannot wrap this")))))
21869 (defun org-do-wrap (words width)
21870 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21871 (let (lines line)
21872 (while words
21873 (setq line (pop words))
21874 (while (and words (< (+ (length line) (length (car words))) width))
21875 (setq line (concat line " " (pop words))))
21876 (setq lines (push line lines)))
21877 (nreverse lines)))
21879 (defun org-quote-vert (s)
21880 "Replace \"|\" with \"\\vert\"."
21881 (while (string-match "|" s)
21882 (setq s (replace-match "\\vert" t t s)))
21885 (defun org-uuidgen-p (s)
21886 "Is S an ID created by UUIDGEN?"
21887 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21889 (defun org-in-src-block-p (&optional inside)
21890 "Whether point is in a code source block.
21891 When INSIDE is non-nil, don't consider we are within a src block
21892 when point is at #+BEGIN_SRC or #+END_SRC."
21893 (let ((case-fold-search t))
21894 (or (and (eq (get-char-property (point) 'src-block) t))
21895 (and (not inside)
21896 (save-match-data
21897 (save-excursion
21898 (beginning-of-line)
21899 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21901 (defun org-context ()
21902 "Return a list of contexts of the current cursor position.
21903 If several contexts apply, all are returned.
21904 Each context entry is a list with a symbol naming the context, and
21905 two positions indicating start and end of the context. Possible
21906 contexts are:
21908 :headline anywhere in a headline
21909 :headline-stars on the leading stars in a headline
21910 :todo-keyword on a TODO keyword (including DONE) in a headline
21911 :tags on the TAGS in a headline
21912 :priority on the priority cookie in a headline
21913 :item on the first line of a plain list item
21914 :item-bullet on the bullet/number of a plain list item
21915 :checkbox on the checkbox in a plain list item
21916 :table in an Org table
21917 :table-special on a special filed in a table
21918 :table-table in a table.el table
21919 :clocktable in a clocktable
21920 :src-block in a source block
21921 :link on a hyperlink
21922 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21923 :target on a <<target>>
21924 :radio-target on a <<<radio-target>>>
21925 :latex-fragment on a LaTeX fragment
21926 :latex-preview on a LaTeX fragment with overlaid preview image
21928 This function expects the position to be visible because it uses font-lock
21929 faces as a help to recognize the following contexts: :table-special, :link,
21930 and :keyword."
21931 (let* ((f (get-text-property (point) 'face))
21932 (faces (if (listp f) f (list f)))
21933 (case-fold-search t)
21934 (p (point)) clist o)
21935 ;; First the large context
21936 (cond
21937 ((org-at-heading-p t)
21938 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21939 (when (progn
21940 (beginning-of-line 1)
21941 (looking-at org-todo-line-tags-regexp))
21942 (push (org-point-in-group p 1 :headline-stars) clist)
21943 (push (org-point-in-group p 2 :todo-keyword) clist)
21944 (push (org-point-in-group p 4 :tags) clist))
21945 (goto-char p)
21946 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21947 (when (looking-at "\\[#[A-Z0-9]\\]")
21948 (push (org-point-in-group p 0 :priority) clist)))
21950 ((org-at-item-p)
21951 (push (org-point-in-group p 2 :item-bullet) clist)
21952 (push (list :item (point-at-bol)
21953 (save-excursion (org-end-of-item) (point)))
21954 clist)
21955 (and (org-at-item-checkbox-p)
21956 (push (org-point-in-group p 0 :checkbox) clist)))
21958 ((org-at-table-p)
21959 (push (list :table (org-table-begin) (org-table-end)) clist)
21960 (when (memq 'org-formula faces)
21961 (push (list :table-special
21962 (previous-single-property-change p 'face)
21963 (next-single-property-change p 'face)) clist)))
21964 ((org-at-table-p 'any)
21965 (push (list :table-table) clist)))
21966 (goto-char p)
21968 (let ((case-fold-search t))
21969 ;; New the "medium" contexts: clocktables, source blocks
21970 (cond ((org-in-clocktable-p)
21971 (push (list :clocktable
21972 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21973 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21974 (match-beginning 1))
21975 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21976 (match-end 0))) clist))
21977 ((org-in-src-block-p)
21978 (push (list :src-block
21979 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21980 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21981 (match-beginning 1))
21982 (and (search-forward "#+END_SRC" nil t)
21983 (match-beginning 0))) clist))))
21984 (goto-char p)
21986 ;; Now the small context
21987 (cond
21988 ((org-at-timestamp-p)
21989 (push (org-point-in-group p 0 :timestamp) clist))
21990 ((memq 'org-link faces)
21991 (push (list :link
21992 (previous-single-property-change p 'face)
21993 (next-single-property-change p 'face)) clist))
21994 ((memq 'org-special-keyword faces)
21995 (push (list :keyword
21996 (previous-single-property-change p 'face)
21997 (next-single-property-change p 'face)) clist))
21998 ((org-at-target-p)
21999 (push (org-point-in-group p 0 :target) clist)
22000 (goto-char (1- (match-beginning 0)))
22001 (when (looking-at org-radio-target-regexp)
22002 (push (org-point-in-group p 0 :radio-target) clist))
22003 (goto-char p))
22004 ((setq o (cl-some
22005 (lambda (o)
22006 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22008 (overlays-at (point))))
22009 (push (list :latex-fragment
22010 (overlay-start o) (overlay-end o)) clist)
22011 (push (list :latex-preview
22012 (overlay-start o) (overlay-end o)) clist))
22013 ((org-inside-LaTeX-fragment-p)
22014 ;; FIXME: positions wrong.
22015 (push (list :latex-fragment (point) (point)) clist)))
22017 (setq clist (nreverse (delq nil clist)))
22018 clist))
22020 (defun org-in-regexp (regexp &optional nlines visually)
22021 "Check if point is inside a match of REGEXP.
22023 Normally only the current line is checked, but you can include
22024 NLINES extra lines around point into the search. If VISUALLY is
22025 set, require that the cursor is not after the match but really
22026 on, so that the block visually is on the match.
22028 Return nil or a cons cell (BEG . END) where BEG and END are,
22029 respectively, the positions at the beginning and the end of the
22030 match."
22031 (catch :exit
22032 (let ((pos (point))
22033 (eol (line-end-position (if nlines (1+ nlines) 1))))
22034 (save-excursion
22035 (beginning-of-line (- 1 (or nlines 0)))
22036 (while (and (re-search-forward regexp eol t)
22037 (<= (match-beginning 0) pos))
22038 (let ((end (match-end 0)))
22039 (when (or (> end pos) (and (= end pos) (not visually)))
22040 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22042 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22043 "Non-nil when point is between matches of START-RE and END-RE.
22045 Also return a non-nil value when point is on one of the matches.
22047 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22048 buffer positions. Default values are the positions of headlines
22049 surrounding the point.
22051 The functions returns a cons cell whose car (resp. cdr) is the
22052 position before START-RE (resp. after END-RE)."
22053 (save-match-data
22054 (let ((pos (point))
22055 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22056 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22057 beg end)
22058 (save-excursion
22059 ;; Point is on a block when on START-RE or if START-RE can be
22060 ;; found before it...
22061 (and (or (org-in-regexp start-re)
22062 (re-search-backward start-re limit-up t))
22063 (setq beg (match-beginning 0))
22064 ;; ... and END-RE after it...
22065 (goto-char (match-end 0))
22066 (re-search-forward end-re limit-down t)
22067 (> (setq end (match-end 0)) pos)
22068 ;; ... without another START-RE in-between.
22069 (goto-char (match-beginning 0))
22070 (not (re-search-backward start-re (1+ beg) t))
22071 ;; Return value.
22072 (cons beg end))))))
22074 (defun org-in-block-p (names)
22075 "Non-nil when point belongs to a block whose name belongs to NAMES.
22077 NAMES is a list of strings containing names of blocks.
22079 Return first block name matched, or nil. Beware that in case of
22080 nested blocks, the returned name may not belong to the closest
22081 block from point."
22082 (save-match-data
22083 (catch 'exit
22084 (let ((case-fold-search t)
22085 (lim-up (save-excursion (outline-previous-heading)))
22086 (lim-down (save-excursion (outline-next-heading))))
22087 (dolist (name names)
22088 (let ((n (regexp-quote name)))
22089 (when (org-between-regexps-p
22090 (concat "^[ \t]*#\\+begin_" n)
22091 (concat "^[ \t]*#\\+end_" n)
22092 lim-up lim-down)
22093 (throw 'exit n)))))
22094 nil)))
22096 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22097 "Call `multi-occur' with buffers for all agenda files."
22098 (interactive "sOrg-files matching: ")
22099 (let* ((files (org-agenda-files))
22100 (tnames (mapcar #'file-truename files))
22101 (extra org-agenda-text-search-extra-files))
22102 (when (eq (car extra) 'agenda-archives)
22103 (setq extra (cdr extra))
22104 (setq files (org-add-archive-files files)))
22105 (dolist (f extra)
22106 (unless (member (file-truename f) tnames)
22107 (unless (member f files) (setq files (append files (list f))))
22108 (setq tnames (append tnames (list (file-truename f))))))
22109 (multi-occur
22110 (mapcar (lambda (x)
22111 (with-current-buffer
22112 ;; FIXME: Why not just (find-file-noselect x)?
22113 ;; Is it to avoid the "revert buffer" prompt?
22114 (or (get-file-buffer x) (find-file-noselect x))
22115 (widen)
22116 (current-buffer)))
22117 files)
22118 regexp)))
22120 (add-hook 'occur-mode-find-occurrence-hook
22121 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22123 (defun org-occur-link-in-agenda-files ()
22124 "Create a link and search for it in the agendas.
22125 The link is not stored in `org-stored-links', it is just created
22126 for the search purpose."
22127 (interactive)
22128 (let ((link (condition-case nil
22129 (org-store-link nil)
22130 (error "Unable to create a link to here"))))
22131 (org-occur-in-agenda-files (regexp-quote link))))
22133 (defun org-reverse-string (string)
22134 "Return the reverse of STRING."
22135 (apply 'string (reverse (string-to-list string))))
22137 ;; defsubst org-uniquify must be defined before first use
22139 (defun org-uniquify-alist (alist)
22140 "Merge elements of ALIST with the same key.
22142 For example, in this alist:
22144 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22145 => \\='((a 1 3) (b 2))
22147 merge (a 1) and (a 3) into (a 1 3).
22149 The function returns the new ALIST."
22150 (let (rtn)
22151 (dolist (e alist rtn)
22152 (let (n)
22153 (if (not (assoc (car e) rtn))
22154 (push e rtn)
22155 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22156 (setq rtn (assq-delete-all (car e) rtn))
22157 (push n rtn))))))
22159 (defun org-delete-all (elts list)
22160 "Remove all elements in ELTS from LIST.
22161 Comparison is done with `equal'. It is a destructive operation
22162 that may remove elements by altering the list structure."
22163 (while elts
22164 (setq list (delete (pop elts) list)))
22165 list)
22167 (defun org-back-over-empty-lines ()
22168 "Move backwards over whitespace, to the beginning of the first empty line.
22169 Returns the number of empty lines passed."
22170 (let ((pos (point)))
22171 (if (cdr (assq 'heading org-blank-before-new-entry))
22172 (skip-chars-backward " \t\n\r")
22173 (unless (eobp)
22174 (forward-line -1)))
22175 (beginning-of-line 2)
22176 (goto-char (min (point) pos))
22177 (count-lines (point) pos)))
22179 (defun org-skip-whitespace ()
22180 (skip-chars-forward " \t\n\r"))
22182 (defun org-point-in-group (point group &optional context)
22183 "Check if POINT is in match-group GROUP.
22184 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22185 match. If the match group does not exist or point is not inside it,
22186 return nil."
22187 (and (match-beginning group)
22188 (>= point (match-beginning group))
22189 (<= point (match-end group))
22190 (if context
22191 (list context (match-beginning group) (match-end group))
22192 t)))
22194 (defun org-switch-to-buffer-other-window (&rest args)
22195 "Switch to buffer in a second window on the current frame.
22196 In particular, do not allow pop-up frames.
22197 Returns the newly created buffer."
22198 (org-no-popups
22199 (apply 'switch-to-buffer-other-window args)))
22201 (defun org-combine-plists (&rest plists)
22202 "Create a single property list from all plists in PLISTS.
22203 The process starts by copying the first list, and then setting properties
22204 from the other lists. Settings in the last list are the most significant
22205 ones and overrule settings in the other lists."
22206 (let ((rtn (copy-sequence (pop plists)))
22207 p v ls)
22208 (while plists
22209 (setq ls (pop plists))
22210 (while ls
22211 (setq p (pop ls) v (pop ls))
22212 (setq rtn (plist-put rtn p v))))
22213 rtn))
22215 (defun org-replace-escapes (string table)
22216 "Replace %-escapes in STRING with values in TABLE.
22217 TABLE is an association list with keys like \"%a\" and string values.
22218 The sequences in STRING may contain normal field width and padding information,
22219 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22220 so values can contain further %-escapes if they are define later in TABLE."
22221 (let ((tbl (copy-alist table))
22222 (case-fold-search nil)
22223 (pchg 0)
22224 re rpl)
22225 (dolist (e tbl)
22226 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22227 (when (and (cdr e) (string-match re (cdr e)))
22228 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22229 (safe "SREF"))
22230 (add-text-properties 0 3 (list 'sref sref) safe)
22231 (setcdr e (replace-match safe t t (cdr e)))))
22232 (while (string-match re string)
22233 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22234 (cdr e)))
22235 (setq string (replace-match rpl t t string))))
22236 (while (setq pchg (next-property-change pchg string))
22237 (let ((sref (get-text-property pchg 'sref string)))
22238 (when (and sref (string-match "SREF" string pchg))
22239 (setq string (replace-match sref t t string)))))
22240 string))
22242 (defun org-find-base-buffer-visiting (file)
22243 "Like `find-buffer-visiting' but always return the base buffer and
22244 not an indirect buffer."
22245 (let ((buf (or (get-file-buffer file)
22246 (find-buffer-visiting file))))
22247 (if buf
22248 (or (buffer-base-buffer buf) buf)
22249 nil)))
22251 ;;; TODO: Only called once, from ox-odt which should probably use
22252 ;;; org-export-inline-image-p or something.
22253 (defun org-file-image-p (file)
22254 "Return non-nil if FILE is an image."
22255 (save-match-data
22256 (string-match (image-file-name-regexp) file)))
22258 (defun org-get-cursor-date (&optional with-time)
22259 "Return the date at cursor in as a time.
22260 This works in the calendar and in the agenda, anywhere else it just
22261 returns the current time.
22262 If WITH-TIME is non-nil, returns the time of the event at point (in
22263 the agenda) or the current time of the day."
22264 (let (date day defd tp hod mod)
22265 (when with-time
22266 (setq tp (get-text-property (point) 'time))
22267 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22268 (setq hod (string-to-number (match-string 1 tp))
22269 mod (string-to-number (match-string 2 tp))))
22270 (or tp (let ((now (decode-time)))
22271 (setq hod (nth 2 now)
22272 mod (nth 1 now)))))
22273 (cond
22274 ((eq major-mode 'calendar-mode)
22275 (setq date (calendar-cursor-to-date)
22276 defd (encode-time 0 (or mod 0) (or hod 0)
22277 (nth 1 date) (nth 0 date) (nth 2 date))))
22278 ((eq major-mode 'org-agenda-mode)
22279 (setq day (get-text-property (point) 'day))
22280 (when day
22281 (setq date (calendar-gregorian-from-absolute day)
22282 defd (encode-time 0 (or mod 0) (or hod 0)
22283 (nth 1 date) (nth 0 date) (nth 2 date))))))
22284 (or defd (current-time))))
22286 (defun org-mark-subtree (&optional up)
22287 "Mark the current subtree.
22288 This puts point at the start of the current subtree, and mark at
22289 the end. If a numeric prefix UP is given, move up into the
22290 hierarchy of headlines by UP levels before marking the subtree."
22291 (interactive "P")
22292 (org-with-limited-levels
22293 (cond ((org-at-heading-p) (beginning-of-line))
22294 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22295 (t (outline-previous-visible-heading 1))))
22296 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22297 (if (called-interactively-p 'any)
22298 (call-interactively 'org-mark-element)
22299 (org-mark-element)))
22301 (defun org-file-newer-than-p (file time)
22302 "Non-nil if FILE is newer than TIME.
22303 FILE is a filename, as a string, TIME is a list of integers, as
22304 returned by, e.g., `current-time'."
22305 (and (file-exists-p file)
22306 ;; Only compare times up to whole seconds as some file-systems
22307 ;; (e.g. HFS+) do not retain any finer granularity. As
22308 ;; a consequence, make sure we return non-nil when the two
22309 ;; times are equal.
22310 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22311 (cl-subseq time 0 2)))))
22313 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22314 "Compile a SOURCE file using PROCESS.
22316 PROCESS is either a function or a list of shell commands, as
22317 strings. EXT is a file extension, without the leading dot, as
22318 a string. It is used to check if the process actually succeeded.
22320 PROCESS must create a file with the same base name and directory
22321 as SOURCE, but ending with EXT. The function then returns its
22322 filename. Otherwise, it raises an error. The error message can
22323 then be refined by providing string ERR-MSG, which is appended to
22324 the standard message.
22326 If PROCESS is a function, it is called with a single argument:
22327 the SOURCE file.
22329 If it is a list of commands, each of them is called using
22330 `shell-command'. By default, in each command, %b, %f, %F, %o and
22331 %O are replaced with, respectively, SOURCE base name, name, full
22332 name, directory and absolute output file name. It is possible,
22333 however, to use more place-holders by specifying them in optional
22334 argument SPEC, as an alist following the pattern
22336 (CHARACTER . REPLACEMENT-STRING).
22338 When PROCESS is a list of commands, optional argument LOG-BUF can
22339 be set to a buffer or a buffer name. `shell-command' then uses
22340 it for output."
22341 (let* ((base-name (file-name-base source))
22342 (full-name (file-truename source))
22343 (out-dir (or (file-name-directory source) "./"))
22344 (output (expand-file-name (concat base-name "." ext) out-dir))
22345 (time (current-time))
22346 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22347 (save-window-excursion
22348 (pcase process
22349 ((pred functionp) (funcall process (shell-quote-argument source)))
22350 ((pred consp)
22351 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22352 (spec (append spec
22353 `((?b . ,(shell-quote-argument base-name))
22354 (?f . ,(shell-quote-argument source))
22355 (?F . ,(shell-quote-argument full-name))
22356 (?o . ,(shell-quote-argument out-dir))
22357 (?O . ,(shell-quote-argument output))))))
22358 (dolist (command process)
22359 (shell-command (format-spec command spec) log-buf))
22360 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22361 (_ (error "No valid command to process %S%s" source err-msg))))
22362 ;; Check for process failure. Output file is expected to be
22363 ;; located in the same directory as SOURCE.
22364 (unless (org-file-newer-than-p output time)
22365 (error (format "File %S wasn't produced%s" output err-msg)))
22366 output))
22368 ;;; Indentation
22370 (defvar org-element-greater-elements)
22371 (defun org--get-expected-indentation (element contentsp)
22372 "Expected indentation column for current line, according to ELEMENT.
22373 ELEMENT is an element containing point. CONTENTSP is non-nil
22374 when indentation is to be computed according to contents of
22375 ELEMENT."
22376 (let ((type (org-element-type element))
22377 (start (org-element-property :begin element))
22378 (post-affiliated (org-element-property :post-affiliated element)))
22379 (org-with-wide-buffer
22380 (cond
22381 (contentsp
22382 (cl-case type
22383 ((diary-sexp footnote-definition) 0)
22384 ((headline inlinetask nil)
22385 (if (not org-adapt-indentation) 0
22386 (let ((level (org-current-level)))
22387 (if level (1+ level) 0))))
22388 ((item plain-list) (org-list-item-body-column post-affiliated))
22390 (goto-char start)
22391 (org-get-indentation))))
22392 ((memq type '(headline inlinetask nil))
22393 (if (org-match-line "[ \t]*$")
22394 (org--get-expected-indentation element t)
22396 ((memq type '(diary-sexp footnote-definition)) 0)
22397 ;; First paragraph of a footnote definition or an item.
22398 ;; Indent like parent.
22399 ((< (line-beginning-position) start)
22400 (org--get-expected-indentation
22401 (org-element-property :parent element) t))
22402 ;; At first line: indent according to previous sibling, if any,
22403 ;; ignoring footnote definitions and inline tasks, or parent's
22404 ;; contents.
22405 ((= (line-beginning-position) start)
22406 (catch 'exit
22407 (while t
22408 (if (= (point-min) start) (throw 'exit 0)
22409 (goto-char (1- start))
22410 (let* ((previous (org-element-at-point))
22411 (parent previous))
22412 (while (and parent (<= (org-element-property :end parent) start))
22413 (setq previous parent
22414 parent (org-element-property :parent parent)))
22415 (cond
22416 ((not previous) (throw 'exit 0))
22417 ((> (org-element-property :end previous) start)
22418 (throw 'exit (org--get-expected-indentation previous t)))
22419 ((memq (org-element-type previous)
22420 '(footnote-definition inlinetask))
22421 (setq start (org-element-property :begin previous)))
22422 (t (goto-char (org-element-property :begin previous))
22423 (throw 'exit
22424 (if (bolp) (org-get-indentation)
22425 ;; At first paragraph in an item or
22426 ;; a footnote definition.
22427 (org--get-expected-indentation
22428 (org-element-property :parent previous) t))))))))))
22429 ;; Otherwise, move to the first non-blank line above.
22431 (beginning-of-line)
22432 (let ((pos (point)))
22433 (skip-chars-backward " \r\t\n")
22434 (cond
22435 ;; Two blank lines end a footnote definition or a plain
22436 ;; list. When we indent an empty line after them, the
22437 ;; containing list or footnote definition is over, so it
22438 ;; qualifies as a previous sibling. Therefore, we indent
22439 ;; like its first line.
22440 ((and (memq type '(footnote-definition plain-list))
22441 (> (count-lines (point) pos) 2))
22442 (goto-char start)
22443 (org-get-indentation))
22444 ;; Line above is the first one of a paragraph at the
22445 ;; beginning of an item or a footnote definition. Indent
22446 ;; like parent.
22447 ((< (line-beginning-position) start)
22448 (org--get-expected-indentation
22449 (org-element-property :parent element) t))
22450 ;; Line above is the beginning of an element, i.e., point
22451 ;; was originally on the blank lines between element's start
22452 ;; and contents.
22453 ((= (line-beginning-position) post-affiliated)
22454 (org--get-expected-indentation element t))
22455 ;; POS is after contents in a greater element. Indent like
22456 ;; the beginning of the element.
22457 ((and (memq type org-element-greater-elements)
22458 (let ((cend (org-element-property :contents-end element)))
22459 (and cend (<= cend pos))))
22460 ;; As a special case, if point is at the end of a footnote
22461 ;; definition or an item, indent like the very last element
22462 ;; within. If that last element is an item, indent like
22463 ;; its contents.
22464 (if (memq type '(footnote-definition item plain-list))
22465 (let ((last (org-element-at-point)))
22466 (goto-char pos)
22467 (org--get-expected-indentation
22468 last (eq (org-element-type last) 'item)))
22469 (goto-char start)
22470 (org-get-indentation)))
22471 ;; In any other case, indent like the current line.
22472 (t (org-get-indentation)))))))))
22474 (defun org--align-node-property ()
22475 "Align node property at point.
22476 Alignment is done according to `org-property-format', which see."
22477 (when (save-excursion
22478 (beginning-of-line)
22479 (looking-at org-property-re))
22480 (replace-match
22481 (concat (match-string 4)
22482 (org-trim
22483 (format org-property-format (match-string 1) (match-string 3))))
22484 t t)))
22486 (defun org-indent-line ()
22487 "Indent line depending on context.
22489 Indentation is done according to the following rules:
22491 - Footnote definitions, diary sexps, headlines and inline tasks
22492 have to start at column 0.
22494 - On the very first line of an element, consider, in order, the
22495 next rules until one matches:
22497 1. If there's a sibling element before, ignoring footnote
22498 definitions and inline tasks, indent like its first line.
22500 2. If element has a parent, indent like its contents. More
22501 precisely, if parent is an item, indent after the
22502 description part, if any, or the bullet (see
22503 `org-list-description-max-indent'). Else, indent like
22504 parent's first line.
22506 3. Otherwise, indent relatively to current level, if
22507 `org-adapt-indentation' is non-nil, or to left margin.
22509 - On a blank line at the end of an element, indent according to
22510 the type of the element. More precisely
22512 1. If element is a plain list, an item, or a footnote
22513 definition, indent like the very last element within.
22515 2. If element is a paragraph, indent like its last non blank
22516 line.
22518 3. Otherwise, indent like its very first line.
22520 - In the code part of a source block, use language major mode
22521 to indent current line if `org-src-tab-acts-natively' is
22522 non-nil. If it is nil, do nothing.
22524 - Otherwise, indent like the first non-blank line above.
22526 The function doesn't indent an item as it could break the whole
22527 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22528 `\\[org-shiftmetaright]'.
22530 Also align node properties according to `org-property-format'."
22531 (interactive)
22532 (cond
22533 (orgstruct-is-++
22534 (let ((indent-line-function
22535 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22536 (indent-according-to-mode)))
22537 ((org-at-heading-p) 'noindent)
22539 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22540 (type (org-element-type element)))
22541 (cond ((and (memq type '(plain-list item))
22542 (= (line-beginning-position)
22543 (org-element-property :post-affiliated element)))
22544 'noindent)
22545 ((and (eq type 'latex-environment)
22546 (>= (point) (org-element-property :post-affiliated element))
22547 (< (point) (org-with-wide-buffer
22548 (goto-char (org-element-property :end element))
22549 (skip-chars-backward " \r\t\n")
22550 (line-beginning-position 2))))
22551 'noindent)
22552 ((and (eq type 'src-block)
22553 org-src-tab-acts-natively
22554 (> (line-beginning-position)
22555 (org-element-property :post-affiliated element))
22556 (< (line-beginning-position)
22557 (org-with-wide-buffer
22558 (goto-char (org-element-property :end element))
22559 (skip-chars-backward " \r\t\n")
22560 (line-beginning-position))))
22561 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22563 (let ((column (org--get-expected-indentation element nil)))
22564 ;; Preserve current column.
22565 (if (<= (current-column) (current-indentation))
22566 (indent-line-to column)
22567 (save-excursion (indent-line-to column))))
22568 ;; Align node property. Also preserve current column.
22569 (when (eq type 'node-property)
22570 (let ((column (current-column)))
22571 (org--align-node-property)
22572 (org-move-to-column column)))))))))
22574 (defun org-indent-region (start end)
22575 "Indent each non-blank line in the region.
22576 Called from a program, START and END specify the region to
22577 indent. The function will not indent contents of example blocks,
22578 verse blocks and export blocks as leading white spaces are
22579 assumed to be significant there."
22580 (interactive "r")
22581 (save-excursion
22582 (goto-char start)
22583 (skip-chars-forward " \r\t\n")
22584 (unless (eobp) (beginning-of-line))
22585 (let ((indent-to
22586 (lambda (ind pos)
22587 ;; Set IND as indentation for all lines between point and
22588 ;; POS. Blank lines are ignored. Leave point after POS
22589 ;; once done.
22590 (let ((limit (copy-marker pos)))
22591 (while (< (point) limit)
22592 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22593 (forward-line))
22594 (set-marker limit nil))))
22595 (end (copy-marker end)))
22596 (while (< (point) end)
22597 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22598 (let* ((element (org-element-at-point))
22599 (type (org-element-type element))
22600 (element-end (copy-marker (org-element-property :end element)))
22601 (ind (org--get-expected-indentation element nil)))
22602 (cond
22603 ;; Element indented as a single block. Example blocks
22604 ;; preserving indentation are a special case since the
22605 ;; "contents" must not be indented whereas the block
22606 ;; boundaries can.
22607 ((or (memq type '(export-block latex-environment))
22608 (and (eq type 'example-block)
22609 (not
22610 (or org-src-preserve-indentation
22611 (org-element-property :preserve-indent element)))))
22612 (let ((offset (- ind (org-get-indentation))))
22613 (unless (zerop offset)
22614 (indent-rigidly (org-element-property :begin element)
22615 (org-element-property :end element)
22616 offset)))
22617 (goto-char element-end))
22618 ;; Elements indented line wise. Be sure to exclude
22619 ;; example blocks (preserving indentation) and source
22620 ;; blocks from this category as they are treated
22621 ;; specially later.
22622 ((or (memq type '(paragraph table table-row))
22623 (not (or (org-element-property :contents-begin element)
22624 (memq type '(example-block src-block)))))
22625 (when (eq type 'node-property)
22626 (org--align-node-property)
22627 (beginning-of-line))
22628 (funcall indent-to ind (min element-end end)))
22629 ;; Elements consisting of three parts: before the
22630 ;; contents, the contents, and after the contents. The
22631 ;; contents are treated specially, according to the
22632 ;; element type, or not indented at all. Other parts are
22633 ;; indented as a single block.
22635 (let* ((post (copy-marker
22636 (org-element-property :post-affiliated element)))
22637 (cbeg
22638 (copy-marker
22639 (cond
22640 ((not (org-element-property :contents-begin element))
22641 ;; Fake contents for source blocks.
22642 (org-with-wide-buffer
22643 (goto-char post)
22644 (line-beginning-position 2)))
22645 ((memq type '(footnote-definition item plain-list))
22646 ;; Contents in these elements could start on
22647 ;; the same line as the beginning of the
22648 ;; element. Make sure we start indenting
22649 ;; from the second line.
22650 (org-with-wide-buffer
22651 (goto-char post)
22652 (end-of-line)
22653 (skip-chars-forward " \r\t\n")
22654 (if (eobp) (point) (line-beginning-position))))
22655 (t (org-element-property :contents-begin element)))))
22656 (cend (copy-marker
22657 (or (org-element-property :contents-end element)
22658 ;; Fake contents for source blocks.
22659 (org-with-wide-buffer
22660 (goto-char element-end)
22661 (skip-chars-backward " \r\t\n")
22662 (line-beginning-position)))
22663 t)))
22664 ;; Do not change items indentation individually as it
22665 ;; might break the list as a whole. On the other
22666 ;; hand, when at a plain list, indent it as a whole.
22667 (cond ((eq type 'plain-list)
22668 (let ((offset (- ind (org-get-indentation))))
22669 (unless (zerop offset)
22670 (indent-rigidly (org-element-property :begin element)
22671 (org-element-property :end element)
22672 offset))
22673 (goto-char cbeg)))
22674 ((eq type 'item) (goto-char cbeg))
22675 (t (funcall indent-to ind (min cbeg end))))
22676 (when (< (point) end)
22677 (cl-case type
22678 ((example-block verse-block))
22679 (src-block
22680 ;; In a source block, indent source code
22681 ;; according to language major mode, but only if
22682 ;; `org-src-tab-acts-natively' is non-nil.
22683 (when (and (< (point) end) org-src-tab-acts-natively)
22684 (ignore-errors
22685 (org-babel-do-in-edit-buffer
22686 (indent-region (point-min) (point-max))))))
22687 (t (org-indent-region (point) (min cend end))))
22688 (goto-char (min cend end))
22689 (when (< (point) end)
22690 (funcall indent-to ind (min element-end end))))
22691 (set-marker post nil)
22692 (set-marker cbeg nil)
22693 (set-marker cend nil))))
22694 (set-marker element-end nil))))
22695 (set-marker end nil))))
22697 (defun org-indent-drawer ()
22698 "Indent the drawer at point."
22699 (interactive)
22700 (unless (save-excursion
22701 (beginning-of-line)
22702 (looking-at-p org-drawer-regexp))
22703 (user-error "Not at a drawer"))
22704 (let ((element (org-element-at-point)))
22705 (unless (memq (org-element-type element) '(drawer property-drawer))
22706 (user-error "Not at a drawer"))
22707 (org-with-wide-buffer
22708 (org-indent-region (org-element-property :begin element)
22709 (org-element-property :end element))))
22710 (message "Drawer at point indented"))
22712 (defun org-indent-block ()
22713 "Indent the block at point."
22714 (interactive)
22715 (unless (save-excursion
22716 (beginning-of-line)
22717 (let ((case-fold-search t))
22718 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22719 (user-error "Not at a block"))
22720 (let ((element (org-element-at-point)))
22721 (unless (memq (org-element-type element)
22722 '(comment-block center-block dynamic-block example-block
22723 export-block quote-block special-block
22724 src-block verse-block))
22725 (user-error "Not at a block"))
22726 (org-with-wide-buffer
22727 (org-indent-region (org-element-property :begin element)
22728 (org-element-property :end element))))
22729 (message "Block at point indented"))
22732 ;;; Filling
22734 ;; We use our own fill-paragraph and auto-fill functions.
22736 ;; `org-fill-paragraph' relies on adaptive filling and context
22737 ;; checking. Appropriate `fill-prefix' is computed with
22738 ;; `org-adaptive-fill-function'.
22740 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22741 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22742 ;; `org-adaptive-fill-function' value. Internally,
22743 ;; `org-comment-line-break-function' breaks the line.
22745 ;; `org-setup-filling' installs filling and auto-filling related
22746 ;; variables during `org-mode' initialization.
22748 (defvar org-element-paragraph-separate) ; org-element.el
22749 (defun org-setup-filling ()
22750 (require 'org-element)
22751 ;; Prevent auto-fill from inserting unwanted new items.
22752 (when (boundp 'fill-nobreak-predicate)
22753 (setq-local
22754 fill-nobreak-predicate
22755 (org-uniquify
22756 (append fill-nobreak-predicate
22757 '(org-fill-line-break-nobreak-p
22758 org-fill-n-macro-as-item-nobreak-p
22759 org-fill-paragraph-with-timestamp-nobreak-p)))))
22760 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22761 (setq-local paragraph-start paragraph-ending)
22762 (setq-local paragraph-separate paragraph-ending))
22763 (setq-local fill-paragraph-function 'org-fill-paragraph)
22764 (setq-local auto-fill-inhibit-regexp nil)
22765 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22766 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22767 (setq-local comment-line-break-function 'org-comment-line-break-function))
22769 (defun org-fill-line-break-nobreak-p ()
22770 "Non-nil when a new line at point would create an Org line break."
22771 (save-excursion
22772 (skip-chars-backward "[ \t]")
22773 (skip-chars-backward "\\\\")
22774 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22776 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22777 "Non-nil when a new line at point would split a timestamp."
22778 (and (org-at-timestamp-p 'lax)
22779 (not (looking-at org-ts-regexp-both))))
22781 (defun org-fill-n-macro-as-item-nobreak-p ()
22782 "Non-nil when a new line at point would create a new list."
22783 ;; During export, a "n" macro followed by a dot or a closing
22784 ;; parenthesis can end up being parsed as a new list item.
22785 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22787 (declare-function message-in-body-p "message" ())
22788 (defvar orgtbl-line-start-regexp) ; From org-table.el
22789 (defun org-adaptive-fill-function ()
22790 "Compute a fill prefix for the current line.
22791 Return fill prefix, as a string, or nil if current line isn't
22792 meant to be filled. For convenience, if `adaptive-fill-regexp'
22793 matches in paragraphs or comments, use it."
22794 (catch 'exit
22795 (when (derived-mode-p 'message-mode)
22796 (save-excursion
22797 (beginning-of-line)
22798 (cond ((not (message-in-body-p)) (throw 'exit nil))
22799 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22800 ((looking-at message-cite-prefix-regexp)
22801 (throw 'exit (match-string-no-properties 0)))
22802 ((looking-at org-outline-regexp)
22803 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22804 (org-with-wide-buffer
22805 (unless (org-at-heading-p)
22806 (let* ((p (line-beginning-position))
22807 (element (save-excursion
22808 (beginning-of-line)
22809 (org-element-at-point)))
22810 (type (org-element-type element))
22811 (post-affiliated (org-element-property :post-affiliated element)))
22812 (unless (< p post-affiliated)
22813 (cl-case type
22814 (comment
22815 (save-excursion
22816 (beginning-of-line)
22817 (looking-at "[ \t]*")
22818 (concat (match-string 0) "# ")))
22819 (footnote-definition "")
22820 ((item plain-list)
22821 (make-string (org-list-item-body-column post-affiliated) ?\s))
22822 (paragraph
22823 ;; Fill prefix is usually the same as the current line,
22824 ;; unless the paragraph is at the beginning of an item.
22825 (let ((parent (org-element-property :parent element)))
22826 (save-excursion
22827 (beginning-of-line)
22828 (cond ((eq (org-element-type parent) 'item)
22829 (make-string (org-list-item-body-column
22830 (org-element-property :begin parent))
22831 ?\s))
22832 ((and adaptive-fill-regexp
22833 ;; Locally disable
22834 ;; `adaptive-fill-function' to let
22835 ;; `fill-context-prefix' handle
22836 ;; `adaptive-fill-regexp' variable.
22837 (let (adaptive-fill-function)
22838 (fill-context-prefix
22839 post-affiliated
22840 (org-element-property :end element)))))
22841 ((looking-at "[ \t]+") (match-string 0))
22842 (t "")))))
22843 (comment-block
22844 ;; Only fill contents if P is within block boundaries.
22845 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22846 (forward-line)
22847 (point)))
22848 (cend (save-excursion
22849 (goto-char (org-element-property :end element))
22850 (skip-chars-backward " \r\t\n")
22851 (line-beginning-position))))
22852 (when (and (>= p cbeg) (< p cend))
22853 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22854 (match-string 0)
22855 "")))))))))))
22857 (declare-function message-goto-body "message" ())
22858 (defvar message-cite-prefix-regexp) ; From message.el
22860 (defun org-fill-element (&optional justify)
22861 "Fill element at point, when applicable.
22863 This function only applies to comment blocks, comments, example
22864 blocks and paragraphs. Also, as a special case, re-align table
22865 when point is at one.
22867 If JUSTIFY is non-nil (interactively, with prefix argument),
22868 justify as well. If `sentence-end-double-space' is non-nil, then
22869 period followed by one space does not end a sentence, so don't
22870 break a line there. The variable `fill-column' controls the
22871 width for filling.
22873 For convenience, when point is at a plain list, an item or
22874 a footnote definition, try to fill the first paragraph within."
22875 (with-syntax-table org-mode-transpose-word-syntax-table
22876 ;; Move to end of line in order to get the first paragraph within
22877 ;; a plain list or a footnote definition.
22878 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22879 ;; First check if point is in a blank line at the beginning of
22880 ;; the buffer. In that case, ignore filling.
22881 (cl-case (org-element-type element)
22882 ;; Use major mode filling function is src blocks.
22883 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22884 ;; Align Org tables, leave table.el tables as-is.
22885 (table-row (org-table-align) t)
22886 (table
22887 (when (eq (org-element-property :type element) 'org)
22888 (save-excursion
22889 (goto-char (org-element-property :post-affiliated element))
22890 (org-table-align)))
22892 (paragraph
22893 ;; Paragraphs may contain `line-break' type objects.
22894 (let ((beg (max (point-min)
22895 (org-element-property :contents-begin element)))
22896 (end (min (point-max)
22897 (org-element-property :contents-end element))))
22898 ;; Do nothing if point is at an affiliated keyword.
22899 (if (< (line-end-position) beg) t
22900 (when (derived-mode-p 'message-mode)
22901 ;; In `message-mode', do not fill following citation
22902 ;; in current paragraph nor text before message body.
22903 (let ((body-start (save-excursion (message-goto-body))))
22904 (when body-start (setq beg (max body-start beg))))
22905 (when (save-excursion
22906 (re-search-forward
22907 (concat "^" message-cite-prefix-regexp) end t))
22908 (setq end (match-beginning 0))))
22909 ;; Fill paragraph, taking line breaks into account.
22910 (save-excursion
22911 (goto-char beg)
22912 (let ((cuts (list beg)))
22913 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22914 (when (eq 'line-break
22915 (org-element-type
22916 (save-excursion (backward-char)
22917 (org-element-context))))
22918 (push (point) cuts)))
22919 (dolist (c (delq end cuts))
22920 (fill-region-as-paragraph c end justify)
22921 (setq end c))))
22922 t)))
22923 ;; Contents of `comment-block' type elements should be
22924 ;; filled as plain text, but only if point is within block
22925 ;; markers.
22926 (comment-block
22927 (let* ((case-fold-search t)
22928 (beg (save-excursion
22929 (goto-char (org-element-property :begin element))
22930 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22931 (forward-line)
22932 (point)))
22933 (end (save-excursion
22934 (goto-char (org-element-property :end element))
22935 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22936 (line-beginning-position))))
22937 (if (or (< (point) beg) (> (point) end)) t
22938 (fill-region-as-paragraph
22939 (save-excursion (end-of-line)
22940 (re-search-backward "^[ \t]*$" beg 'move)
22941 (line-beginning-position))
22942 (save-excursion (beginning-of-line)
22943 (re-search-forward "^[ \t]*$" end 'move)
22944 (line-beginning-position))
22945 justify))))
22946 ;; Fill comments.
22947 (comment
22948 (let ((begin (org-element-property :post-affiliated element))
22949 (end (org-element-property :end element)))
22950 (when (and (>= (point) begin) (<= (point) end))
22951 (let ((begin (save-excursion
22952 (end-of-line)
22953 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22954 (progn (forward-line) (point))
22955 begin)))
22956 (end (save-excursion
22957 (end-of-line)
22958 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22959 (1- (line-beginning-position))
22960 (skip-chars-backward " \r\t\n")
22961 (line-end-position)))))
22962 ;; Do not fill comments when at a blank line.
22963 (when (> end begin)
22964 (let ((fill-prefix
22965 (save-excursion
22966 (beginning-of-line)
22967 (looking-at "[ \t]*#")
22968 (let ((comment-prefix (match-string 0)))
22969 (goto-char (match-end 0))
22970 (if (looking-at adaptive-fill-regexp)
22971 (concat comment-prefix (match-string 0))
22972 (concat comment-prefix " "))))))
22973 (save-excursion
22974 (fill-region-as-paragraph begin end justify))))))
22976 ;; Ignore every other element.
22977 (otherwise t)))))
22979 (defun org-fill-paragraph (&optional justify region)
22980 "Fill element at point, when applicable.
22982 This function only applies to comment blocks, comments, example
22983 blocks and paragraphs. Also, as a special case, re-align table
22984 when point is at one.
22986 For convenience, when point is at a plain list, an item or
22987 a footnote definition, try to fill the first paragraph within.
22989 If JUSTIFY is non-nil (interactively, with prefix argument),
22990 justify as well. If `sentence-end-double-space' is non-nil, then
22991 period followed by one space does not end a sentence, so don't
22992 break a line there. The variable `fill-column' controls the
22993 width for filling.
22995 The REGION argument is non-nil if called interactively; in that
22996 case, if Transient Mark mode is enabled and the mark is active,
22997 fill each of the elements in the active region, instead of just
22998 filling the current element."
22999 (interactive (progn
23000 (barf-if-buffer-read-only)
23001 (list (if current-prefix-arg 'full) t)))
23002 (cond
23003 ((and (derived-mode-p 'message-mode)
23004 (or (not (message-in-body-p))
23005 (save-excursion (move-beginning-of-line 1)
23006 (looking-at message-cite-prefix-regexp))))
23007 ;; First ensure filling is correct in message-mode.
23008 (let ((fill-paragraph-function
23009 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23010 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23011 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23012 (paragraph-separate
23013 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23014 (fill-paragraph nil)))
23015 ((and region transient-mark-mode mark-active
23016 (not (eq (region-beginning) (region-end))))
23017 (let ((origin (point-marker))
23018 (start (region-beginning)))
23019 (unwind-protect
23020 (progn
23021 (goto-char (region-end))
23022 (while (> (point) start)
23023 (org-backward-paragraph)
23024 (org-fill-element justify)))
23025 (goto-char origin)
23026 (set-marker origin nil))))
23027 (t (org-fill-element justify))))
23028 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23030 (defun org-auto-fill-function ()
23031 "Auto-fill function."
23032 ;; Check if auto-filling is meaningful.
23033 (let ((fc (current-fill-column)))
23034 (when (and fc (> (current-column) fc))
23035 (let* ((fill-prefix (org-adaptive-fill-function))
23036 ;; Enforce empty fill prefix, if required. Otherwise, it
23037 ;; will be computed again.
23038 (adaptive-fill-mode (not (equal fill-prefix ""))))
23039 (when fill-prefix (do-auto-fill))))))
23041 (defun org-comment-line-break-function (&optional soft)
23042 "Break line at point and indent, continuing comment if within one.
23043 The inserted newline is marked hard if variable
23044 `use-hard-newlines' is true, unless optional argument SOFT is
23045 non-nil."
23046 (if soft (insert-and-inherit ?\n) (newline 1))
23047 (save-excursion (forward-char -1) (delete-horizontal-space))
23048 (delete-horizontal-space)
23049 (indent-to-left-margin)
23050 (insert-before-markers-and-inherit fill-prefix))
23053 ;;; Fixed Width Areas
23055 (defun org-toggle-fixed-width ()
23056 "Toggle fixed-width markup.
23058 Add or remove fixed-width markup on current line, whenever it
23059 makes sense. Return an error otherwise.
23061 If a region is active and if it contains only fixed-width areas
23062 or blank lines, remove all fixed-width markup in it. If the
23063 region contains anything else, convert all non-fixed-width lines
23064 to fixed-width ones.
23066 Blank lines at the end of the region are ignored unless the
23067 region only contains such lines."
23068 (interactive)
23069 (if (not (org-region-active-p))
23070 ;; No region:
23072 ;; Remove fixed width marker only in a fixed-with element.
23074 ;; Add fixed width maker in paragraphs, in blank lines after
23075 ;; elements or at the beginning of a headline or an inlinetask,
23076 ;; and before any one-line elements (e.g., a clock).
23077 (progn
23078 (beginning-of-line)
23079 (let* ((element (org-element-at-point))
23080 (type (org-element-type element)))
23081 (cond
23082 ((and (eq type 'fixed-width)
23083 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23084 (replace-match
23085 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23086 ((and (memq type '(babel-call clock comment diary-sexp headline
23087 horizontal-rule keyword paragraph
23088 planning))
23089 (<= (org-element-property :post-affiliated element) (point)))
23090 (skip-chars-forward " \t")
23091 (insert ": "))
23092 ((and (looking-at-p "[ \t]*$")
23093 (or (eq type 'inlinetask)
23094 (save-excursion
23095 (skip-chars-forward " \r\t\n")
23096 (<= (org-element-property :end element) (point)))))
23097 (delete-region (point) (line-end-position))
23098 (org-indent-line)
23099 (insert ": "))
23100 (t (user-error "Cannot insert a fixed-width line here")))))
23101 ;; Region active.
23102 (let* ((begin (save-excursion
23103 (goto-char (region-beginning))
23104 (line-beginning-position)))
23105 (end (copy-marker
23106 (save-excursion
23107 (goto-char (region-end))
23108 (unless (eolp) (beginning-of-line))
23109 (if (save-excursion (re-search-backward "\\S-" begin t))
23110 (progn (skip-chars-backward " \r\t\n") (point))
23111 (point)))))
23112 (all-fixed-width-p
23113 (catch 'not-all-p
23114 (save-excursion
23115 (goto-char begin)
23116 (skip-chars-forward " \r\t\n")
23117 (when (eobp) (throw 'not-all-p nil))
23118 (while (< (point) end)
23119 (let ((element (org-element-at-point)))
23120 (if (eq (org-element-type element) 'fixed-width)
23121 (goto-char (org-element-property :end element))
23122 (throw 'not-all-p nil))))
23123 t))))
23124 (if all-fixed-width-p
23125 (save-excursion
23126 (goto-char begin)
23127 (while (< (point) end)
23128 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23129 (replace-match
23130 "" nil nil nil
23131 (if (= (line-end-position) (match-end 0)) 0 1)))
23132 (forward-line)))
23133 (let ((min-ind (point-max)))
23134 ;; Find minimum indentation across all lines.
23135 (save-excursion
23136 (goto-char begin)
23137 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23138 (setq min-ind 0)
23139 (catch 'zerop
23140 (while (< (point) end)
23141 (unless (looking-at-p "[ \t]*$")
23142 (let ((ind (org-get-indentation)))
23143 (setq min-ind (min min-ind ind))
23144 (when (zerop ind) (throw 'zerop t))))
23145 (forward-line)))))
23146 ;; Loop over all lines and add fixed-width markup everywhere
23147 ;; but in fixed-width lines.
23148 (save-excursion
23149 (goto-char begin)
23150 (while (< (point) end)
23151 (cond
23152 ((org-at-heading-p)
23153 (insert ": ")
23154 (forward-line)
23155 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23156 (insert ":")
23157 (forward-line)))
23158 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23159 (let* ((element (org-element-at-point))
23160 (element-end (org-element-property :end element)))
23161 (if (eq (org-element-type element) 'fixed-width)
23162 (progn (goto-char element-end)
23163 (skip-chars-backward " \r\t\n")
23164 (forward-line))
23165 (let ((limit (min end element-end)))
23166 (while (< (point) limit)
23167 (org-move-to-column min-ind t)
23168 (insert ": ")
23169 (forward-line))))))
23171 (org-move-to-column min-ind t)
23172 (insert ": ")
23173 (forward-line)))))))
23174 (set-marker end nil))))
23177 ;;; Comments
23179 ;; Org comments syntax is quite complex. It requires the entire line
23180 ;; to be just a comment. Also, even with the right syntax at the
23181 ;; beginning of line, some elements (e.g., verse-block or
23182 ;; example-block) don't accept comments. Usual Emacs comment commands
23183 ;; cannot cope with those requirements. Therefore, Org replaces them.
23185 ;; Org still relies on `comment-dwim', but cannot trust
23186 ;; `comment-only-p'. So, `comment-region-function' and
23187 ;; `uncomment-region-function' both point
23188 ;; to`org-comment-or-uncomment-region'. Eventually,
23189 ;; `org-insert-comment' takes care of insertion of comments at the
23190 ;; beginning of line.
23192 ;; `org-setup-comments-handling' install comments related variables
23193 ;; during `org-mode' initialization.
23195 (defun org-setup-comments-handling ()
23196 (interactive)
23197 (setq-local comment-use-syntax nil)
23198 (setq-local comment-start "# ")
23199 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23200 (setq-local comment-insert-comment-function 'org-insert-comment)
23201 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23202 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23204 (defun org-insert-comment ()
23205 "Insert an empty comment above current line.
23206 If the line is empty, insert comment at its beginning. When
23207 point is within a source block, comment according to the related
23208 major mode."
23209 (if (let ((element (org-element-at-point)))
23210 (and (eq (org-element-type element) 'src-block)
23211 (< (save-excursion
23212 (goto-char (org-element-property :post-affiliated element))
23213 (line-end-position))
23214 (point))
23215 (> (save-excursion
23216 (goto-char (org-element-property :end element))
23217 (skip-chars-backward " \r\t\n")
23218 (line-beginning-position))
23219 (point))))
23220 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23221 (beginning-of-line)
23222 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23223 (open-line 1))
23224 (org-indent-line)
23225 (insert "# ")))
23227 (defvar comment-empty-lines) ; From newcomment.el.
23228 (defun org-comment-or-uncomment-region (beg end &rest _)
23229 "Comment or uncomment each non-blank line in the region.
23230 Uncomment each non-blank line between BEG and END if it only
23231 contains commented lines. Otherwise, comment them. If region is
23232 strictly within a source block, use appropriate comment syntax."
23233 (if (let ((element (org-element-at-point)))
23234 (and (eq (org-element-type element) 'src-block)
23235 (< (save-excursion
23236 (goto-char (org-element-property :post-affiliated element))
23237 (line-end-position))
23238 beg)
23239 (>= (save-excursion
23240 (goto-char (org-element-property :end element))
23241 (skip-chars-backward " \r\t\n")
23242 (line-beginning-position))
23243 end)))
23244 ;; Translate region boundaries for the Org buffer to the source
23245 ;; buffer.
23246 (let ((offset (- end beg)))
23247 (save-excursion
23248 (goto-char beg)
23249 (org-babel-do-in-edit-buffer
23250 (comment-or-uncomment-region (point) (+ offset (point))))))
23251 (save-restriction
23252 ;; Restrict region
23253 (narrow-to-region (save-excursion (goto-char beg)
23254 (skip-chars-forward " \r\t\n" end)
23255 (line-beginning-position))
23256 (save-excursion (goto-char end)
23257 (skip-chars-backward " \r\t\n" beg)
23258 (line-end-position)))
23259 (let ((uncommentp
23260 ;; UNCOMMENTP is non-nil when every non blank line between
23261 ;; BEG and END is a comment.
23262 (save-excursion
23263 (goto-char (point-min))
23264 (while (and (not (eobp))
23265 (let ((element (org-element-at-point)))
23266 (and (eq (org-element-type element) 'comment)
23267 (goto-char (min (point-max)
23268 (org-element-property
23269 :end element)))))))
23270 (eobp))))
23271 (if uncommentp
23272 ;; Only blank lines and comments in region: uncomment it.
23273 (save-excursion
23274 (goto-char (point-min))
23275 (while (not (eobp))
23276 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23277 (replace-match "" nil nil nil 1))
23278 (forward-line)))
23279 ;; Comment each line in region.
23280 (let ((min-indent (point-max)))
23281 ;; First find the minimum indentation across all lines.
23282 (save-excursion
23283 (goto-char (point-min))
23284 (while (and (not (eobp)) (not (zerop min-indent)))
23285 (unless (looking-at "[ \t]*$")
23286 (setq min-indent (min min-indent (current-indentation))))
23287 (forward-line)))
23288 ;; Then loop over all lines.
23289 (save-excursion
23290 (goto-char (point-min))
23291 (while (not (eobp))
23292 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23293 ;; Don't get fooled by invisible text (e.g. link path)
23294 ;; when moving to column MIN-INDENT.
23295 (let ((buffer-invisibility-spec nil))
23296 (org-move-to-column min-indent t))
23297 (insert comment-start))
23298 (forward-line)))))))))
23300 (defun org-comment-dwim (_arg)
23301 "Call `comment-dwim' within a source edit buffer if needed."
23302 (interactive "*P")
23303 (if (org-in-src-block-p)
23304 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23305 (call-interactively 'comment-dwim)))
23308 ;;; Timestamps API
23310 ;; This section contains tools to operate on timestamp objects, as
23311 ;; returned by, e.g. `org-element-context'.
23313 (defun org-timestamp--to-internal-time (timestamp &optional end)
23314 "Encode TIMESTAMP object into Emacs internal time.
23315 Use end of date range or time range when END is non-nil."
23316 (apply #'encode-time
23317 (cons 0
23318 (mapcar
23319 (lambda (prop) (or (org-element-property prop timestamp) 0))
23320 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23321 '(:minute-start :hour-start :day-start :month-start
23322 :year-start))))))
23324 (defun org-timestamp-has-time-p (timestamp)
23325 "Non-nil when TIMESTAMP has a time specified."
23326 (org-element-property :hour-start timestamp))
23328 (defun org-timestamp-format (timestamp format &optional end utc)
23329 "Format a TIMESTAMP object into a string.
23331 FORMAT is a format specifier to be passed to
23332 `format-time-string'.
23334 When optional argument END is non-nil, use end of date-range or
23335 time-range, if possible.
23337 When optional argument UTC is non-nil, time will be expressed as
23338 Universal Time."
23339 (format-time-string
23340 format (org-timestamp--to-internal-time timestamp end)
23341 (and utc t)))
23343 (defun org-timestamp-split-range (timestamp &optional end)
23344 "Extract a TIMESTAMP object from a date or time range.
23346 END, when non-nil, means extract the end of the range.
23347 Otherwise, extract its start.
23349 Return a new timestamp object."
23350 (let ((type (org-element-property :type timestamp)))
23351 (if (memq type '(active inactive diary)) timestamp
23352 (let ((split-ts (org-element-copy timestamp)))
23353 ;; Set new type.
23354 (org-element-put-property
23355 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23356 ;; Copy start properties over end properties if END is
23357 ;; non-nil. Otherwise, copy end properties over `start' ones.
23358 (let ((p-alist '((:minute-start . :minute-end)
23359 (:hour-start . :hour-end)
23360 (:day-start . :day-end)
23361 (:month-start . :month-end)
23362 (:year-start . :year-end))))
23363 (dolist (p-cell p-alist)
23364 (org-element-put-property
23365 split-ts
23366 (funcall (if end #'car #'cdr) p-cell)
23367 (org-element-property
23368 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23369 ;; Eventually refresh `:raw-value'.
23370 (org-element-put-property split-ts :raw-value nil)
23371 (org-element-put-property
23372 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23374 (defun org-timestamp-translate (timestamp &optional boundary)
23375 "Translate TIMESTAMP object to custom format.
23377 Format string is defined in `org-time-stamp-custom-formats',
23378 which see.
23380 When optional argument BOUNDARY is non-nil, it is either the
23381 symbol `start' or `end'. In this case, only translate the
23382 starting or ending part of TIMESTAMP if it is a date or time
23383 range. Otherwise, translate both parts.
23385 Return timestamp as-is if `org-display-custom-times' is nil or if
23386 it has a `diary' type."
23387 (let ((type (org-element-property :type timestamp)))
23388 (if (or (not org-display-custom-times) (eq type 'diary))
23389 (org-element-interpret-data timestamp)
23390 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23391 org-time-stamp-custom-formats)))
23392 (if (and (not boundary) (memq type '(active-range inactive-range)))
23393 (concat (org-timestamp-format timestamp fmt)
23394 "--"
23395 (org-timestamp-format timestamp fmt t))
23396 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23400 ;;; Other stuff.
23402 (defvar reftex-docstruct-symbol)
23403 (defvar org--rds)
23405 (defun org-reftex-citation ()
23406 "Use reftex-citation to insert a citation into the buffer.
23407 This looks for a line like
23409 #+BIBLIOGRAPHY: foo plain option:-d
23411 and derives from it that foo.bib is the bibliography file relevant
23412 for this document. It then installs the necessary environment for RefTeX
23413 to work in this buffer and calls `reftex-citation' to insert a citation
23414 into the buffer.
23416 Export of such citations to both LaTeX and HTML is handled by the contributed
23417 package ox-bibtex by Taru Karttunen."
23418 (interactive)
23419 (let ((reftex-docstruct-symbol 'org--rds)
23420 org--rds bib)
23421 (org-with-wide-buffer
23422 (let ((case-fold-search t)
23423 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23424 (if (not (save-excursion
23425 (or (re-search-forward re nil t)
23426 (re-search-backward re nil t))))
23427 (user-error "No bibliography defined in file")
23428 (setq bib (concat (match-string 1) ".bib")
23429 org--rds (list (list 'bib bib))))))
23430 (call-interactively 'reftex-citation)))
23432 ;;;; Functions extending outline functionality
23434 (defun org-beginning-of-line (&optional n)
23435 "Go to the beginning of the current visible line.
23437 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23438 tags on the first attempt, and only move to after the tags when
23439 the cursor is already beyond the end of the headline.
23441 With argument N not nil or 1, move forward N - 1 lines first."
23442 (interactive "^p")
23443 (let ((origin (point))
23444 (special (pcase org-special-ctrl-a/e
23445 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23446 deactivate-mark)
23447 ;; First move to a visible line.
23448 (if (bound-and-true-p visual-line-mode)
23449 (beginning-of-visual-line n)
23450 (move-beginning-of-line n)
23451 ;; `move-beginning-of-line' may leave point after invisible
23452 ;; characters if line starts with such of these (e.g., with
23453 ;; a link at column 0). Really move to the beginning of the
23454 ;; current visible line.
23455 (beginning-of-line))
23456 (cond
23457 ;; No special behavior. Point is already at the beginning of
23458 ;; a line, logical or visual.
23459 ((not special))
23460 ;; `beginning-of-visual-line' left point before logical beginning
23461 ;; of line: point is at the beginning of a visual line. Bail
23462 ;; out.
23463 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23464 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23465 ;; At a headline, special position is before the title, but
23466 ;; after any TODO keyword or priority cookie.
23467 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23468 (line-end-position)))
23469 (bol (point)))
23470 (if (eq special 'reversed)
23471 (when (and (= origin bol) (eq last-command this-command))
23472 (goto-char refpos))
23473 (when (or (> origin refpos) (= origin bol))
23474 (goto-char refpos)))))
23475 ((and (looking-at org-list-full-item-re)
23476 (memq (org-element-type (save-match-data (org-element-at-point)))
23477 '(item plain-list)))
23478 ;; Set special position at first white space character after
23479 ;; bullet, and check-box, if any.
23480 (let ((after-bullet
23481 (let ((box (match-end 3)))
23482 (cond ((not box) (match-end 1))
23483 ((eq (char-after box) ?\s) (1+ box))
23484 (t box)))))
23485 (if (eq special 'reversed)
23486 (when (and (= (point) origin) (eq last-command this-command))
23487 (goto-char after-bullet))
23488 (when (or (> origin after-bullet) (= (point) origin))
23489 (goto-char after-bullet)))))
23490 ;; No special context. Point is already at beginning of line.
23491 (t nil))))
23493 (defun org-end-of-line (&optional n)
23494 "Go to the end of the line, but before ellipsis, if any.
23496 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23497 tags on the first attempt, and only move to after the tags when
23498 the cursor is already beyond the end of the headline.
23500 With argument N not nil or 1, move forward N - 1 lines first."
23501 (interactive "^p")
23502 (let ((origin (point))
23503 (special (pcase org-special-ctrl-a/e
23504 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23505 deactivate-mark)
23506 ;; First move to a visible line.
23507 (if (bound-and-true-p visual-line-mode)
23508 (beginning-of-visual-line n)
23509 (move-beginning-of-line n))
23510 (cond
23511 ;; At a headline, with tags.
23512 ((and special
23513 (save-excursion
23514 (beginning-of-line)
23515 (let ((case-fold-search nil))
23516 (looking-at org-complex-heading-regexp)))
23517 (match-end 5))
23518 (let ((tags (save-excursion
23519 (goto-char (match-beginning 5))
23520 (skip-chars-backward " \t")
23521 (point)))
23522 (visual-end (and (bound-and-true-p visual-line-mode)
23523 (save-excursion
23524 (end-of-visual-line)
23525 (point)))))
23526 ;; If `end-of-visual-line' brings us before end of line or
23527 ;; even tags, i.e., the headline spans over multiple visual
23528 ;; lines, move there.
23529 (cond ((and visual-end
23530 (< visual-end tags)
23531 (<= origin visual-end))
23532 (goto-char visual-end))
23533 ((eq special 'reversed)
23534 (if (and (= origin (line-end-position))
23535 (eq this-command last-command))
23536 (goto-char tags)
23537 (end-of-line)))
23539 (if (or (< origin tags) (= origin (line-end-position)))
23540 (goto-char tags)
23541 (end-of-line))))))
23542 ((bound-and-true-p visual-line-mode)
23543 (let ((bol (line-beginning-position)))
23544 (end-of-visual-line)
23545 ;; If `end-of-visual-line' gets us past the ellipsis at the
23546 ;; end of a line, backtrack and use `end-of-line' instead.
23547 (when (/= bol (line-beginning-position))
23548 (goto-char bol)
23549 (end-of-line))))
23550 (t (end-of-line)))))
23552 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23553 (define-key org-mode-map "\C-e" 'org-end-of-line)
23555 (defun org-backward-sentence (&optional _arg)
23556 "Go to beginning of sentence, or beginning of table field.
23557 This will call `backward-sentence' or `org-table-beginning-of-field',
23558 depending on context."
23559 (interactive)
23560 (let* ((element (org-element-at-point))
23561 (contents-begin (org-element-property :contents-begin element))
23562 (table (org-element-lineage element '(table) t)))
23563 (if (and table
23564 (> (point) contents-begin)
23565 (<= (point) (org-element-property :contents-end table)))
23566 (call-interactively #'org-table-beginning-of-field)
23567 (save-restriction
23568 (when (and contents-begin
23569 (< (point-min) contents-begin)
23570 (> (point) contents-begin))
23571 (narrow-to-region contents-begin
23572 (org-element-property :contents-end element)))
23573 (call-interactively #'backward-sentence)))))
23575 (defun org-forward-sentence (&optional _arg)
23576 "Go to end of sentence, or end of table field.
23577 This will call `forward-sentence' or `org-table-end-of-field',
23578 depending on context."
23579 (interactive)
23580 (if (and (org-at-heading-p)
23581 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23582 (save-restriction
23583 (narrow-to-region (line-beginning-position) (line-end-position))
23584 (call-interactively #'forward-sentence))
23585 (let* ((element (org-element-at-point))
23586 (contents-end (org-element-property :contents-end element))
23587 (table (org-element-lineage element '(table) t)))
23588 (if (and table
23589 (>= (point) (org-element-property :contents-begin table))
23590 (< (point) contents-end))
23591 (call-interactively #'org-table-end-of-field)
23592 (save-restriction
23593 (when (and contents-end
23594 (> (point-max) contents-end)
23595 ;; Skip blank lines between elements.
23596 (< (org-element-property :end element)
23597 (save-excursion (goto-char contents-end)
23598 (skip-chars-forward " \r\t\n"))))
23599 (narrow-to-region (org-element-property :contents-begin element)
23600 contents-end))
23601 ;; End of heading is considered as the end of a sentence.
23602 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23603 (call-interactively #'forward-sentence)))))))
23605 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23606 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23608 (defun org-kill-line (&optional _arg)
23609 "Kill line, to tags or end of line."
23610 (interactive)
23611 (cond
23612 ((or (not org-special-ctrl-k)
23613 (bolp)
23614 (not (org-at-heading-p)))
23615 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23616 org-ctrl-k-protect-subtree
23617 (or (eq org-ctrl-k-protect-subtree 'error)
23618 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23619 (user-error "C-k aborted as it would kill a hidden subtree"))
23620 (call-interactively
23621 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23622 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23623 (kill-region (point) (match-beginning 1))
23624 (org-set-tags nil t))
23625 (t (kill-region (point) (point-at-eol)))))
23627 (define-key org-mode-map "\C-k" 'org-kill-line)
23629 (defun org-yank (&optional arg)
23630 "Yank. If the kill is a subtree, treat it specially.
23631 This command will look at the current kill and check if is a single
23632 subtree, or a series of subtrees[1]. If it passes the test, and if the
23633 cursor is at the beginning of a line or after the stars of a currently
23634 empty headline, then the yank is handled specially. How exactly depends
23635 on the value of the following variables.
23637 `org-yank-folded-subtrees'
23638 By default, this variable is non-nil, which results in
23639 subtree(s) being folded after insertion, except if doing so
23640 would swallow text after the yanked text.
23642 `org-yank-adjusted-subtrees'
23643 When non-nil (the default value is nil), the subtree will be
23644 promoted or demoted in order to fit into the local outline tree
23645 structure, which means that the level will be adjusted so that it
23646 becomes the smaller one of the two *visible* surrounding headings.
23648 Any prefix to this command will cause `yank' to be called directly with
23649 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23650 will just
23651 plainly yank the text as it is.
23653 \[1] The test checks if the first non-white line is a heading
23654 and if there are no other headings with fewer stars."
23655 (interactive "P")
23656 (org-yank-generic 'yank arg))
23658 (defun org-yank-generic (command arg)
23659 "Perform some yank-like command.
23661 This function implements the behavior described in the `org-yank'
23662 documentation. However, it has been generalized to work for any
23663 interactive command with similar behavior."
23665 ;; pretend to be command COMMAND
23666 (setq this-command command)
23668 (if arg
23669 (call-interactively command)
23671 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23672 (and (org-kill-is-subtree-p)
23673 (or (bolp)
23674 (and (looking-at "[ \t]*$")
23675 (string-match
23676 "\\`\\*+\\'"
23677 (buffer-substring (point-at-bol) (point)))))))
23678 swallowp)
23679 (cond
23680 ((and subtreep org-yank-folded-subtrees)
23681 (let ((beg (point))
23682 end)
23683 (if (and subtreep org-yank-adjusted-subtrees)
23684 (org-paste-subtree nil nil 'for-yank)
23685 (call-interactively command))
23687 (setq end (point))
23688 (goto-char beg)
23689 (when (and (bolp) subtreep
23690 (not (setq swallowp
23691 (org-yank-folding-would-swallow-text beg end))))
23692 (org-with-limited-levels
23693 (or (looking-at org-outline-regexp)
23694 (re-search-forward org-outline-regexp-bol end t))
23695 (while (and (< (point) end) (looking-at org-outline-regexp))
23696 (outline-hide-subtree)
23697 (org-cycle-show-empty-lines 'folded)
23698 (condition-case nil
23699 (outline-forward-same-level 1)
23700 (error (goto-char end))))))
23701 (when swallowp
23702 (message
23703 "Inserted text not folded because that would swallow text"))
23705 (goto-char end)
23706 (skip-chars-forward " \t\n\r")
23707 (beginning-of-line 1)
23708 (push-mark beg 'nomsg)))
23709 ((and subtreep org-yank-adjusted-subtrees)
23710 (let ((beg (point-at-bol)))
23711 (org-paste-subtree nil nil 'for-yank)
23712 (push-mark beg 'nomsg)))
23714 (call-interactively command))))))
23716 (defun org-yank-folding-would-swallow-text (beg end)
23717 "Would hide-subtree at BEG swallow any text after END?"
23718 (let (level)
23719 (org-with-limited-levels
23720 (save-excursion
23721 (goto-char beg)
23722 (when (or (looking-at org-outline-regexp)
23723 (re-search-forward org-outline-regexp-bol end t))
23724 (setq level (org-outline-level)))
23725 (goto-char end)
23726 (skip-chars-forward " \t\r\n\v\f")
23727 (not (or (eobp)
23728 (and (bolp) (looking-at-p org-outline-regexp)
23729 (<= (org-outline-level) level))))))))
23731 (define-key org-mode-map "\C-y" 'org-yank)
23733 (defun org-truely-invisible-p ()
23734 "Check if point is at a character currently not visible.
23735 This version does not only check the character property, but also
23736 `visible-mode'."
23737 (unless (bound-and-true-p visible-mode)
23738 (org-invisible-p)))
23740 (defun org-invisible-p2 ()
23741 "Check if point is at a character currently not visible.
23743 If the point is at EOL (and not at the beginning of a buffer too),
23744 move it back by one char before doing this check."
23745 (save-excursion
23746 (when (and (eolp) (not (bobp)))
23747 (backward-char 1))
23748 (org-invisible-p)))
23750 (defun org-back-to-heading (&optional invisible-ok)
23751 "Call `outline-back-to-heading', but provide a better error message."
23752 (condition-case nil
23753 (outline-back-to-heading invisible-ok)
23754 (error (error "Before first headline at position %d in buffer %s"
23755 (point) (current-buffer)))))
23757 (defun org-before-first-heading-p ()
23758 "Before first heading?"
23759 (save-excursion
23760 (end-of-line)
23761 (null (re-search-backward org-outline-regexp-bol nil t))))
23763 (defun org-at-heading-p (&optional ignored)
23764 (outline-on-heading-p t))
23766 (defun org-in-commented-heading-p (&optional no-inheritance)
23767 "Non-nil if point is under a commented heading.
23768 This function also checks ancestors of the current headline,
23769 unless optional argument NO-INHERITANCE is non-nil."
23770 (cond
23771 ((org-before-first-heading-p) nil)
23772 ((let ((headline (nth 4 (org-heading-components))))
23773 (and headline
23774 (let ((case-fold-search nil))
23775 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23776 headline)))))
23777 (no-inheritance nil)
23779 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23781 (defun org-at-comment-p nil
23782 "Is cursor in a commented line?"
23783 (save-excursion
23784 (save-match-data
23785 (beginning-of-line)
23786 (looking-at "^[ \t]*# "))))
23788 (defun org-at-drawer-p nil
23789 "Is cursor at a drawer keyword?"
23790 (save-excursion
23791 (move-beginning-of-line 1)
23792 (looking-at org-drawer-regexp)))
23794 (defun org-at-block-p nil
23795 "Is cursor at a block keyword?"
23796 (save-excursion
23797 (move-beginning-of-line 1)
23798 (looking-at org-block-regexp)))
23800 (defun org-point-at-end-of-empty-headline ()
23801 "If point is at the end of an empty headline, return t, else nil.
23802 If the heading only contains a TODO keyword, it is still still considered
23803 empty."
23804 (let ((case-fold-search nil))
23805 (and (looking-at "[ \t]*$")
23806 org-todo-line-regexp
23807 (save-excursion
23808 (beginning-of-line)
23809 (looking-at org-todo-line-regexp)
23810 (string= (match-string 3) "")))))
23812 (defun org-at-heading-or-item-p ()
23813 (or (org-at-heading-p) (org-at-item-p)))
23815 (defun org-at-target-p ()
23816 (or (org-in-regexp org-radio-target-regexp)
23817 (org-in-regexp org-target-regexp)))
23818 ;; Compatibility alias with Org versions < 7.8.03
23819 (defalias 'org-on-target-p 'org-at-target-p)
23821 (defun org-up-heading-all (arg)
23822 "Move to the heading line of which the present line is a subheading.
23823 This function considers both visible and invisible heading lines.
23824 With argument, move up ARG levels."
23825 (outline-up-heading arg t))
23827 (defun org-up-heading-safe ()
23828 "Move to the heading line of which the present line is a subheading.
23829 This version will not throw an error. It will return the level of the
23830 headline found, or nil if no higher level is found.
23832 Also, this function will be a lot faster than `outline-up-heading',
23833 because it relies on stars being the outline starters. This can really
23834 make a significant difference in outlines with very many siblings."
23835 (when (ignore-errors (org-back-to-heading t))
23836 (let ((level-up (1- (funcall outline-level))))
23837 (and (> level-up 0)
23838 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23839 (funcall outline-level)))))
23841 (defun org-first-sibling-p ()
23842 "Is this heading the first child of its parents?"
23843 (interactive)
23844 (let ((re org-outline-regexp-bol)
23845 level l)
23846 (unless (org-at-heading-p t)
23847 (user-error "Not at a heading"))
23848 (setq level (funcall outline-level))
23849 (save-excursion
23850 (if (not (re-search-backward re nil t))
23852 (setq l (funcall outline-level))
23853 (< l level)))))
23855 (defun org-goto-sibling (&optional previous)
23856 "Goto the next sibling, even if it is invisible.
23857 When PREVIOUS is set, go to the previous sibling instead. Returns t
23858 when a sibling was found. When none is found, return nil and don't
23859 move point."
23860 (let ((fun (if previous 're-search-backward 're-search-forward))
23861 (pos (point))
23862 (re org-outline-regexp-bol)
23863 level l)
23864 (when (ignore-errors (org-back-to-heading t))
23865 (setq level (funcall outline-level))
23866 (catch 'exit
23867 (or previous (forward-char 1))
23868 (while (funcall fun re nil t)
23869 (setq l (funcall outline-level))
23870 (when (< l level) (goto-char pos) (throw 'exit nil))
23871 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23872 (goto-char pos)
23873 nil))))
23875 (defun org-show-siblings ()
23876 "Show all siblings of the current headline."
23877 (save-excursion
23878 (while (org-goto-sibling) (org-flag-heading nil)))
23879 (save-excursion
23880 (while (org-goto-sibling 'previous)
23881 (org-flag-heading nil))))
23883 (defun org-goto-first-child ()
23884 "Goto the first child, even if it is invisible.
23885 Return t when a child was found. Otherwise don't move point and
23886 return nil."
23887 (let (level (pos (point)) (re org-outline-regexp-bol))
23888 (when (ignore-errors (org-back-to-heading t))
23889 (setq level (outline-level))
23890 (forward-char 1)
23891 (if (and (re-search-forward re nil t) (> (outline-level) level))
23892 (progn (goto-char (match-beginning 0)) t)
23893 (goto-char pos) nil))))
23895 (defun org-show-hidden-entry ()
23896 "Show an entry where even the heading is hidden."
23897 (save-excursion
23898 (org-show-entry)))
23900 (defun org-flag-heading (flag &optional entry)
23901 "Flag the current heading. FLAG non-nil means make invisible.
23902 When ENTRY is non-nil, show the entire entry."
23903 (save-excursion
23904 (org-back-to-heading t)
23905 ;; Check if we should show the entire entry
23906 (if entry
23907 (progn
23908 (org-show-entry)
23909 (save-excursion
23910 (and (outline-next-heading)
23911 (org-flag-heading nil))))
23912 (outline-flag-region (max (point-min) (1- (point)))
23913 (save-excursion (outline-end-of-heading) (point))
23914 flag))))
23916 (defun org-get-next-sibling ()
23917 "Move to next heading of the same level, and return point.
23918 If there is no such heading, return nil.
23919 This is like outline-next-sibling, but invisible headings are ok."
23920 (let ((level (funcall outline-level)))
23921 (outline-next-heading)
23922 (while (and (not (eobp)) (> (funcall outline-level) level))
23923 (outline-next-heading))
23924 (unless (or (eobp) (< (funcall outline-level) level))
23925 (point))))
23927 (defun org-get-last-sibling ()
23928 "Move to previous heading of the same level, and return point.
23929 If there is no such heading, return nil."
23930 (let ((opoint (point))
23931 (level (funcall outline-level)))
23932 (outline-previous-heading)
23933 (when (and (/= (point) opoint) (outline-on-heading-p t))
23934 (while (and (> (funcall outline-level) level)
23935 (not (bobp)))
23936 (outline-previous-heading))
23937 (unless (< (funcall outline-level) level)
23938 (point)))))
23940 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23941 "Goto to the end of a subtree."
23942 ;; This contains an exact copy of the original function, but it uses
23943 ;; `org-back-to-heading', to make it work also in invisible
23944 ;; trees. And is uses an invisible-ok argument.
23945 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23946 ;; Furthermore, when used inside Org, finding the end of a large subtree
23947 ;; with many children and grandchildren etc, this can be much faster
23948 ;; than the outline version.
23949 (org-back-to-heading invisible-ok)
23950 (let ((first t)
23951 (level (funcall outline-level)))
23952 (if (and (derived-mode-p 'org-mode) (< level 1000))
23953 ;; A true heading (not a plain list item), in Org
23954 ;; This means we can easily find the end by looking
23955 ;; only for the right number of stars. Using a regexp to do
23956 ;; this is so much faster than using a Lisp loop.
23957 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23958 (forward-char 1)
23959 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23960 ;; something else, do it the slow way
23961 (while (and (not (eobp))
23962 (or first (> (funcall outline-level) level)))
23963 (setq first nil)
23964 (outline-next-heading)))
23965 (unless to-heading
23966 (when (memq (preceding-char) '(?\n ?\^M))
23967 ;; Go to end of line before heading
23968 (forward-char -1)
23969 (when (memq (preceding-char) '(?\n ?\^M))
23970 ;; leave blank line before heading
23971 (forward-char -1)))))
23972 (point))
23974 (defun org-end-of-meta-data (&optional full)
23975 "Skip planning line and properties drawer in current entry.
23976 When optional argument FULL is non-nil, also skip empty lines,
23977 clocking lines and regular drawers at the beginning of the
23978 entry."
23979 (org-back-to-heading t)
23980 (forward-line)
23981 (when (looking-at-p org-planning-line-re) (forward-line))
23982 (when (looking-at org-property-drawer-re)
23983 (goto-char (match-end 0))
23984 (forward-line))
23985 (when (and full (not (org-at-heading-p)))
23986 (catch 'exit
23987 (let ((end (save-excursion (outline-next-heading) (point)))
23988 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23989 (while (not (eobp))
23990 (cond ((looking-at-p org-drawer-regexp)
23991 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23992 (forward-line)
23993 (throw 'exit t)))
23994 ((looking-at-p re) (forward-line))
23995 (t (throw 'exit t))))))))
23997 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23998 "Move forward to the ARG'th subheading at same level as this one.
23999 Stop at the first and last subheadings of a superior heading.
24000 Normally this only looks at visible headings, but when INVISIBLE-OK is
24001 non-nil it will also look at invisible ones."
24002 (interactive "p")
24003 (let ((backward? (and arg (< arg 0))))
24004 (if (org-before-first-heading-p)
24005 (if backward? (goto-char (point-min)) (outline-next-heading))
24006 (org-back-to-heading invisible-ok)
24007 (unless backward? (end-of-line)) ;do not match current headline
24008 (let ((level (- (match-end 0) (match-beginning 0) 1))
24009 (f (if backward? #'re-search-backward #'re-search-forward))
24010 (count (if arg (abs arg) 1))
24011 (result (point)))
24012 (while (and (> count 0)
24013 (funcall f org-outline-regexp-bol nil 'move))
24014 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24015 (cond ((< l level) (setq count 0))
24016 ((and (= l level)
24017 (or invisible-ok
24018 (not (org-invisible-p
24019 (line-beginning-position)))))
24020 (cl-decf count)
24021 (when (= l level) (setq result (point)))))))
24022 (goto-char result))
24023 (beginning-of-line))))
24025 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24026 "Move backward to the ARG'th subheading at same level as this one.
24027 Stop at the first and last subheadings of a superior heading."
24028 (interactive "p")
24029 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24031 (defun org-next-visible-heading (arg)
24032 "Move to the next visible heading.
24034 This function wraps `outline-next-visible-heading' with
24035 `org-with-limited-levels' in order to skip over inline tasks and
24036 respect customization of `org-odd-levels-only'."
24037 (interactive "p")
24038 (org-with-limited-levels
24039 (outline-next-visible-heading arg)))
24041 (defun org-previous-visible-heading (arg)
24042 "Move to the previous visible heading.
24044 This function wraps `outline-previous-visible-heading' with
24045 `org-with-limited-levels' in order to skip over inline tasks and
24046 respect customization of `org-odd-levels-only'."
24047 (interactive "p")
24048 (org-with-limited-levels
24049 (outline-previous-visible-heading arg)))
24051 (defun org-next-block (arg &optional backward block-regexp)
24052 "Jump to the next block.
24054 With a prefix argument ARG, jump forward ARG many blocks.
24056 When BACKWARD is non-nil, jump to the previous block.
24058 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24059 Match data is set according to this regexp when the function
24060 returns.
24062 Return point at beginning of the opening line of found block.
24063 Throw an error if no block is found."
24064 (interactive "p")
24065 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24066 (case-fold-search t)
24067 (search-fn (if backward #'re-search-backward #'re-search-forward))
24068 (count (or arg 1))
24069 (origin (point))
24070 last-element)
24071 (if backward (beginning-of-line) (end-of-line))
24072 (while (and (> count 0) (funcall search-fn re nil t))
24073 (let ((element (save-excursion
24074 (goto-char (match-beginning 0))
24075 (save-match-data (org-element-at-point)))))
24076 (when (and (memq (org-element-type element)
24077 '(center-block comment-block dynamic-block
24078 example-block export-block quote-block
24079 special-block src-block verse-block))
24080 (<= (match-beginning 0)
24081 (org-element-property :post-affiliated element)))
24082 (setq last-element element)
24083 (cl-decf count))))
24084 (if (= count 0)
24085 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24086 (save-match-data (org-show-context)))
24087 (goto-char origin)
24088 (user-error "No %s code blocks" (if backward "previous" "further")))))
24090 (defun org-previous-block (arg &optional block-regexp)
24091 "Jump to the previous block.
24092 With a prefix argument ARG, jump backward ARG many source blocks.
24093 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24094 (interactive "p")
24095 (org-next-block arg t block-regexp))
24097 (defun org-forward-paragraph ()
24098 "Move forward to beginning of next paragraph or equivalent.
24100 The function moves point to the beginning of the next visible
24101 structural element, which can be a paragraph, a table, a list
24102 item, etc. It also provides some special moves for convenience:
24104 - On an affiliated keyword, jump to the beginning of the
24105 relative element.
24106 - On an item or a footnote definition, move to the second
24107 element inside, if any.
24108 - On a table or a property drawer, jump after it.
24109 - On a verse or source block, stop after blank lines."
24110 (interactive)
24111 (unless (eobp)
24112 (let* ((deactivate-mark nil)
24113 (element (org-element-at-point))
24114 (type (org-element-type element))
24115 (post-affiliated (org-element-property :post-affiliated element))
24116 (contents-begin (org-element-property :contents-begin element))
24117 (contents-end (org-element-property :contents-end element))
24118 (end (let ((end (org-element-property :end element)) (parent element))
24119 (while (and (setq parent (org-element-property :parent parent))
24120 (= (org-element-property :contents-end parent) end))
24121 (setq end (org-element-property :end parent)))
24122 end)))
24123 (cond ((not element)
24124 (skip-chars-forward " \r\t\n")
24125 (or (eobp) (beginning-of-line)))
24126 ;; On affiliated keywords, move to element's beginning.
24127 ((< (point) post-affiliated)
24128 (goto-char post-affiliated))
24129 ;; At a table row, move to the end of the table. Similarly,
24130 ;; at a node property, move to the end of the property
24131 ;; drawer.
24132 ((memq type '(node-property table-row))
24133 (goto-char (org-element-property
24134 :end (org-element-property :parent element))))
24135 ((memq type '(property-drawer table)) (goto-char end))
24136 ;; Consider blank lines as separators in verse and source
24137 ;; blocks to ease editing.
24138 ((memq type '(src-block verse-block))
24139 (when (eq type 'src-block)
24140 (setq contents-end
24141 (save-excursion (goto-char end)
24142 (skip-chars-backward " \r\t\n")
24143 (line-beginning-position))))
24144 (beginning-of-line)
24145 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24146 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24147 (goto-char end)
24148 (skip-chars-forward " \r\t\n")
24149 (if (= (point) contents-end) (goto-char end)
24150 (beginning-of-line))))
24151 ;; With no contents, just skip element.
24152 ((not contents-begin) (goto-char end))
24153 ;; If contents are invisible, skip the element altogether.
24154 ((org-invisible-p (line-end-position))
24155 (cl-case type
24156 (headline
24157 (org-with-limited-levels (outline-next-visible-heading 1)))
24158 ;; At a plain list, make sure we move to the next item
24159 ;; instead of skipping the whole list.
24160 (plain-list (forward-char)
24161 (org-forward-paragraph))
24162 (otherwise (goto-char end))))
24163 ((>= (point) contents-end) (goto-char end))
24164 ((>= (point) contents-begin)
24165 ;; This can only happen on paragraphs and plain lists.
24166 (cl-case type
24167 (paragraph (goto-char end))
24168 ;; At a plain list, try to move to second element in
24169 ;; first item, if possible.
24170 (plain-list (end-of-line)
24171 (org-forward-paragraph))))
24172 ;; When contents start on the middle of a line (e.g. in
24173 ;; items and footnote definitions), try to reach first
24174 ;; element starting after current line.
24175 ((> (line-end-position) contents-begin)
24176 (end-of-line)
24177 (org-forward-paragraph))
24178 (t (goto-char contents-begin))))))
24180 (defun org-backward-paragraph ()
24181 "Move backward to start of previous paragraph or equivalent.
24183 The function moves point to the beginning of the current
24184 structural element, which can be a paragraph, a table, a list
24185 item, etc., or to the beginning of the previous visible one if
24186 point is already there. It also provides some special moves for
24187 convenience:
24189 - On an affiliated keyword, jump to the first one.
24190 - On a table or a property drawer, move to its beginning.
24191 - On comment, example, export, src and verse blocks, stop
24192 before blank lines."
24193 (interactive)
24194 (unless (bobp)
24195 (let* ((deactivate-mark nil)
24196 (element (org-element-at-point))
24197 (type (org-element-type element))
24198 (contents-end (org-element-property :contents-end element))
24199 (post-affiliated (org-element-property :post-affiliated element))
24200 (begin (org-element-property :begin element))
24201 (special? ;blocks handled specially
24202 (memq type '(comment-block example-block export-block src-block
24203 verse-block)))
24204 (contents-begin
24205 (if special?
24206 ;; These types have no proper contents. Fake line
24207 ;; below the block opening line as contents beginning.
24208 (save-excursion (goto-char begin) (line-beginning-position 2))
24209 (org-element-property :contents-begin element))))
24210 (cond
24211 ((not element) (goto-char (point-min)))
24212 ((= (point) begin)
24213 (backward-char)
24214 (org-backward-paragraph))
24215 ((<= (point) post-affiliated) (goto-char begin))
24216 ;; Special behavior: on a table or a property drawer, move to
24217 ;; its beginning.
24218 ((memq type '(node-property table-row))
24219 (goto-char (org-element-property
24220 :post-affiliated (org-element-property :parent element))))
24221 (special?
24222 (if (<= (point) contents-begin) (goto-char post-affiliated)
24223 ;; Inside a verse block, see blank lines as paragraph
24224 ;; separators.
24225 (let ((origin (point)))
24226 (skip-chars-backward " \r\t\n" contents-begin)
24227 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24228 (skip-chars-forward " \r\t\n" origin)
24229 (if (= (point) origin) (goto-char contents-begin)
24230 (beginning-of-line))))))
24231 ((eq type 'paragraph) (goto-char contents-begin)
24232 ;; When at first paragraph in an item or a footnote definition,
24233 ;; move directly to beginning of line.
24234 (let ((parent-contents
24235 (org-element-property
24236 :contents-begin (org-element-property :parent element))))
24237 (when (and parent-contents (= parent-contents contents-begin))
24238 (beginning-of-line))))
24239 ;; At the end of a greater element, move to the beginning of
24240 ;; the last element within.
24241 ((and contents-end (>= (point) contents-end))
24242 (goto-char (1- contents-end))
24243 (org-backward-paragraph))
24244 (t (goto-char (or post-affiliated begin))))
24245 ;; Ensure we never leave point invisible.
24246 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24248 (defun org-forward-element ()
24249 "Move forward by one element.
24250 Move to the next element at the same level, when possible."
24251 (interactive)
24252 (cond ((eobp) (user-error "Cannot move further down"))
24253 ((org-with-limited-levels (org-at-heading-p))
24254 (let ((origin (point)))
24255 (goto-char (org-end-of-subtree nil t))
24256 (unless (org-with-limited-levels (org-at-heading-p))
24257 (goto-char origin)
24258 (user-error "Cannot move further down"))))
24260 (let* ((elem (org-element-at-point))
24261 (end (org-element-property :end elem))
24262 (parent (org-element-property :parent elem)))
24263 (cond ((and parent (= (org-element-property :contents-end parent) end))
24264 (goto-char (org-element-property :end parent)))
24265 ((integer-or-marker-p end) (goto-char end))
24266 (t (message "No element at point")))))))
24268 (defun org-backward-element ()
24269 "Move backward by one element.
24270 Move to the previous element at the same level, when possible."
24271 (interactive)
24272 (cond ((bobp) (user-error "Cannot move further up"))
24273 ((org-with-limited-levels (org-at-heading-p))
24274 ;; At a headline, move to the previous one, if any, or stay
24275 ;; here.
24276 (let ((origin (point)))
24277 (org-with-limited-levels (org-backward-heading-same-level 1))
24278 ;; When current headline has no sibling above, move to its
24279 ;; parent.
24280 (when (= (point) origin)
24281 (or (org-with-limited-levels (org-up-heading-safe))
24282 (progn (goto-char origin)
24283 (user-error "Cannot move further up"))))))
24285 (let* ((elem (org-element-at-point))
24286 (beg (org-element-property :begin elem)))
24287 (cond
24288 ;; Move to beginning of current element if point isn't
24289 ;; there already.
24290 ((null beg) (message "No element at point"))
24291 ((/= (point) beg) (goto-char beg))
24292 (t (goto-char beg)
24293 (skip-chars-backward " \r\t\n")
24294 (unless (bobp)
24295 (let ((prev (org-element-at-point)))
24296 (goto-char (org-element-property :begin prev))
24297 (while (and (setq prev (org-element-property :parent prev))
24298 (<= (org-element-property :end prev) beg))
24299 (goto-char (org-element-property :begin prev)))))))))))
24301 (defun org-up-element ()
24302 "Move to upper element."
24303 (interactive)
24304 (if (org-with-limited-levels (org-at-heading-p))
24305 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24306 (let* ((elem (org-element-at-point))
24307 (parent (org-element-property :parent elem)))
24308 (if parent (goto-char (org-element-property :begin parent))
24309 (if (org-with-limited-levels (org-before-first-heading-p))
24310 (user-error "No surrounding element")
24311 (org-with-limited-levels (org-back-to-heading)))))))
24313 (defun org-down-element ()
24314 "Move to inner element."
24315 (interactive)
24316 (let ((element (org-element-at-point)))
24317 (cond
24318 ((memq (org-element-type element) '(plain-list table))
24319 (goto-char (org-element-property :contents-begin element))
24320 (forward-char))
24321 ((memq (org-element-type element) org-element-greater-elements)
24322 ;; If contents are hidden, first disclose them.
24323 (when (org-invisible-p (line-end-position)) (org-cycle))
24324 (goto-char (or (org-element-property :contents-begin element)
24325 (user-error "No content for this element"))))
24326 (t (user-error "No inner element")))))
24328 (defun org-drag-element-backward ()
24329 "Move backward element at point."
24330 (interactive)
24331 (let ((elem (or (org-element-at-point)
24332 (user-error "No element at point"))))
24333 (if (eq (org-element-type elem) 'headline)
24334 ;; Preserve point when moving a whole tree, even if point was
24335 ;; on blank lines below the headline.
24336 (let ((offset (skip-chars-backward " \t\n")))
24337 (unwind-protect (org-move-subtree-up)
24338 (forward-char (- offset))))
24339 (let ((prev-elem
24340 (save-excursion
24341 (goto-char (org-element-property :begin elem))
24342 (skip-chars-backward " \r\t\n")
24343 (unless (bobp)
24344 (let* ((beg (org-element-property :begin elem))
24345 (prev (org-element-at-point))
24346 (up prev))
24347 (while (and (setq up (org-element-property :parent up))
24348 (<= (org-element-property :end up) beg))
24349 (setq prev up))
24350 prev)))))
24351 ;; Error out if no previous element or previous element is
24352 ;; a parent of the current one.
24353 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24354 (user-error "Cannot drag element backward")
24355 (let ((pos (point)))
24356 (org-element-swap-A-B prev-elem elem)
24357 (goto-char (+ (org-element-property :begin prev-elem)
24358 (- pos (org-element-property :begin elem))))))))))
24360 (defun org-drag-element-forward ()
24361 "Move forward element at point."
24362 (interactive)
24363 (let* ((pos (point))
24364 (elem (or (org-element-at-point)
24365 (user-error "No element at point"))))
24366 (when (= (point-max) (org-element-property :end elem))
24367 (user-error "Cannot drag element forward"))
24368 (goto-char (org-element-property :end elem))
24369 (let ((next-elem (org-element-at-point)))
24370 (when (or (org-element-nested-p elem next-elem)
24371 (and (eq (org-element-type next-elem) 'headline)
24372 (not (eq (org-element-type elem) 'headline))))
24373 (goto-char pos)
24374 (user-error "Cannot drag element forward"))
24375 ;; Compute new position of point: it's shifted by NEXT-ELEM
24376 ;; body's length (without final blanks) and by the length of
24377 ;; blanks between ELEM and NEXT-ELEM.
24378 (let ((size-next (- (save-excursion
24379 (goto-char (org-element-property :end next-elem))
24380 (skip-chars-backward " \r\t\n")
24381 (forward-line)
24382 ;; Small correction if buffer doesn't end
24383 ;; with a newline character.
24384 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24385 (org-element-property :begin next-elem)))
24386 (size-blank (- (org-element-property :end elem)
24387 (save-excursion
24388 (goto-char (org-element-property :end elem))
24389 (skip-chars-backward " \r\t\n")
24390 (forward-line)
24391 (point)))))
24392 (org-element-swap-A-B elem next-elem)
24393 (goto-char (+ pos size-next size-blank))))))
24395 (defun org-drag-line-forward (arg)
24396 "Drag the line at point ARG lines forward."
24397 (interactive "p")
24398 (dotimes (_ (abs arg))
24399 (let ((c (current-column)))
24400 (if (< 0 arg)
24401 (progn
24402 (beginning-of-line 2)
24403 (transpose-lines 1)
24404 (beginning-of-line 0))
24405 (transpose-lines 1)
24406 (beginning-of-line -1))
24407 (org-move-to-column c))))
24409 (defun org-drag-line-backward (arg)
24410 "Drag the line at point ARG lines backward."
24411 (interactive "p")
24412 (org-drag-line-forward (- arg)))
24414 (defun org-mark-element ()
24415 "Put point at beginning of this element, mark at end.
24417 Interactively, if this command is repeated or (in Transient Mark
24418 mode) if the mark is active, it marks the next element after the
24419 ones already marked."
24420 (interactive)
24421 (let (deactivate-mark)
24422 (if (and (called-interactively-p 'any)
24423 (or (and (eq last-command this-command) (mark t))
24424 (and transient-mark-mode mark-active)))
24425 (set-mark
24426 (save-excursion
24427 (goto-char (mark))
24428 (goto-char (org-element-property :end (org-element-at-point)))))
24429 (let ((element (org-element-at-point)))
24430 (end-of-line)
24431 (push-mark (org-element-property :end element) t t)
24432 (goto-char (org-element-property :begin element))))))
24434 (defun org-narrow-to-element ()
24435 "Narrow buffer to current element."
24436 (interactive)
24437 (let ((elem (org-element-at-point)))
24438 (cond
24439 ((eq (car elem) 'headline)
24440 (narrow-to-region
24441 (org-element-property :begin elem)
24442 (org-element-property :end elem)))
24443 ((memq (car elem) org-element-greater-elements)
24444 (narrow-to-region
24445 (org-element-property :contents-begin elem)
24446 (org-element-property :contents-end elem)))
24448 (narrow-to-region
24449 (org-element-property :begin elem)
24450 (org-element-property :end elem))))))
24452 (defun org-transpose-element ()
24453 "Transpose current and previous elements, keeping blank lines between.
24454 Point is moved after both elements."
24455 (interactive)
24456 (org-skip-whitespace)
24457 (let ((end (org-element-property :end (org-element-at-point))))
24458 (org-drag-element-backward)
24459 (goto-char end)))
24461 (defun org-unindent-buffer ()
24462 "Un-indent the visible part of the buffer.
24463 Relative indentation (between items, inside blocks, etc.) isn't
24464 modified."
24465 (interactive)
24466 (unless (eq major-mode 'org-mode)
24467 (user-error "Cannot un-indent a buffer not in Org mode"))
24468 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24469 (unindent-tree
24470 (lambda (contents)
24471 (dolist (element (reverse contents))
24472 (if (memq (org-element-type element) '(headline section))
24473 (funcall unindent-tree (org-element-contents element))
24474 (save-excursion
24475 (save-restriction
24476 (narrow-to-region
24477 (org-element-property :begin element)
24478 (org-element-property :end element))
24479 (org-do-remove-indentation))))))))
24480 (funcall unindent-tree (org-element-contents parse-tree))))
24482 (defun org-show-children (&optional level)
24483 "Show all direct subheadings of this heading.
24484 Prefix arg LEVEL is how many levels below the current level
24485 should be shown. Default is enough to cause the following
24486 heading to appear."
24487 (interactive "p")
24488 ;; If `orgstruct-mode' is active, use the slower version.
24489 (if orgstruct-mode (call-interactively #'outline-show-children)
24490 (save-excursion
24491 (org-back-to-heading t)
24492 (let* ((current-level (funcall outline-level))
24493 (max-level (org-get-valid-level
24494 current-level
24495 (if level (prefix-numeric-value level) 1)))
24496 (end (save-excursion (org-end-of-subtree t t)))
24497 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24498 (past-first-child nil)
24499 ;; Make sure to skip inlinetasks.
24500 (re (format regexp-fmt
24501 current-level
24502 (cond
24503 ((not (featurep 'org-inlinetask)) "")
24504 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24506 (t (1- org-inlinetask-min-level))))))
24507 ;; Display parent heading.
24508 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24509 (forward-line)
24510 ;; Display children. First child may be deeper than expected
24511 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24512 ;; MAX-LEVEL accordingly.
24513 (while (re-search-forward re end t)
24514 (unless past-first-child
24515 (setq re (format regexp-fmt
24516 current-level
24517 (max (funcall outline-level) max-level)))
24518 (setq past-first-child t))
24519 (outline-flag-region
24520 (line-end-position 0) (line-end-position) nil))))))
24522 (defun org-show-subtree ()
24523 "Show everything after this heading at deeper levels."
24524 (interactive)
24525 (outline-flag-region
24526 (point)
24527 (save-excursion
24528 (org-end-of-subtree t t))
24529 nil))
24531 (defun org-show-entry ()
24532 "Show the body directly following this heading.
24533 Show the heading too, if it is currently invisible."
24534 (interactive)
24535 (save-excursion
24536 (ignore-errors
24537 (org-back-to-heading t)
24538 (outline-flag-region
24539 (max (point-min) (1- (point)))
24540 (save-excursion
24541 (if (re-search-forward
24542 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24543 (match-beginning 1)
24544 (point-max)))
24545 nil)
24546 (org-cycle-hide-drawers 'children))))
24548 (defun org-make-options-regexp (kwds &optional extra)
24549 "Make a regular expression for keyword lines.
24550 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24551 when non-nil, is a regexp matching keywords names."
24552 (concat "^[ \t]*#\\+\\("
24553 (regexp-opt kwds)
24554 (and extra (concat (and kwds "\\|") extra))
24555 "\\):[ \t]*\\(.*\\)"))
24557 ;;;; Integration with and fixes for other packages
24559 ;;; Imenu support
24561 (defvar-local org-imenu-markers nil
24562 "All markers currently used by Imenu.")
24564 (defun org-imenu-new-marker (&optional pos)
24565 "Return a new marker for use by Imenu, and remember the marker."
24566 (let ((m (make-marker)))
24567 (move-marker m (or pos (point)))
24568 (push m org-imenu-markers)
24571 (defun org-imenu-get-tree ()
24572 "Produce the index for Imenu."
24573 (dolist (x org-imenu-markers) (move-marker x nil))
24574 (setq org-imenu-markers nil)
24575 (let* ((case-fold-search nil)
24576 (n org-imenu-depth)
24577 (re (concat "^" (org-get-limited-outline-regexp)))
24578 (subs (make-vector (1+ n) nil))
24579 (last-level 0)
24580 m level head0 head)
24581 (org-with-wide-buffer
24582 (goto-char (point-max))
24583 (while (re-search-backward re nil t)
24584 (setq level (org-reduced-level (funcall outline-level)))
24585 (when (and (<= level n)
24586 (looking-at org-complex-heading-regexp)
24587 (setq head0 (match-string-no-properties 4)))
24588 (setq head (org-link-display-format head0)
24589 m (org-imenu-new-marker))
24590 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24591 (if (>= level last-level)
24592 (push (cons head m) (aref subs level))
24593 (push (cons head (aref subs (1+ level))) (aref subs level))
24594 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24595 (setq last-level level))))
24596 (aref subs 1)))
24598 (eval-after-load "imenu"
24599 '(progn
24600 (add-hook 'imenu-after-jump-hook
24601 (lambda ()
24602 (when (derived-mode-p 'org-mode)
24603 (org-show-context 'org-goto))))))
24605 (defun org-link-display-format (s)
24606 "Replace links in string S with their description.
24607 If there is no description, use the link target."
24608 (save-match-data
24609 (replace-regexp-in-string
24610 org-bracket-link-analytic-regexp
24611 (lambda (m)
24612 (if (match-end 5) (match-string 5 m)
24613 (concat (match-string 1 m) (match-string 3 m))))
24614 s nil t)))
24616 (defun org-toggle-link-display ()
24617 "Toggle the literal or descriptive display of links."
24618 (interactive)
24619 (if org-descriptive-links
24620 (progn (org-remove-from-invisibility-spec '(org-link))
24621 (org-restart-font-lock)
24622 (setq org-descriptive-links nil))
24623 (progn (add-to-invisibility-spec '(org-link))
24624 (org-restart-font-lock)
24625 (setq org-descriptive-links t))))
24627 ;; Speedbar support
24629 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24630 "Overlay marking the agenda restriction line in speedbar.")
24631 (overlay-put org-speedbar-restriction-lock-overlay
24632 'face 'org-agenda-restriction-lock)
24633 (overlay-put org-speedbar-restriction-lock-overlay
24634 'help-echo "Agendas are currently limited to this item.")
24635 (delete-overlay org-speedbar-restriction-lock-overlay)
24637 (defun org-speedbar-set-agenda-restriction ()
24638 "Restrict future agenda commands to the location at point in speedbar.
24639 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24640 (interactive)
24641 (require 'org-agenda)
24642 (let (p m tp np dir txt)
24643 (cond
24644 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24645 'org-imenu t))
24646 (setq m (get-text-property p 'org-imenu-marker))
24647 (with-current-buffer (marker-buffer m)
24648 (goto-char m)
24649 (org-agenda-set-restriction-lock 'subtree)))
24650 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24651 'speedbar-function 'speedbar-find-file))
24652 (setq tp (previous-single-property-change
24653 (1+ p) 'speedbar-function)
24654 np (next-single-property-change
24655 tp 'speedbar-function)
24656 dir (speedbar-line-directory)
24657 txt (buffer-substring-no-properties (or tp (point-min))
24658 (or np (point-max))))
24659 (with-current-buffer (find-file-noselect
24660 (let ((default-directory dir))
24661 (expand-file-name txt)))
24662 (unless (derived-mode-p 'org-mode)
24663 (user-error "Cannot restrict to non-Org mode file"))
24664 (org-agenda-set-restriction-lock 'file)))
24665 (t (user-error "Don't know how to restrict Org mode agenda")))
24666 (move-overlay org-speedbar-restriction-lock-overlay
24667 (point-at-bol) (point-at-eol))
24668 (setq current-prefix-arg nil)
24669 (org-agenda-maybe-redo)))
24671 (defvar speedbar-file-key-map)
24672 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24673 (eval-after-load "speedbar"
24674 '(progn
24675 (speedbar-add-supported-extension ".org")
24676 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24677 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24678 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24679 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24680 (add-hook 'speedbar-visiting-tag-hook
24681 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24683 ;;; Fixes and Hacks for problems with other packages
24685 (defun org--flyspell-object-check-p (element)
24686 "Non-nil when Flyspell can check object at point.
24687 ELEMENT is the element at point."
24688 (let ((object (save-excursion
24689 (when (looking-at-p "\\>") (backward-char))
24690 (org-element-context element))))
24691 (cl-case (org-element-type object)
24692 ;; Prevent checks in links due to keybinding conflict with
24693 ;; Flyspell.
24694 ((code entity export-snippet inline-babel-call
24695 inline-src-block line-break latex-fragment link macro
24696 statistics-cookie target timestamp verbatim)
24697 nil)
24698 (footnote-reference
24699 ;; Only in inline footnotes, within the definition.
24700 (and (eq (org-element-property :type object) 'inline)
24701 (< (save-excursion
24702 (goto-char (org-element-property :begin object))
24703 (search-forward ":" nil t 2))
24704 (point))))
24705 (otherwise t))))
24707 (defun org-mode-flyspell-verify ()
24708 "Function used for `flyspell-generic-check-word-predicate'."
24709 (if (org-at-heading-p)
24710 ;; At a headline or an inlinetask, check title only. This is
24711 ;; faster than relying on `org-element-at-point'.
24712 (and (save-excursion (beginning-of-line)
24713 (and (let ((case-fold-search t))
24714 (not (looking-at-p "\\*+ END[ \t]*$")))
24715 (let ((case-fold-search nil))
24716 (looking-at org-complex-heading-regexp))))
24717 (match-beginning 4)
24718 (>= (point) (match-beginning 4))
24719 (or (not (match-beginning 5))
24720 (< (point) (match-beginning 5))))
24721 (let* ((element (org-element-at-point))
24722 (post-affiliated (org-element-property :post-affiliated element)))
24723 (cond
24724 ;; Ignore checks in all affiliated keywords but captions.
24725 ((< (point) post-affiliated)
24726 (and (save-excursion
24727 (beginning-of-line)
24728 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24729 (> (point) (match-end 0))
24730 (org--flyspell-object-check-p element)))
24731 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24732 ((let ((log (org-log-into-drawer)))
24733 (and log
24734 (let ((drawer (org-element-lineage element '(drawer))))
24735 (and drawer
24736 (eq (compare-strings
24737 log nil nil
24738 (org-element-property :drawer-name drawer) nil nil t)
24739 t)))))
24740 nil)
24742 (cl-case (org-element-type element)
24743 ((comment quote-section) t)
24744 (comment-block
24745 ;; Allow checks between block markers, not on them.
24746 (and (> (line-beginning-position) post-affiliated)
24747 (save-excursion
24748 (end-of-line)
24749 (skip-chars-forward " \r\t\n")
24750 (< (point) (org-element-property :end element)))))
24751 ;; Arbitrary list of keywords where checks are meaningful.
24752 ;; Make sure point is on the value part of the element.
24753 (keyword
24754 (and (member (org-element-property :key element)
24755 '("DESCRIPTION" "TITLE"))
24756 (save-excursion
24757 (search-backward ":" (line-beginning-position) t))))
24758 ;; Check is globally allowed in paragraphs verse blocks and
24759 ;; table rows (after affiliated keywords) but some objects
24760 ;; must not be affected.
24761 ((paragraph table-row verse-block)
24762 (let ((cbeg (org-element-property :contents-begin element))
24763 (cend (org-element-property :contents-end element)))
24764 (and cbeg (>= (point) cbeg) (< (point) cend)
24765 (org--flyspell-object-check-p element))))))))))
24766 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24768 (defun org-remove-flyspell-overlays-in (beg end)
24769 "Remove flyspell overlays in region."
24770 (and (bound-and-true-p flyspell-mode)
24771 (fboundp 'flyspell-delete-region-overlays)
24772 (flyspell-delete-region-overlays beg end)))
24774 (defvar flyspell-delayed-commands)
24775 (eval-after-load "flyspell"
24776 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24778 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24779 (eval-after-load "bookmark"
24780 '(if (boundp 'bookmark-after-jump-hook)
24781 ;; We can use the hook
24782 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24783 ;; Hook not available, use advice
24784 (defadvice bookmark-jump (after org-make-visible activate)
24785 "Make the position visible."
24786 (org-bookmark-jump-unhide))))
24788 ;; Make sure saveplace shows the location if it was hidden
24789 (eval-after-load "saveplace"
24790 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24791 "Make the position visible."
24792 (org-bookmark-jump-unhide)))
24794 ;; Make sure ecb shows the location if it was hidden
24795 (eval-after-load "ecb"
24796 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24797 "Make hierarchy visible when jumping into location from ECB tree buffer."
24798 (when (derived-mode-p 'org-mode)
24799 (org-show-context))))
24801 (defun org-bookmark-jump-unhide ()
24802 "Unhide the current position, to show the bookmark location."
24803 (and (derived-mode-p 'org-mode)
24804 (or (org-invisible-p)
24805 (save-excursion (goto-char (max (point-min) (1- (point))))
24806 (org-invisible-p)))
24807 (org-show-context 'bookmark-jump)))
24809 (defun org-mark-jump-unhide ()
24810 "Make the point visible with `org-show-context' after jumping to the mark."
24811 (when (and (derived-mode-p 'org-mode)
24812 (org-invisible-p))
24813 (org-show-context 'mark-goto)))
24815 (eval-after-load "simple"
24816 '(defadvice pop-to-mark-command (after org-make-visible activate)
24817 "Make the point visible with `org-show-context'."
24818 (org-mark-jump-unhide)))
24820 (eval-after-load "simple"
24821 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24822 "Make the point visible with `org-show-context'."
24823 (org-mark-jump-unhide)))
24825 (eval-after-load "simple"
24826 '(defadvice pop-global-mark (after org-make-visible activate)
24827 "Make the point visible with `org-show-context'."
24828 (org-mark-jump-unhide)))
24830 ;; Make session.el ignore our circular variable
24831 (defvar session-globals-exclude)
24832 (eval-after-load "session"
24833 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24835 ;;;; Finish up
24837 (provide 'org)
24839 (run-hooks 'org-load-hook)
24841 ;;; org.el ends here