Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob861ce31db02eb397a2b1c899cb3af87c6bd2e6cf
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 (defcustom org-startup-folded t
919 "Non-nil means entering Org mode will switch to OVERVIEW.
921 This can also be configured on a per-file basis by adding one of
922 the following lines anywhere in the buffer:
924 #+STARTUP: fold (or `overview', this is equivalent)
925 #+STARTUP: nofold (or `showall', this is equivalent)
926 #+STARTUP: content
927 #+STARTUP: showeverything
929 Set `org-agenda-inhibit-startup' to a non-nil value if you want
930 to ignore this option when Org opens agenda files for the first
931 time."
932 :group 'org-startup
933 :type '(choice
934 (const :tag "nofold: show all" nil)
935 (const :tag "fold: overview" t)
936 (const :tag "content: all headlines" content)
937 (const :tag "show everything, even drawers" showeverything)))
939 (defcustom org-startup-truncated t
940 "Non-nil means entering Org mode will set `truncate-lines'.
941 This is useful since some lines containing links can be very long and
942 uninteresting. Also tables look terrible when wrapped.
944 The variable `org-startup-truncated' allows to configure
945 truncation for Org mode different to the other modes that use the
946 variable `truncate-lines' and as a shortcut instead of putting
947 the variable `truncate-lines' into the `org-mode-hook'. If one
948 wants to configure truncation for Org mode not statically but
949 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
950 the variable `truncate-lines' has to be used because in such a
951 case it is too late to set the variable `org-startup-truncated'."
952 :group 'org-startup
953 :type 'boolean)
955 (defcustom org-startup-indented nil
956 "Non-nil means turn on `org-indent-mode' on startup.
957 This can also be configured on a per-file basis by adding one of
958 the following lines anywhere in the buffer:
960 #+STARTUP: indent
961 #+STARTUP: noindent"
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Not" nil)
965 (const :tag "Globally (slow on startup in large files)" t)))
967 (defcustom org-use-sub-superscripts t
968 "Non-nil means interpret \"_\" and \"^\" for display.
970 If you want to control how Org exports those characters, see
971 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
972 used to be an alias for `org-export-with-sub-superscripts' in
973 Org <8.0, it is not anymore.
975 When this option is turned on, you can use TeX-like syntax for
976 sub- and superscripts within the buffer. Several characters after
977 \"_\" or \"^\" will be considered as a single item - so grouping
978 with {} is normally not needed. For example, the following things
979 will be parsed as single sub- or superscripts:
981 10^24 or 10^tau several digits will be considered 1 item.
982 10^-12 or 10^-tau a leading sign with digits or a word
983 x^2-y^3 will be read as x^2 - y^3, because items are
984 terminated by almost any nonword/nondigit char.
985 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
987 Still, ambiguity is possible. So when in doubt, use {} to enclose
988 the sub/superscript. If you set this variable to the symbol `{}',
989 the braces are *required* in order to trigger interpretations as
990 sub/superscript. This can be helpful in documents that need \"_\"
991 frequently in plain text."
992 :group 'org-startup
993 :version "24.4"
994 :package-version '(Org . "8.0")
995 :type '(choice
996 (const :tag "Always interpret" t)
997 (const :tag "Only with braces" {})
998 (const :tag "Never interpret" nil)))
1000 (defcustom org-startup-with-beamer-mode nil
1001 "Non-nil means turn on `org-beamer-mode' on startup.
1002 This can also be configured on a per-file basis by adding one of
1003 the following lines anywhere in the buffer:
1005 #+STARTUP: beamer"
1006 :group 'org-startup
1007 :version "24.1"
1008 :type 'boolean)
1010 (defcustom org-startup-align-all-tables nil
1011 "Non-nil means align all tables when visiting a file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-shrink-all-tables nil
1020 "Non-nil means shrink all table columns with a width cookie.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: shrink"
1024 :group 'org-startup
1025 :type 'boolean
1026 :version "27.1"
1027 :package-version '(Org . "9.2")
1028 :safe #'booleanp)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like shift-selection-mode'
1066 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1067 If you want to use Org mode together with one of these other modes,
1068 or more generally if you would like to move some Org mode commands to
1069 other keys, set this variable and configure the keys with the variable
1070 `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots. When a non-empty string,
1123 use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1133 (defvar org-display-table nil
1134 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car of each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "26.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defgroup org-sparse-trees nil
1657 "Options concerning sparse trees in Org mode."
1658 :tag "Org Sparse Trees"
1659 :group 'org-structure)
1661 (defcustom org-highlight-sparse-tree-matches t
1662 "Non-nil means highlight all matches that define a sparse tree.
1663 The highlights will automatically disappear the next time the buffer is
1664 changed by an edit command."
1665 :group 'org-sparse-trees
1666 :type 'boolean)
1668 (defcustom org-remove-highlights-with-change t
1669 "Non-nil means any change to the buffer will remove temporary highlights.
1670 \\<org-mode-map>\
1671 Such highlights are created by `org-occur' and `org-clock-display'.
1672 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1673 to get rid of the highlights.
1674 The highlights created by `org-toggle-latex-fragment' always need
1675 `\\[org-toggle-latex-fragment]' to be removed."
1676 :group 'org-sparse-trees
1677 :group 'org-time
1678 :type 'boolean)
1680 (defcustom org-occur-case-fold-search t
1681 "Non-nil means `org-occur' should be case-insensitive.
1682 If set to `smart' the search will be case-insensitive only if it
1683 doesn't specify any upper case character."
1684 :group 'org-sparse-trees
1685 :version "26.1"
1686 :type '(choice
1687 (const :tag "Case-sensitive" nil)
1688 (const :tag "Case-insensitive" t)
1689 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1691 (defcustom org-occur-hook '(org-first-headline-recenter)
1692 "Hook that is run after `org-occur' has constructed a sparse tree.
1693 This can be used to recenter the window to show as much of the structure
1694 as possible."
1695 :group 'org-sparse-trees
1696 :type 'hook)
1698 (defgroup org-table nil
1699 "Options concerning tables in Org mode."
1700 :tag "Org Table"
1701 :group 'org)
1703 (defcustom org-self-insert-cluster-for-undo nil
1704 "Non-nil means cluster self-insert commands for undo when possible.
1705 If this is set, then, like in the Emacs command loop, 20 consecutive
1706 characters will be undone together.
1707 This is configurable, because there is some impact on typing performance."
1708 :group 'org-table
1709 :type 'boolean)
1711 (defcustom org-table-tab-recognizes-table.el t
1712 "Non-nil means TAB will automatically notice a table.el table.
1713 When it sees such a table, it moves point into it and - if necessary -
1714 calls `table-recognize-table'."
1715 :group 'org-table-editing
1716 :type 'boolean)
1718 (defgroup org-link nil
1719 "Options concerning links in Org mode."
1720 :tag "Org Link"
1721 :group 'org)
1723 (defvar-local org-link-abbrev-alist-local nil
1724 "Buffer-local version of `org-link-abbrev-alist', which see.
1725 The value of this is taken from the #+LINK lines.")
1727 (defcustom org-link-parameters
1728 '(("doi" :follow org--open-doi-link)
1729 ("elisp" :follow org--open-elisp-link)
1730 ("file" :complete org-file-complete-link)
1731 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1732 ("help" :follow org--open-help-link)
1733 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1734 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1735 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1736 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1737 ("shell" :follow org--open-shell-link))
1738 "An alist of properties that defines all the links in Org mode.
1739 The key in each association is a string of the link type.
1740 Subsequent optional elements make up a p-list of link properties.
1742 :follow - A function that takes the link path as an argument.
1744 :export - A function that takes the link path, description and
1745 export-backend as arguments.
1747 :store - A function responsible for storing the link. See the
1748 function `org-store-link-functions'.
1750 :complete - A function that inserts a link with completion. The
1751 function takes one optional prefix arg.
1753 :face - A face for the link, or a function that returns a face.
1754 The function takes one argument which is the link path. The
1755 default face is `org-link'.
1757 :mouse-face - The mouse-face. The default is `highlight'.
1759 :display - `full' will not fold the link in descriptive
1760 display. Default is `org-link'.
1762 :help-echo - A string or function that takes (window object position)
1763 as arguments and returns a string.
1765 :keymap - A keymap that is active on the link. The default is
1766 `org-mouse-map'.
1768 :htmlize-link - A function for the htmlize-link. Defaults
1769 to (list :uri \"type:path\")
1771 :activate-func - A function to run at the end of font-lock
1772 activation. The function must accept (link-start link-end path bracketp)
1773 as arguments."
1774 :group 'org-link
1775 :type '(alist :tag "Link display parameters"
1776 :value-type plist)
1777 :version "26.1"
1778 :package-version '(Org . "9.1"))
1780 (defun org-link-get-parameter (type key)
1781 "Get TYPE link property for KEY.
1782 TYPE is a string and KEY is a plist keyword."
1783 (plist-get
1784 (cdr (assoc type org-link-parameters))
1785 key))
1787 (defun org-link-set-parameters (type &rest parameters)
1788 "Set link TYPE properties to PARAMETERS.
1789 PARAMETERS should be :key val pairs."
1790 (let ((data (assoc type org-link-parameters)))
1791 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1792 (push (cons type parameters) org-link-parameters)
1793 (org-make-link-regexps)
1794 (org-element-update-syntax))))
1796 (defun org-link-types ()
1797 "Return a list of known link types."
1798 (mapcar #'car org-link-parameters))
1800 (defcustom org-link-abbrev-alist nil
1801 "Alist of link abbreviations.
1802 The car of each element is a string, to be replaced at the start of a link.
1803 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1804 links in Org buffers can have an optional tag after a double colon, e.g.,
1806 [[linkkey:tag][description]]
1808 The `linkkey' must be a single word, starting with a letter, followed
1809 by letters, numbers, `-' or `_'.
1811 If REPLACE is a string, the tag will simply be appended to create the link.
1812 If the string contains \"%s\", the tag will be inserted there. If the string
1813 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1814 at that point (see the function `url-hexify-string'). If the string contains
1815 the specifier \"%(my-function)\", then the custom function `my-function' will
1816 be invoked: this function takes the tag as its only argument and must return
1817 a string.
1819 REPLACE may also be a function that will be called with the tag as the
1820 only argument to create the link, which should be returned as a string.
1822 See the manual for examples."
1823 :group 'org-link
1824 :type '(repeat
1825 (cons
1826 (string :tag "Protocol")
1827 (choice
1828 (string :tag "Format")
1829 (function)))))
1831 (defcustom org-descriptive-links t
1832 "Non-nil means Org will display descriptive links.
1833 E.g. [[http://orgmode.org][Org website]] will be displayed as
1834 \"Org Website\", hiding the link itself and just displaying its
1835 description. When set to nil, Org will display the full links
1836 literally.
1838 You can interactively set the value of this variable by calling
1839 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1840 :group 'org-link
1841 :type 'boolean)
1843 (defcustom org-link-file-path-type 'adaptive
1844 "How the path name in file links should be stored.
1845 Valid values are:
1847 relative Relative to the current directory, i.e. the directory of the file
1848 into which the link is being inserted.
1849 absolute Absolute path, if possible with ~ for home directory.
1850 noabbrev Absolute path, no abbreviation of home directory.
1851 adaptive Use relative path for files in the current directory and sub-
1852 directories of it. For other files, use an absolute path."
1853 :group 'org-link
1854 :type '(choice
1855 (const relative)
1856 (const absolute)
1857 (const noabbrev)
1858 (const adaptive)))
1860 (defvaralias 'org-activate-links 'org-highlight-links)
1861 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1862 "Types of links that should be highlighted in Org files.
1864 This is a list of symbols, each one of them leading to the
1865 highlighting of a certain link type.
1867 You can still open links that are not highlighted.
1869 In principle, it does not hurt to turn on highlighting for all
1870 link types. There may be a small gain when turning off unused
1871 link types. The types are:
1873 bracket The recommended [[link][description]] or [[link]] links with hiding.
1874 angle Links in angular brackets that may contain whitespace like
1875 <bbdb:Carsten Dominik>.
1876 plain Plain links in normal text, no whitespace, like http://google.com.
1877 radio Text that is matched by a radio target, see manual for details.
1878 tag Tag settings in a headline (link to tag search).
1879 date Time stamps (link to calendar).
1880 footnote Footnote labels.
1882 If you set this variable during an Emacs session, use `org-mode-restart'
1883 in the Org buffer so that the change takes effect."
1884 :group 'org-link
1885 :group 'org-appearance
1886 :type '(set :greedy t
1887 (const :tag "Double bracket links" bracket)
1888 (const :tag "Angular bracket links" angle)
1889 (const :tag "Plain text links" plain)
1890 (const :tag "Radio target matches" radio)
1891 (const :tag "Tags" tag)
1892 (const :tag "Timestamps" date)
1893 (const :tag "Footnotes" footnote)))
1895 (defcustom org-make-link-description-function nil
1896 "Function to use for generating link descriptions from links.
1897 This function must take two parameters: the first one is the
1898 link, the second one is the description generated by
1899 `org-insert-link'. The function should return the description to
1900 use."
1901 :group 'org-link
1902 :type '(choice (const nil) (function)))
1904 (defgroup org-link-store nil
1905 "Options concerning storing links in Org mode."
1906 :tag "Org Store Link"
1907 :group 'org-link)
1909 (defcustom org-url-hexify-p t
1910 "When non-nil, hexify URL when creating a link."
1911 :type 'boolean
1912 :version "24.3"
1913 :group 'org-link-store)
1915 (defcustom org-email-link-description-format "Email %c: %.30s"
1916 "Format of the description part of a link to an email or usenet message.
1917 The following %-escapes will be replaced by corresponding information:
1919 %F full \"From\" field
1920 %f name, taken from \"From\" field, address if no name
1921 %T full \"To\" field
1922 %t first name in \"To\" field, address if no name
1923 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1924 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1925 %s subject
1926 %d date
1927 %m message-id.
1929 You may use normal field width specification between the % and the letter.
1930 This is for example useful to limit the length of the subject.
1932 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1933 :group 'org-link-store
1934 :type 'string)
1936 (defcustom org-from-is-user-regexp
1937 (let (r1 r2)
1938 (when (and user-mail-address (not (string= user-mail-address "")))
1939 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1940 (when (and user-full-name (not (string= user-full-name "")))
1941 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1942 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1943 "Regexp matched against the \"From:\" header of an email or usenet message.
1944 It should match if the message is from the user him/herself."
1945 :group 'org-link-store
1946 :type 'regexp)
1948 (defcustom org-context-in-file-links t
1949 "Non-nil means file links from `org-store-link' contain context.
1950 \\<org-mode-map>
1951 A search string will be added to the file name with :: as separator
1952 and used to find the context when the link is activated by the command
1953 `org-open-at-point'. When this option is t, the entire active region
1954 will be placed in the search string of the file link. If set to a
1955 positive integer, only the first n lines of context will be stored.
1957 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1958 \\[org-store-link]')
1959 negates this setting for the duration of the command."
1960 :group 'org-link-store
1961 :type '(choice boolean integer))
1963 (defcustom org-keep-stored-link-after-insertion nil
1964 "Non-nil means keep link in list for entire session.
1965 \\<org-mode-map>
1966 The command `org-store-link' adds a link pointing to the current
1967 location to an internal list. These links accumulate during a session.
1968 The command `org-insert-link' can be used to insert links into any
1969 Org file (offering completion for all stored links).
1971 When this option is nil, every link which has been inserted once using
1972 `\\[org-insert-link]' will be removed from the list, to make completing the \
1973 unused
1974 links more efficient."
1975 :group 'org-link-store
1976 :type 'boolean)
1978 (defgroup org-link-follow nil
1979 "Options concerning following links in Org mode."
1980 :tag "Org Follow Link"
1981 :group 'org-link)
1983 (defcustom org-link-translation-function nil
1984 "Function to translate links with different syntax to Org syntax.
1985 This can be used to translate links created for example by the Planner
1986 or emacs-wiki packages to Org syntax.
1987 The function must accept two parameters, a TYPE containing the link
1988 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1989 which is everything after the link protocol. It should return a cons
1990 with possibly modified values of type and path.
1991 Org contains a function for this, so if you set this variable to
1992 `org-translate-link-from-planner', you should be able follow many
1993 links created by planner."
1994 :group 'org-link-follow
1995 :type '(choice (const nil) (function)))
1997 (defcustom org-follow-link-hook nil
1998 "Hook that is run after a link has been followed."
1999 :group 'org-link-follow
2000 :type 'hook)
2002 (defcustom org-tab-follows-link nil
2003 "Non-nil means on links TAB will follow the link.
2004 Needs to be set before org.el is loaded.
2005 This really should not be used, it does not make sense, and the
2006 implementation is bad."
2007 :group 'org-link-follow
2008 :type 'boolean)
2010 (defcustom org-return-follows-link nil
2011 "Non-nil means on links RET will follow the link.
2012 In tables, the special behavior of RET has precedence."
2013 :group 'org-link-follow
2014 :type 'boolean)
2016 (defcustom org-mouse-1-follows-link
2017 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2018 "Non-nil means mouse-1 on a link will follow the link.
2019 A longer mouse click will still set point. Needs to be set
2020 before org.el is loaded."
2021 :group 'org-link-follow
2022 :version "26.1"
2023 :package-version '(Org . "8.3")
2024 :type '(choice
2025 (const :tag "A double click follows the link" double)
2026 (const :tag "Unconditionally follow the link with mouse-1" t)
2027 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2029 (defcustom org-mark-ring-length 4
2030 "Number of different positions to be recorded in the ring.
2031 Changing this requires a restart of Emacs to work correctly."
2032 :group 'org-link-follow
2033 :type 'integer)
2035 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2036 "Non-nil means internal fuzzy links can only match headlines.
2038 When nil, the a fuzzy link may point to a target or a named
2039 construct in the document. When set to the special value
2040 `query-to-create', offer to create a new headline when none
2041 matched.
2043 Spaces and statistics cookies are ignored during heading searches."
2044 :group 'org-link-follow
2045 :version "24.1"
2046 :type '(choice
2047 (const :tag "Use fuzzy text search" nil)
2048 (const :tag "Match only exact headline" t)
2049 (const :tag "Match exact headline or query to create it"
2050 query-to-create))
2051 :safe #'symbolp)
2053 (defcustom org-link-frame-setup
2054 '((vm . vm-visit-folder-other-frame)
2055 (vm-imap . vm-visit-imap-folder-other-frame)
2056 (gnus . org-gnus-no-new-news)
2057 (file . find-file-other-window)
2058 (wl . wl-other-frame))
2059 "Setup the frame configuration for following links.
2060 When following a link with Emacs, it may often be useful to display
2061 this link in another window or frame. This variable can be used to
2062 set this up for the different types of links.
2063 For VM, use any of
2064 `vm-visit-folder'
2065 `vm-visit-folder-other-window'
2066 `vm-visit-folder-other-frame'
2067 For Gnus, use any of
2068 `gnus'
2069 `gnus-other-frame'
2070 `org-gnus-no-new-news'
2071 For FILE, use any of
2072 `find-file'
2073 `find-file-other-window'
2074 `find-file-other-frame'
2075 For Wanderlust use any of
2076 `wl'
2077 `wl-other-frame'
2078 For the calendar, use the variable `calendar-setup'.
2079 For BBDB, it is currently only possible to display the matches in
2080 another window."
2081 :group 'org-link-follow
2082 :type '(list
2083 (cons (const vm)
2084 (choice
2085 (const vm-visit-folder)
2086 (const vm-visit-folder-other-window)
2087 (const vm-visit-folder-other-frame)))
2088 (cons (const vm-imap)
2089 (choice
2090 (const vm-visit-imap-folder)
2091 (const vm-visit-imap-folder-other-window)
2092 (const vm-visit-imap-folder-other-frame)))
2093 (cons (const gnus)
2094 (choice
2095 (const gnus)
2096 (const gnus-other-frame)
2097 (const org-gnus-no-new-news)))
2098 (cons (const file)
2099 (choice
2100 (const find-file)
2101 (const find-file-other-window)
2102 (const find-file-other-frame)))
2103 (cons (const wl)
2104 (choice
2105 (const wl)
2106 (const wl-other-frame)))))
2108 (defcustom org-display-internal-link-with-indirect-buffer nil
2109 "Non-nil means use indirect buffer to display infile links.
2110 Activating internal links (from one location in a file to another location
2111 in the same file) normally just jumps to the location. When the link is
2112 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2113 is displayed in
2114 another window. When this option is set, the other window actually displays
2115 an indirect buffer clone of the current buffer, to avoid any visibility
2116 changes to the current buffer."
2117 :group 'org-link-follow
2118 :type 'boolean)
2120 (defcustom org-open-non-existing-files nil
2121 "Non-nil means `org-open-file' will open non-existing files.
2122 When nil, an error will be generated.
2123 This variable applies only to external applications because they
2124 might choke on non-existing files. If the link is to a file that
2125 will be opened in Emacs, the variable is ignored."
2126 :group 'org-link-follow
2127 :type 'boolean)
2129 (defcustom org-open-directory-means-index-dot-org nil
2130 "Non-nil means a link to a directory really means to index.org.
2131 When nil, following a directory link will run dired or open a finder/explorer
2132 window on that directory."
2133 :group 'org-link-follow
2134 :type 'boolean)
2136 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2137 "Non-nil means ask for confirmation before executing shell links.
2138 Shell links can be dangerous: just think about a link
2140 [[shell:rm -rf ~/*][Google Search]]
2142 This link would show up in your Org document as \"Google Search\",
2143 but really it would remove your entire home directory.
2144 Therefore we advise against setting this variable to nil.
2145 Just change it to `y-or-n-p' if you want to confirm with a
2146 single keystroke rather than having to type \"yes\"."
2147 :group 'org-link-follow
2148 :type '(choice
2149 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2150 (const :tag "with y-or-n (faster)" y-or-n-p)
2151 (const :tag "no confirmation (dangerous)" nil)))
2152 (put 'org-confirm-shell-link-function
2153 'safe-local-variable
2154 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2156 (defcustom org-confirm-shell-link-not-regexp ""
2157 "A regexp to skip confirmation for shell links."
2158 :group 'org-link-follow
2159 :version "24.1"
2160 :type 'regexp)
2162 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2164 Elisp links can be dangerous: just think about a link
2166 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-elisp-link-not-regexp ""
2183 "A regexp to skip confirmation for Elisp links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defconst org-file-apps-defaults-gnu
2189 '((remote . emacs)
2190 (system . mailcap)
2191 (t . mailcap))
2192 "Default file applications on a UNIX or GNU/Linux system.
2193 See `org-file-apps'.")
2195 (defconst org-file-apps-defaults-macosx
2196 '((remote . emacs)
2197 (system . "open %s")
2198 ("ps.gz" . "gv %s")
2199 ("eps.gz" . "gv %s")
2200 ("dvi" . "xdvi %s")
2201 ("fig" . "xfig %s")
2202 (t . "open %s"))
2203 "Default file applications on a macOS system.
2204 The system \"open\" is known as a default, but we use X11 applications
2205 for some files for which the OS does not have a good default.
2206 See `org-file-apps'.")
2208 (defconst org-file-apps-defaults-windowsnt
2209 (list '(remote . emacs)
2210 (cons 'system (lambda (file _path)
2211 (with-no-warnings (w32-shell-execute "open" file))))
2212 (cons t (lambda (file _path)
2213 (with-no-warnings (w32-shell-execute "open" file)))))
2214 "Default file applications on a Windows NT system.
2215 The system \"open\" is used for most files.
2216 See `org-file-apps'.")
2218 (defcustom org-file-apps
2219 '((auto-mode . emacs)
2220 ("\\.mm\\'" . default)
2221 ("\\.x?html?\\'" . default)
2222 ("\\.pdf\\'" . default))
2223 "External applications for opening `file:path' items in a document.
2224 \\<org-mode-map>\
2226 Org mode uses system defaults for different file types, but
2227 you can use this variable to set the application for a given file
2228 extension. The entries in this list are cons cells where the car identifies
2229 files and the cdr the corresponding command.
2231 Possible values for the file identifier are:
2233 \"string\" A string as a file identifier can be interpreted in different
2234 ways, depending on its contents:
2236 - Alphanumeric characters only:
2237 Match links with this file extension.
2238 Example: (\"pdf\" . \"evince %s\")
2239 to open PDFs with evince.
2241 - Regular expression: Match links where the
2242 filename matches the regexp. If you want to
2243 use groups here, use shy groups.
2245 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2246 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2247 to open *.html and *.xhtml with firefox.
2249 - Regular expression which contains (non-shy) groups:
2250 Match links where the whole link, including \"::\", and
2251 anything after that, matches the regexp.
2252 In a custom command string, %1, %2, etc. are replaced with
2253 the parts of the link that were matched by the groups.
2254 For backwards compatibility, if a command string is given
2255 that does not use any of the group matches, this case is
2256 handled identically to the second one (i.e. match against
2257 file name only).
2258 In a custom function, you can access the group matches with
2259 (match-string n link).
2261 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2262 \"evince -p %1 %s\")
2263 to open [[file:document.pdf::5]] with evince at page 5.
2265 `directory' Matches a directory
2266 `remote' Matches a remote file, accessible through tramp or efs.
2267 Remote files most likely should be visited through Emacs
2268 because external applications cannot handle such paths.
2269 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2270 so all files Emacs knows how to handle. Using this with
2271 command `emacs' will open most files in Emacs. Beware that this
2272 will also open html files inside Emacs, unless you add
2273 (\"html\" . default) to the list as well.
2274 `system' The system command to open files, like `open' on Windows
2275 and macOS, and mailcap under GNU/Linux. This is the command
2276 that will be selected if you call `org-open-at-point' with a
2277 double prefix argument (`\\[universal-argument] \
2278 \\[universal-argument] \\[org-open-at-point]').
2279 t Default for files not matched by any of the other options.
2281 Possible values for the command are:
2283 `emacs' The file will be visited by the current Emacs process.
2284 `default' Use the default application for this file type, which is the
2285 association for t in the list, most likely in the system-specific
2286 part. This can be used to overrule an unwanted setting in the
2287 system-specific variable.
2288 `system' Use the system command for opening files, like \"open\".
2289 This command is specified by the entry whose car is `system'.
2290 Most likely, the system-specific version of this variable
2291 does define this command, but you can overrule/replace it
2292 here.
2293 `mailcap' Use command specified in the mailcaps.
2294 string A command to be executed by a shell; %s will be replaced
2295 by the path to the file.
2296 function A Lisp function, which will be called with two arguments:
2297 the file path and the original link string, without the
2298 \"file:\" prefix.
2300 For more examples, see the system specific constants
2301 `org-file-apps-defaults-macosx'
2302 `org-file-apps-defaults-windowsnt'
2303 `org-file-apps-defaults-gnu'."
2304 :group 'org-link-follow
2305 :type '(repeat
2306 (cons (choice :value ""
2307 (string :tag "Extension")
2308 (const :tag "System command to open files" system)
2309 (const :tag "Default for unrecognized files" t)
2310 (const :tag "Remote file" remote)
2311 (const :tag "Links to a directory" directory)
2312 (const :tag "Any files that have Emacs modes"
2313 auto-mode))
2314 (choice :value ""
2315 (const :tag "Visit with Emacs" emacs)
2316 (const :tag "Use default" default)
2317 (const :tag "Use the system command" system)
2318 (string :tag "Command")
2319 (function :tag "Function")))))
2321 (defcustom org-doi-server-url "http://dx.doi.org/"
2322 "The URL of the DOI server."
2323 :type 'string
2324 :version "24.3"
2325 :group 'org-link-follow)
2327 (defgroup org-refile nil
2328 "Options concerning refiling entries in Org mode."
2329 :tag "Org Refile"
2330 :group 'org)
2332 (defcustom org-directory "~/org"
2333 "Directory with Org files.
2334 This is just a default location to look for Org files. There is no need
2335 at all to put your files into this directory. It is used in the
2336 following situations:
2338 1. When a capture template specifies a target file that is not an
2339 absolute path. The path will then be interpreted relative to
2340 `org-directory'
2341 2. When the value of variable `org-agenda-files' is a single file, any
2342 relative paths in this file will be taken as relative to
2343 `org-directory'."
2344 :group 'org-refile
2345 :group 'org-capture
2346 :type 'directory)
2348 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2349 "Default target for storing notes.
2350 Used as a fall back file for org-capture.el, for templates that
2351 do not specify a target file."
2352 :group 'org-refile
2353 :group 'org-capture
2354 :type 'file)
2356 (defcustom org-reverse-note-order nil
2357 "Non-nil means store new notes at the beginning of a file or entry.
2358 When nil, new notes will be filed to the end of a file or entry.
2359 This can also be a list with cons cells of regular expressions that
2360 are matched against file names, and values."
2361 :group 'org-capture
2362 :group 'org-refile
2363 :type '(choice
2364 (const :tag "Reverse always" t)
2365 (const :tag "Reverse never" nil)
2366 (repeat :tag "By file name regexp"
2367 (cons regexp boolean))))
2369 (defcustom org-log-refile nil
2370 "Information to record when a task is refiled.
2372 Possible values are:
2374 nil Don't add anything
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologrefile
2381 #+STARTUP: logrefile
2382 #+STARTUP: lognoterefile
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords.
2387 When bulk-refiling from the agenda, the value `note' is forbidden and
2388 will temporarily be changed to `time'."
2389 :group 'org-refile
2390 :group 'org-progress
2391 :version "24.1"
2392 :type '(choice
2393 (const :tag "No logging" nil)
2394 (const :tag "Record timestamp" time)
2395 (const :tag "Record timestamp with note." note)))
2397 (defcustom org-refile-targets nil
2398 "Targets for refiling entries with `\\[org-refile]'.
2399 This is a list of cons cells. Each cell contains:
2400 - a specification of the files to be considered, either a list of files,
2401 or a symbol whose function or variable value will be used to retrieve
2402 a file name or a list of file names. If you use `org-agenda-files' for
2403 that, all agenda files will be scanned for targets. Nil means consider
2404 headings in the current buffer.
2405 - A specification of how to find candidate refile targets. This may be
2406 any of:
2407 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2408 This tag has to be present in all target headlines, inheritance will
2409 not be considered.
2410 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2411 todo keyword.
2412 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2413 headlines that are refiling targets.
2414 - a cons cell (:level . N). Any headline of level N is considered a target.
2415 Note that, when `org-odd-levels-only' is set, level corresponds to
2416 order in hierarchy, not to the number of stars.
2417 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2418 Note that, when `org-odd-levels-only' is set, level corresponds to
2419 order in hierarchy, not to the number of stars.
2421 Each element of this list generates a set of possible targets.
2422 The union of these sets is presented (with completion) to
2423 the user by `org-refile'.
2425 You can set the variable `org-refile-target-verify-function' to a function
2426 to verify each headline found by the simple criteria above.
2428 When this variable is nil, all top-level headlines in the current buffer
2429 are used, equivalent to the value `((nil . (:level . 1))'."
2430 :group 'org-refile
2431 :type '(repeat
2432 (cons
2433 (choice :value org-agenda-files
2434 (const :tag "All agenda files" org-agenda-files)
2435 (const :tag "Current buffer" nil)
2436 (function) (variable) (file))
2437 (choice :tag "Identify target headline by"
2438 (cons :tag "Specific tag" (const :value :tag) (string))
2439 (cons :tag "TODO keyword" (const :value :todo) (string))
2440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2441 (cons :tag "Level number" (const :value :level) (integer))
2442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2444 (defcustom org-refile-target-verify-function nil
2445 "Function to verify if the headline at point should be a refile target.
2446 The function will be called without arguments, with point at the
2447 beginning of the headline. It should return t and leave point
2448 where it is if the headline is a valid target for refiling.
2450 If the target should not be selected, the function must return nil.
2451 In addition to this, it may move point to a place from where the search
2452 should be continued. For example, the function may decide that the entire
2453 subtree of the current entry should be excluded and move point to the end
2454 of the subtree."
2455 :group 'org-refile
2456 :type '(choice
2457 (const nil)
2458 (function)))
2460 (defcustom org-refile-use-cache nil
2461 "Non-nil means cache refile targets to speed up the process.
2462 \\<org-mode-map>\
2463 The cache for a particular file will be updated automatically when
2464 the buffer has been killed, or when any of the marker used for flagging
2465 refile targets no longer points at a live buffer.
2466 If you have added new entries to a buffer that might themselves be targets,
2467 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2468 if you find that easier, \
2469 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2470 \\[org-refile]'."
2471 :group 'org-refile
2472 :version "24.1"
2473 :type 'boolean)
2475 (defcustom org-refile-use-outline-path nil
2476 "Non-nil means provide refile targets as paths.
2477 So a level 3 headline will be available as level1/level2/level3.
2479 When the value is `file', also include the file name (without directory)
2480 into the path. In this case, you can also stop the completion after
2481 the file name, to get entries inserted as top level in the file.
2483 When `full-file-path', include the full file path.
2485 When `buffer-name', use the buffer name."
2486 :group 'org-refile
2487 :type '(choice
2488 (const :tag "Not" nil)
2489 (const :tag "Yes" t)
2490 (const :tag "Start with file name" file)
2491 (const :tag "Start with full file path" full-file-path)
2492 (const :tag "Start with buffer name" buffer-name)))
2494 (defcustom org-outline-path-complete-in-steps t
2495 "Non-nil means complete the outline path in hierarchical steps.
2496 When Org uses the refile interface to select an outline path (see
2497 `org-refile-use-outline-path'), the completion of the path can be
2498 done in a single go, or it can be done in steps down the headline
2499 hierarchy. Going in steps is probably the best if you do not use
2500 a special completion package like `ido' or `icicles'. However,
2501 when using these packages, going in one step can be very fast,
2502 while still showing the whole path to the entry."
2503 :group 'org-refile
2504 :type 'boolean)
2506 (defcustom org-refile-allow-creating-parent-nodes nil
2507 "Non-nil means allow the creation of new nodes as refile targets.
2508 New nodes are then created by adding \"/new node name\" to the completion
2509 of an existing node. When the value of this variable is `confirm',
2510 new node creation must be confirmed by the user (recommended).
2511 When nil, the completion must match an existing entry.
2513 Note that, if the new heading is not seen by the criteria
2514 listed in `org-refile-targets', multiple instances of the same
2515 heading would be created by trying again to file under the new
2516 heading."
2517 :group 'org-refile
2518 :type '(choice
2519 (const :tag "Never" nil)
2520 (const :tag "Always" t)
2521 (const :tag "Prompt for confirmation" confirm)))
2523 (defcustom org-refile-active-region-within-subtree nil
2524 "Non-nil means also refile active region within a subtree.
2526 By default `org-refile' doesn't allow refiling regions if they
2527 don't contain a set of subtrees, but it might be convenient to
2528 do so sometimes: in that case, the first line of the region is
2529 converted to a headline before refiling."
2530 :group 'org-refile
2531 :version "24.1"
2532 :type 'boolean)
2534 (defgroup org-todo nil
2535 "Options concerning TODO items in Org mode."
2536 :tag "Org TODO"
2537 :group 'org)
2539 (defgroup org-progress nil
2540 "Options concerning Progress logging in Org mode."
2541 :tag "Org Progress"
2542 :group 'org-time)
2544 (defvar org-todo-interpretation-widgets
2545 '((:tag "Sequence (cycling hits every state)" sequence)
2546 (:tag "Type (cycling directly to DONE)" type))
2547 "The available interpretation symbols for customizing `org-todo-keywords'.
2548 Interested libraries should add to this list.")
2550 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2551 "List of TODO entry keyword sequences and their interpretation.
2552 \\<org-mode-map>This is a list of sequences.
2554 Each sequence starts with a symbol, either `sequence' or `type',
2555 indicating if the keywords should be interpreted as a sequence of
2556 action steps, or as different types of TODO items. The first
2557 keywords are states requiring action - these states will select a headline
2558 for inclusion into the global TODO list Org produces. If one of the
2559 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2560 signify that no further action is necessary. If \"|\" is not found,
2561 the last keyword is treated as the only DONE state of the sequence.
2563 The command `\\[org-todo]' cycles an entry through these states, and one
2564 additional state where no keyword is present. For details about this
2565 cycling, see the manual.
2567 TODO keywords and interpretation can also be set on a per-file basis with
2568 the special #+SEQ_TODO and #+TYP_TODO lines.
2570 Each keyword can optionally specify a character for fast state selection
2571 \(in combination with the variable `org-use-fast-todo-selection')
2572 and specifiers for state change logging, using the same syntax that
2573 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2574 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2575 indicates to record a time stamp each time this state is selected.
2577 Each keyword may also specify if a timestamp or a note should be
2578 recorded when entering or leaving the state, by adding additional
2579 characters in the parenthesis after the keyword. This looks like this:
2580 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2581 record only the time of the state change. With X and Y being either
2582 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2583 Y when leaving the state if and only if the *target* state does not
2584 define X. You may omit any of the fast-selection key or X or /Y,
2585 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2587 For backward compatibility, this variable may also be just a list
2588 of keywords. In this case the interpretation (sequence or type) will be
2589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2590 :group 'org-todo
2591 :group 'org-keywords
2592 :type '(choice
2593 (repeat :tag "Old syntax, just keywords"
2594 (string :tag "Keyword"))
2595 (repeat :tag "New syntax"
2596 (cons
2597 (choice
2598 :tag "Interpretation"
2599 ;;Quick and dirty way to see
2600 ;;`org-todo-interpretations'. This takes the
2601 ;;place of item arguments
2602 :convert-widget
2603 (lambda (widget)
2604 (widget-put widget
2605 :args (mapcar
2606 (lambda (x)
2607 (widget-convert
2608 (cons 'const x)))
2609 org-todo-interpretation-widgets))
2610 widget))
2611 (repeat
2612 (string :tag "Keyword"))))))
2614 (defvar-local org-todo-keywords-1 nil
2615 "All TODO and DONE keywords active in a buffer.")
2616 (defvar org-todo-keywords-for-agenda nil)
2617 (defvar org-done-keywords-for-agenda nil)
2618 (defvar org-todo-keyword-alist-for-agenda nil)
2619 (defvar org-tag-alist-for-agenda nil
2620 "Alist of all tags from all agenda files.")
2621 (defvar org-tag-groups-alist-for-agenda nil
2622 "Alist of all groups tags from all current agenda files.")
2623 (defvar-local org-tag-groups-alist nil)
2624 (defvar org-agenda-contributing-files nil)
2625 (defvar-local org-current-tag-alist nil
2626 "Alist of all tag groups in current buffer.
2627 This variable takes into consideration `org-tag-alist',
2628 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2629 (defvar-local org-not-done-keywords nil)
2630 (defvar-local org-done-keywords nil)
2631 (defvar-local org-todo-heads nil)
2632 (defvar-local org-todo-sets nil)
2633 (defvar-local org-todo-log-states nil)
2634 (defvar-local org-todo-kwd-alist nil)
2635 (defvar-local org-todo-key-alist nil)
2636 (defvar-local org-todo-key-trigger nil)
2638 (defcustom org-todo-interpretation 'sequence
2639 "Controls how TODO keywords are interpreted.
2640 This variable is in principle obsolete and is only used for
2641 backward compatibility, if the interpretation of todo keywords is
2642 not given already in `org-todo-keywords'. See that variable for
2643 more information."
2644 :group 'org-todo
2645 :group 'org-keywords
2646 :type '(choice (const sequence)
2647 (const type)))
2649 (defcustom org-use-fast-todo-selection t
2650 "\\<org-mode-map>\
2651 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2652 This variable describes if and under what circumstances the cycling
2653 mechanism for TODO keywords will be replaced by a single-key, direct
2654 selection scheme.
2656 When nil, fast selection is never used.
2658 When the symbol `prefix', it will be used when `org-todo' is called
2659 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2660 in an Org buffer, and
2661 `\\[universal-argument] t' in an agenda buffer.
2663 When t, fast selection is used by default. In this case, the prefix
2664 argument forces cycling instead.
2666 In all cases, the special interface is only used if access keys have
2667 actually been assigned by the user, i.e. if keywords in the configuration
2668 are followed by a letter in parenthesis, like TODO(t)."
2669 :group 'org-todo
2670 :type '(choice
2671 (const :tag "Never" nil)
2672 (const :tag "By default" t)
2673 (const :tag "Only with C-u C-c C-t" prefix)))
2675 (defcustom org-provide-todo-statistics t
2676 "Non-nil means update todo statistics after insert and toggle.
2677 ALL-HEADLINES means update todo statistics by including headlines
2678 with no TODO keyword as well, counting them as not done.
2679 A list of TODO keywords means the same, but skip keywords that are
2680 not in this list.
2681 When set to a list of two lists, the first list contains keywords
2682 to consider as TODO keywords, the second list contains keywords
2683 to consider as DONE keywords.
2685 When this is set, todo statistics is updated in the parent of the
2686 current entry each time a todo state is changed."
2687 :group 'org-todo
2688 :type '(choice
2689 (const :tag "Yes, only for TODO entries" t)
2690 (const :tag "Yes, including all entries" all-headlines)
2691 (repeat :tag "Yes, for TODOs in this list"
2692 (string :tag "TODO keyword"))
2693 (list :tag "Yes, for TODOs and DONEs in these lists"
2694 (repeat (string :tag "TODO keyword"))
2695 (repeat (string :tag "DONE keyword")))
2696 (other :tag "No TODO statistics" nil)))
2698 (defcustom org-hierarchical-todo-statistics t
2699 "Non-nil means TODO statistics covers just direct children.
2700 When nil, all entries in the subtree are considered.
2701 This has only an effect if `org-provide-todo-statistics' is set.
2702 To set this to nil for only a single subtree, use a COOKIE_DATA
2703 property and include the word \"recursive\" into the value."
2704 :group 'org-todo
2705 :type 'boolean)
2707 (defcustom org-after-todo-state-change-hook nil
2708 "Hook which is run after the state of a TODO item was changed.
2709 The new state (a string with a TODO keyword, or nil) is available in the
2710 Lisp variable `org-state'."
2711 :group 'org-todo
2712 :type 'hook)
2714 (defvar org-blocker-hook nil
2715 "Hook for functions that are allowed to block a state change.
2717 Functions in this hook should not modify the buffer.
2718 Each function gets as its single argument a property list,
2719 see `org-trigger-hook' for more information about this list.
2721 If any of the functions in this hook returns nil, the state change
2722 is blocked.")
2724 (defvar org-trigger-hook nil
2725 "Hook for functions that are triggered by a state change.
2727 Each function gets as its single argument a property list with at
2728 least the following elements:
2730 (:type type-of-change :position pos-at-entry-start
2731 :from old-state :to new-state)
2733 Depending on the type, more properties may be present.
2735 This mechanism is currently implemented for:
2737 TODO state changes
2738 ------------------
2739 :type todo-state-change
2740 :from previous state (keyword as a string), or nil, or a symbol
2741 `todo' or `done', to indicate the general type of state.
2742 :to new state, like in :from")
2744 (defcustom org-enforce-todo-dependencies nil
2745 "Non-nil means undone TODO entries will block switching the parent to DONE.
2746 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2747 be blocked if any prior sibling is not yet done.
2748 Finally, if the parent is blocked because of ordered siblings of its own,
2749 the child will also be blocked."
2750 :set (lambda (var val)
2751 (set var val)
2752 (if val
2753 (add-hook 'org-blocker-hook
2754 'org-block-todo-from-children-or-siblings-or-parent)
2755 (remove-hook 'org-blocker-hook
2756 'org-block-todo-from-children-or-siblings-or-parent)))
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-enforce-todo-checkbox-dependencies nil
2761 "Non-nil means unchecked boxes will block switching the parent to DONE.
2762 When this is nil, checkboxes have no influence on switching TODO states.
2763 When non-nil, you first need to check off all check boxes before the TODO
2764 entry can be switched to DONE.
2765 This variable needs to be set before org.el is loaded, and you need to
2766 restart Emacs after a change to make the change effective. The only way
2767 to change is while Emacs is running is through the customize interface."
2768 :set (lambda (var val)
2769 (set var val)
2770 (if val
2771 (add-hook 'org-blocker-hook
2772 'org-block-todo-from-checkboxes)
2773 (remove-hook 'org-blocker-hook
2774 'org-block-todo-from-checkboxes)))
2775 :group 'org-todo
2776 :type 'boolean)
2778 (defcustom org-treat-insert-todo-heading-as-state-change nil
2779 "Non-nil means inserting a TODO heading is treated as state change.
2780 So when the command `\\[org-insert-todo-heading]' is used, state change
2781 logging will apply if appropriate. When nil, the new TODO item will
2782 be inserted directly, and no logging will take place."
2783 :group 'org-todo
2784 :type 'boolean)
2786 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2787 "Non-nil means switching TODO states with S-cursor counts as state change.
2788 This is the default behavior. However, setting this to nil allows a
2789 convenient way to select a TODO state and bypass any logging associated
2790 with that."
2791 :group 'org-todo
2792 :type 'boolean)
2794 (defcustom org-todo-state-tags-triggers nil
2795 "Tag changes that should be triggered by TODO state changes.
2796 This is a list. Each entry is
2798 (state-change (tag . flag) .......)
2800 State-change can be a string with a state, and empty string to indicate the
2801 state that has no TODO keyword, or it can be one of the symbols `todo'
2802 or `done', meaning any not-done or done state, respectively."
2803 :group 'org-todo
2804 :group 'org-tags
2805 :type '(repeat
2806 (cons (choice :tag "When changing to"
2807 (const :tag "Not-done state" todo)
2808 (const :tag "Done state" done)
2809 (string :tag "State"))
2810 (repeat
2811 (cons :tag "Tag action"
2812 (string :tag "Tag")
2813 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2815 (defcustom org-log-done nil
2816 "Information to record when a task moves to the DONE state.
2818 Possible values are:
2820 nil Don't add anything, just change the keyword
2821 time Add a time stamp to the task
2822 note Prompt for a note and add it with template `org-log-note-headings'
2824 This option can also be set with on a per-file-basis with
2826 #+STARTUP: nologdone
2827 #+STARTUP: logdone
2828 #+STARTUP: lognotedone
2830 You can have local logging settings for a subtree by setting the LOGGING
2831 property to one or more of these keywords."
2832 :group 'org-todo
2833 :group 'org-progress
2834 :type '(choice
2835 (const :tag "No logging" nil)
2836 (const :tag "Record CLOSED timestamp" time)
2837 (const :tag "Record CLOSED timestamp with note." note)))
2839 ;; Normalize old uses of org-log-done.
2840 (cond
2841 ((eq org-log-done t) (setq org-log-done 'time))
2842 ((and (listp org-log-done) (memq 'done org-log-done))
2843 (setq org-log-done 'note)))
2845 (defcustom org-log-reschedule nil
2846 "Information to record when the scheduling date of a tasks is modified.
2848 Possible values are:
2850 nil Don't add anything, just change the date
2851 time Add a time stamp to the task
2852 note Prompt for a note and add it with template `org-log-note-headings'
2854 This option can also be set with on a per-file-basis with
2856 #+STARTUP: nologreschedule
2857 #+STARTUP: logreschedule
2858 #+STARTUP: lognotereschedule"
2859 :group 'org-todo
2860 :group 'org-progress
2861 :type '(choice
2862 (const :tag "No logging" nil)
2863 (const :tag "Record timestamp" time)
2864 (const :tag "Record timestamp with note." note)))
2866 (defcustom org-log-redeadline nil
2867 "Information to record when the deadline date of a tasks is modified.
2869 Possible values are:
2871 nil Don't add anything, just change the date
2872 time Add a time stamp to the task
2873 note Prompt for a note and add it with template `org-log-note-headings'
2875 This option can also be set with on a per-file-basis with
2877 #+STARTUP: nologredeadline
2878 #+STARTUP: logredeadline
2879 #+STARTUP: lognoteredeadline
2881 You can have local logging settings for a subtree by setting the LOGGING
2882 property to one or more of these keywords."
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type '(choice
2886 (const :tag "No logging" nil)
2887 (const :tag "Record timestamp" time)
2888 (const :tag "Record timestamp with note." note)))
2890 (defcustom org-log-note-clock-out nil
2891 "Non-nil means record a note when clocking out of an item.
2892 This can also be configured on a per-file basis by adding one of
2893 the following lines anywhere in the buffer:
2895 #+STARTUP: lognoteclock-out
2896 #+STARTUP: nolognoteclock-out"
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type 'boolean)
2901 (defcustom org-log-done-with-time t
2902 "Non-nil means the CLOSED time stamp will contain date and time.
2903 When nil, only the date will be recorded."
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-note-headings
2908 '((done . "CLOSING NOTE %t")
2909 (state . "State %-12s from %-12S %t")
2910 (note . "Note taken on %t")
2911 (reschedule . "Rescheduled from %S on %t")
2912 (delschedule . "Not scheduled, was %S on %t")
2913 (redeadline . "New deadline from %S on %t")
2914 (deldeadline . "Removed deadline, was %S on %t")
2915 (refile . "Refiled on %t")
2916 (clock-out . ""))
2917 "Headings for notes added to entries.
2919 The value is an alist, with the car being a symbol indicating the
2920 note context, and the cdr is the heading to be used. The heading
2921 may also be the empty string. The following placeholders can be
2922 used:
2924 %t a time stamp.
2925 %T an active time stamp instead the default inactive one
2926 %d a short-format time stamp.
2927 %D an active short-format time stamp.
2928 %s the new TODO state or time stamp (inactive), in double quotes.
2929 %S the old TODO state or time stamp (inactive), in double quotes.
2930 %u the user name.
2931 %U full user name.
2933 In fact, it is not a good idea to change the `state' entry,
2934 because Agenda Log mode depends on the format of these entries."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(list :greedy t
2938 (cons (const :tag "Heading when closing an item" done) string)
2939 (cons (const :tag
2940 "Heading when changing todo state (todo sequence only)"
2941 state) string)
2942 (cons (const :tag "Heading when just taking a note" note) string)
2943 (cons (const :tag "Heading when rescheduling" reschedule) string)
2944 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2945 (cons (const :tag "Heading when changing deadline" redeadline) string)
2946 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2947 (cons (const :tag "Heading when refiling" refile) string)
2948 (cons (const :tag "Heading when clocking out" clock-out) string)))
2950 (unless (assq 'note org-log-note-headings)
2951 (push '(note . "%t") org-log-note-headings))
2953 (defcustom org-log-into-drawer nil
2954 "Non-nil means insert state change notes and time stamps into a drawer.
2955 When nil, state changes notes will be inserted after the headline and
2956 any scheduling and clock lines, but not inside a drawer.
2958 The value of this variable should be the name of the drawer to use.
2959 LOGBOOK is proposed as the default drawer for this purpose, you can
2960 also set this to a string to define the drawer of your choice.
2962 A value of t is also allowed, representing \"LOGBOOK\".
2964 A value of t or nil can also be set with on a per-file-basis with
2966 #+STARTUP: logdrawer
2967 #+STARTUP: nologdrawer
2969 If this variable is set, `org-log-state-notes-insert-after-drawers'
2970 will be ignored.
2972 You can set the property LOG_INTO_DRAWER to overrule this setting for
2973 a subtree.
2975 Do not check directly this variable in a Lisp program. Call
2976 function `org-log-into-drawer' instead."
2977 :group 'org-todo
2978 :group 'org-progress
2979 :type '(choice
2980 (const :tag "Not into a drawer" nil)
2981 (const :tag "LOGBOOK" t)
2982 (string :tag "Other")))
2984 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2986 (defun org-log-into-drawer ()
2987 "Name of the log drawer, as a string, or nil.
2988 This is the value of `org-log-into-drawer'. However, if the
2989 current entry has or inherits a LOG_INTO_DRAWER property, it will
2990 be used instead of the default value."
2991 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2992 (cond ((equal p "nil") nil)
2993 ((equal p "t") "LOGBOOK")
2994 ((stringp p) p)
2995 (p "LOGBOOK")
2996 ((stringp org-log-into-drawer) org-log-into-drawer)
2997 (org-log-into-drawer "LOGBOOK"))))
2999 (defcustom org-log-state-notes-insert-after-drawers nil
3000 "Non-nil means insert state change notes after any drawers in entry.
3001 Only the drawers that *immediately* follow the headline and the
3002 deadline/scheduled line are skipped.
3003 When nil, insert notes right after the heading and perhaps the line
3004 with deadline/scheduling if present.
3006 This variable will have no effect if `org-log-into-drawer' is
3007 set."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type 'boolean)
3012 (defcustom org-log-states-order-reversed t
3013 "Non-nil means the latest state note will be directly after heading.
3014 When nil, the state change notes will be ordered according to time.
3016 This option can also be set with on a per-file-basis with
3018 #+STARTUP: logstatesreversed
3019 #+STARTUP: nologstatesreversed"
3020 :group 'org-todo
3021 :group 'org-progress
3022 :type 'boolean)
3024 (defcustom org-todo-repeat-to-state nil
3025 "The TODO state to which a repeater should return the repeating task.
3026 By default this is the first task in a TODO sequence, or the previous state
3027 in a TODO_TYP set. But you can specify another task here.
3028 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3029 :group 'org-todo
3030 :version "24.1"
3031 :type '(choice (const :tag "Head of sequence" nil)
3032 (string :tag "Specific state")))
3034 (defcustom org-log-repeat 'time
3035 "Non-nil means record moving through the DONE state when triggering repeat.
3036 An auto-repeating task is immediately switched back to TODO when
3037 marked DONE. If you are not logging state changes (by adding \"@\"
3038 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3039 record a closing note, there will be no record of the task moving
3040 through DONE. This variable forces taking a note anyway.
3042 nil Don't force a record
3043 time Record a time stamp
3044 note Prompt for a note and add it with template `org-log-note-headings'
3046 This option can also be set with on a per-file-basis with
3048 #+STARTUP: nologrepeat
3049 #+STARTUP: logrepeat
3050 #+STARTUP: lognoterepeat
3052 You can have local logging settings for a subtree by setting the LOGGING
3053 property to one or more of these keywords."
3054 :group 'org-todo
3055 :group 'org-progress
3056 :type '(choice
3057 (const :tag "Don't force a record" nil)
3058 (const :tag "Force recording the DONE state" time)
3059 (const :tag "Force recording a note with the DONE state" note)))
3062 (defgroup org-priorities nil
3063 "Priorities in Org mode."
3064 :tag "Org Priorities"
3065 :group 'org-todo)
3067 (defcustom org-enable-priority-commands t
3068 "Non-nil means priority commands are active.
3069 When nil, these commands will be disabled, so that you never accidentally
3070 set a priority."
3071 :group 'org-priorities
3072 :type 'boolean)
3074 (defcustom org-highest-priority ?A
3075 "The highest priority of TODO items. A character like ?A, ?B etc.
3076 Must have a smaller ASCII number than `org-lowest-priority'."
3077 :group 'org-priorities
3078 :type 'character)
3080 (defcustom org-lowest-priority ?C
3081 "The lowest priority of TODO items. A character like ?A, ?B etc.
3082 Must have a larger ASCII number than `org-highest-priority'."
3083 :group 'org-priorities
3084 :type 'character)
3086 (defcustom org-default-priority ?B
3087 "The default priority of TODO items.
3088 This is the priority an item gets if no explicit priority is given.
3089 When starting to cycle on an empty priority the first step in the cycle
3090 depends on `org-priority-start-cycle-with-default'. The resulting first
3091 step priority must not exceed the range from `org-highest-priority' to
3092 `org-lowest-priority' which means that `org-default-priority' has to be
3093 in this range exclusive or inclusive the range boundaries. Else the
3094 first step refuses to set the default and the second will fall back
3095 to (depending on the command used) the highest or lowest priority."
3096 :group 'org-priorities
3097 :type 'character)
3099 (defcustom org-priority-start-cycle-with-default t
3100 "Non-nil means start with default priority when starting to cycle.
3101 When this is nil, the first step in the cycle will be (depending on the
3102 command used) one higher or lower than the default priority.
3103 See also `org-default-priority'."
3104 :group 'org-priorities
3105 :type 'boolean)
3107 (defcustom org-get-priority-function nil
3108 "Function to extract the priority from a string.
3109 The string is normally the headline. If this is nil Org computes the
3110 priority from the priority cookie like [#A] in the headline. It returns
3111 an integer, increasing by 1000 for each priority level.
3112 The user can set a different function here, which should take a string
3113 as an argument and return the numeric priority."
3114 :group 'org-priorities
3115 :version "24.1"
3116 :type '(choice
3117 (const nil)
3118 (function)))
3120 (defgroup org-time nil
3121 "Options concerning time stamps and deadlines in Org mode."
3122 :tag "Org Time"
3123 :group 'org)
3125 (defcustom org-time-stamp-rounding-minutes '(0 5)
3126 "Number of minutes to round time stamps to.
3127 \\<org-mode-map>\
3128 These are two values, the first applies when first creating a time stamp.
3129 The second applies when changing it with the commands `S-up' and `S-down'.
3130 When changing the time stamp, this means that it will change in steps
3131 of N minutes, as given by the second value.
3133 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3134 numbers should be factors of 60, so for example 5, 10, 15.
3136 When this is larger than 1, you can still force an exact time stamp by using
3137 a double prefix argument to a time stamp command like \
3138 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3139 and by using a prefix arg to `S-up/down' to specify the exact number
3140 of minutes to shift."
3141 :group 'org-time
3142 :get (lambda (var) ; Make sure both elements are there
3143 (if (integerp (default-value var))
3144 (list (default-value var) 5)
3145 (default-value var)))
3146 :type '(list
3147 (integer :tag "when inserting times")
3148 (integer :tag "when modifying times")))
3150 ;; Normalize old customizations of this variable.
3151 (when (integerp org-time-stamp-rounding-minutes)
3152 (setq org-time-stamp-rounding-minutes
3153 (list org-time-stamp-rounding-minutes
3154 org-time-stamp-rounding-minutes)))
3156 (defcustom org-display-custom-times nil
3157 "Non-nil means overlay custom formats over all time stamps.
3158 The formats are defined through the variable `org-time-stamp-custom-formats'.
3159 To turn this on on a per-file basis, insert anywhere in the file:
3160 #+STARTUP: customtime"
3161 :group 'org-time
3162 :set 'set-default
3163 :type 'sexp)
3164 (make-variable-buffer-local 'org-display-custom-times)
3166 (defcustom org-time-stamp-custom-formats
3167 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3168 "Custom formats for time stamps. See `format-time-string' for the syntax.
3169 These are overlaid over the default ISO format if the variable
3170 `org-display-custom-times' is set. Time like %H:%M should be at the
3171 end of the second format. The custom formats are also honored by export
3172 commands, if custom time display is turned on at the time of export."
3173 :group 'org-time
3174 :type 'sexp)
3176 (defun org-time-stamp-format (&optional long inactive)
3177 "Get the right format for a time string."
3178 (let ((f (if long (cdr org-time-stamp-formats)
3179 (car org-time-stamp-formats))))
3180 (if inactive
3181 (concat "[" (substring f 1 -1) "]")
3182 f)))
3184 (defcustom org-deadline-warning-days 14
3185 "Number of days before expiration during which a deadline becomes active.
3186 This variable governs the display in sparse trees and in the agenda.
3187 When 0 or negative, it means use this number (the absolute value of it)
3188 even if a deadline has a different individual lead time specified.
3190 Custom commands can set this variable in the options section."
3191 :group 'org-time
3192 :group 'org-agenda-daily/weekly
3193 :type 'integer)
3195 (defcustom org-scheduled-delay-days 0
3196 "Number of days before a scheduled item becomes active.
3197 This variable governs the display in sparse trees and in the agenda.
3198 The default value (i.e. 0) means: don't delay scheduled item.
3199 When negative, it means use this number (the absolute value of it)
3200 even if a scheduled item has a different individual delay time
3201 specified.
3203 Custom commands can set this variable in the options section."
3204 :group 'org-time
3205 :group 'org-agenda-daily/weekly
3206 :version "24.4"
3207 :package-version '(Org . "8.0")
3208 :type 'integer)
3210 (defcustom org-read-date-prefer-future t
3211 "Non-nil means assume future for incomplete date input from user.
3212 This affects the following situations:
3213 1. The user gives a month but not a year.
3214 For example, if it is April and you enter \"feb 2\", this will be read
3215 as Feb 2, *next* year. \"May 5\", however, will be this year.
3216 2. The user gives a day, but no month.
3217 For example, if today is the 15th, and you enter \"3\", Org will read
3218 this as the third of *next* month. However, if you enter \"17\",
3219 it will be considered as *this* month.
3221 If you set this variable to the symbol `time', then also the following
3222 will work:
3224 3. If the user gives a time.
3225 If the time is before now, it will be interpreted as tomorrow.
3227 Currently none of this works for ISO week specifications.
3229 When this option is nil, the current day, month and year will always be
3230 used as defaults.
3232 See also `org-agenda-jump-prefer-future'."
3233 :group 'org-time
3234 :type '(choice
3235 (const :tag "Never" nil)
3236 (const :tag "Check month and day" t)
3237 (const :tag "Check month, day, and time" time)))
3239 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3240 "Should the agenda jump command prefer the future for incomplete dates?
3241 The default is to do the same as configured in `org-read-date-prefer-future'.
3242 But you can also set a deviating value here.
3243 This may t or nil, or the symbol `org-read-date-prefer-future'."
3244 :group 'org-agenda
3245 :group 'org-time
3246 :version "24.1"
3247 :type '(choice
3248 (const :tag "Use org-read-date-prefer-future"
3249 org-read-date-prefer-future)
3250 (const :tag "Never" nil)
3251 (const :tag "Always" t)))
3253 (defcustom org-read-date-force-compatible-dates t
3254 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3256 Depending on the system Emacs is running on, certain dates cannot
3257 be represented with the type used internally to represent time.
3258 Dates between 1970-1-1 and 2038-1-1 can always be represented
3259 correctly. Some systems allow for earlier dates, some for later,
3260 some for both. One way to find out it to insert any date into an
3261 Org buffer, putting the cursor on the year and hitting S-up and
3262 S-down to test the range.
3264 When this variable is set to t, the date/time prompt will not let
3265 you specify dates outside the 1970-2037 range, so it is certain that
3266 these dates will work in whatever version of Emacs you are
3267 running, and also that you can move a file from one Emacs implementation
3268 to another. WHenever Org is forcing the year for you, it will display
3269 a message and beep.
3271 When this variable is nil, Org will check if the date is
3272 representable in the specific Emacs implementation you are using.
3273 If not, it will force a year, usually the current year, and beep
3274 to remind you. Currently this setting is not recommended because
3275 the likelihood that you will open your Org files in an Emacs that
3276 has limited date range is not negligible.
3278 A workaround for this problem is to use diary sexp dates for time
3279 stamps outside of this range."
3280 :group 'org-time
3281 :version "24.1"
3282 :type 'boolean)
3284 (defcustom org-read-date-display-live t
3285 "Non-nil means display current interpretation of date prompt live.
3286 This display will be in an overlay, in the minibuffer."
3287 :group 'org-time
3288 :type 'boolean)
3290 (defcustom org-read-date-popup-calendar t
3291 "Non-nil means pop up a calendar when prompting for a date.
3292 In the calendar, the date can be selected with mouse-1. However, the
3293 minibuffer will also be active, and you can simply enter the date as well.
3294 When nil, only the minibuffer will be available."
3295 :group 'org-time
3296 :type 'boolean)
3297 (defvaralias 'org-popup-calendar-for-date-prompt
3298 'org-read-date-popup-calendar)
3300 (defcustom org-extend-today-until 0
3301 "The hour when your day really ends. Must be an integer.
3302 This has influence for the following applications:
3303 - When switching the agenda to \"today\". It it is still earlier than
3304 the time given here, the day recognized as TODAY is actually yesterday.
3305 - When a date is read from the user and it is still before the time given
3306 here, the current date and time will be assumed to be yesterday, 23:59.
3307 Also, timestamps inserted in capture templates follow this rule.
3309 IMPORTANT: This is a feature whose implementation is and likely will
3310 remain incomplete. Really, it is only here because past midnight seems to
3311 be the favorite working time of John Wiegley :-)"
3312 :group 'org-time
3313 :type 'integer)
3315 (defcustom org-use-effective-time nil
3316 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3317 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3318 \"effective time\" of any timestamps between midnight and 8am will be
3319 23:59 of the previous day."
3320 :group 'org-time
3321 :version "24.1"
3322 :type 'boolean)
3324 (defcustom org-use-last-clock-out-time-as-effective-time nil
3325 "When non-nil, use the last clock out time for `org-todo'.
3326 Note that this option has precedence over the combined use of
3327 `org-use-effective-time' and `org-extend-today-until'."
3328 :group 'org-time
3329 :version "24.4"
3330 :package-version '(Org . "8.0")
3331 :type 'boolean)
3333 (defcustom org-edit-timestamp-down-means-later nil
3334 "Non-nil means S-down will increase the time in a time stamp.
3335 When nil, S-up will increase."
3336 :group 'org-time
3337 :type 'boolean)
3339 (defcustom org-calendar-follow-timestamp-change t
3340 "Non-nil means make the calendar window follow timestamp changes.
3341 When a timestamp is modified and the calendar window is visible, it will be
3342 moved to the new date."
3343 :group 'org-time
3344 :type 'boolean)
3346 (defgroup org-tags nil
3347 "Options concerning tags in Org mode."
3348 :tag "Org Tags"
3349 :group 'org)
3351 (defcustom org-tag-alist nil
3352 "Default tags available in Org files.
3354 The value of this variable is an alist. Associations either:
3356 (TAG)
3357 (TAG . SELECT)
3358 (SPECIAL)
3360 where TAG is a tag as a string, SELECT is character, used to
3361 select that tag through the fast tag selection interface, and
3362 SPECIAL is one of the following keywords: `:startgroup',
3363 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3364 `:newline'. These keywords are used to define a hierarchy of
3365 tags. See manual for details.
3367 When this variable is nil, Org mode bases tag input on what is
3368 already in the buffer. The value can be overridden locally by
3369 using a TAGS keyword, e.g.,
3371 #+TAGS: tag1 tag2
3373 See also `org-tag-persistent-alist' to sidestep this behavior."
3374 :group 'org-tags
3375 :type '(repeat
3376 (choice
3377 (cons :tag "Tag with key"
3378 (string :tag "Tag name")
3379 (character :tag "Access char"))
3380 (list :tag "Tag" (string :tag "Tag name"))
3381 (const :tag "Start radio group" (:startgroup))
3382 (const :tag "Start tag group, non distinct" (:startgrouptag))
3383 (const :tag "Group tags delimiter" (:grouptags))
3384 (const :tag "End radio group" (:endgroup))
3385 (const :tag "End tag group, non distinct" (:endgrouptag))
3386 (const :tag "New line" (:newline)))))
3388 (defcustom org-tag-persistent-alist nil
3389 "Tags always available in Org files.
3391 The value of this variable is an alist. Associations either:
3393 (TAG)
3394 (TAG . SELECT)
3395 (SPECIAL)
3397 where TAG is a tag as a string, SELECT is a character, used to
3398 select that tag through the fast tag selection interface, and
3399 SPECIAL is one of the following keywords: `:startgroup',
3400 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3401 `:newline'. These keywords are used to define a hierarchy of
3402 tags. See manual for details.
3404 Unlike to `org-tag-alist', tags defined in this variable do not
3405 depend on a local TAGS keyword. Instead, to disable these tags
3406 on a per-file basis, insert anywhere in the file:
3408 #+STARTUP: noptag"
3409 :group 'org-tags
3410 :type '(repeat
3411 (choice
3412 (cons :tag "Tag with key"
3413 (string :tag "Tag name")
3414 (character :tag "Access char"))
3415 (list :tag "Tag" (string :tag "Tag name"))
3416 (const :tag "Start radio group" (:startgroup))
3417 (const :tag "Start tag group, non distinct" (:startgrouptag))
3418 (const :tag "Group tags delimiter" (:grouptags))
3419 (const :tag "End radio group" (:endgroup))
3420 (const :tag "End tag group, non distinct" (:endgrouptag))
3421 (const :tag "New line" (:newline)))))
3423 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3424 "If non-nil, always offer completion for all tags of all agenda files.
3425 Instead of customizing this variable directly, you might want to
3426 set it locally for capture buffers, because there no list of
3427 tags in that file can be created dynamically (there are none).
3429 (add-hook \\='org-capture-mode-hook
3430 (lambda ()
3431 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3432 :group 'org-tags
3433 :version "24.1"
3434 :type 'boolean)
3436 (defvar org-file-tags nil
3437 "List of tags that can be inherited by all entries in the file.
3438 The tags will be inherited if the variable `org-use-tag-inheritance'
3439 says they should be.
3440 This variable is populated from #+FILETAGS lines.")
3442 (defcustom org-use-fast-tag-selection 'auto
3443 "Non-nil means use fast tag selection scheme.
3444 This is a special interface to select and deselect tags with single keys.
3445 When nil, fast selection is never used.
3446 When the symbol `auto', fast selection is used if and only if selection
3447 characters for tags have been configured, either through the variable
3448 `org-tag-alist' or through a #+TAGS line in the buffer.
3449 When t, fast selection is always used and selection keys are assigned
3450 automatically if necessary."
3451 :group 'org-tags
3452 :type '(choice
3453 (const :tag "Always" t)
3454 (const :tag "Never" nil)
3455 (const :tag "When selection characters are configured" auto)))
3457 (defcustom org-fast-tag-selection-single-key nil
3458 "Non-nil means fast tag selection exits after first change.
3459 When nil, you have to press RET to exit it.
3460 During fast tag selection, you can toggle this flag with `C-c'.
3461 This variable can also have the value `expert'. In this case, the window
3462 displaying the tags menu is not even shown, until you press C-c again."
3463 :group 'org-tags
3464 :type '(choice
3465 (const :tag "No" nil)
3466 (const :tag "Yes" t)
3467 (const :tag "Expert" expert)))
3469 (defvar org-fast-tag-selection-include-todo nil
3470 "Non-nil means fast tags selection interface will also offer TODO states.
3471 This is an undocumented feature, you should not rely on it.")
3473 (defcustom org-tags-column -77
3474 "The column to which tags should be indented in a headline.
3475 If this number is positive, it specifies the column. If it is negative,
3476 it means that the tags should be flushright to that column. For example,
3477 -80 works well for a normal 80 character screen.
3478 When 0, place tags directly after headline text, with only one space in
3479 between."
3480 :group 'org-tags
3481 :type 'integer)
3483 (defcustom org-auto-align-tags t
3484 "Non-nil keeps tags aligned when modifying headlines.
3485 Some operations (i.e. demoting) change the length of a headline and
3486 therefore shift the tags around. With this option turned on, after
3487 each such operation the tags are again aligned to `org-tags-column'."
3488 :group 'org-tags
3489 :type 'boolean)
3491 (defcustom org-use-tag-inheritance t
3492 "Non-nil means tags in levels apply also for sublevels.
3493 When nil, only the tags directly given in a specific line apply there.
3494 This may also be a list of tags that should be inherited, or a regexp that
3495 matches tags that should be inherited. Additional control is possible
3496 with the variable `org-tags-exclude-from-inheritance' which gives an
3497 explicit list of tags to be excluded from inheritance, even if the value of
3498 `org-use-tag-inheritance' would select it for inheritance.
3500 If this option is t, a match early-on in a tree can lead to a large
3501 number of matches in the subtree when constructing the agenda or creating
3502 a sparse tree. If you only want to see the first match in a tree during
3503 a search, check out the variable `org-tags-match-list-sublevels'."
3504 :group 'org-tags
3505 :type '(choice
3506 (const :tag "Not" nil)
3507 (const :tag "Always" t)
3508 (repeat :tag "Specific tags" (string :tag "Tag"))
3509 (regexp :tag "Tags matched by regexp")))
3511 (defcustom org-tags-exclude-from-inheritance nil
3512 "List of tags that should never be inherited.
3513 This is a way to exclude a few tags from inheritance. For way to do
3514 the opposite, to actively allow inheritance for selected tags,
3515 see the variable `org-use-tag-inheritance'."
3516 :group 'org-tags
3517 :type '(repeat (string :tag "Tag")))
3519 (defun org-tag-inherit-p (tag)
3520 "Check if TAG is one that should be inherited."
3521 (cond
3522 ((member tag org-tags-exclude-from-inheritance) nil)
3523 ((eq org-use-tag-inheritance t) t)
3524 ((not org-use-tag-inheritance) nil)
3525 ((stringp org-use-tag-inheritance)
3526 (string-match org-use-tag-inheritance tag))
3527 ((listp org-use-tag-inheritance)
3528 (member tag org-use-tag-inheritance))
3529 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3531 (defcustom org-tags-match-list-sublevels t
3532 "Non-nil means list also sublevels of headlines matching a search.
3533 This variable applies to tags/property searches, and also to stuck
3534 projects because this search is based on a tags match as well.
3536 When set to the symbol `indented', sublevels are indented with
3537 leading dots.
3539 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3540 the sublevels of a headline matching a tag search often also match
3541 the same search. Listing all of them can create very long lists.
3542 Setting this variable to nil causes subtrees of a match to be skipped.
3544 This variable is semi-obsolete and probably should always be true. It
3545 is better to limit inheritance to certain tags using the variables
3546 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3547 :group 'org-tags
3548 :type '(choice
3549 (const :tag "No, don't list them" nil)
3550 (const :tag "Yes, do list them" t)
3551 (const :tag "List them, indented with leading dots" indented)))
3553 (defcustom org-tags-sort-function nil
3554 "When set, tags are sorted using this function as a comparator."
3555 :group 'org-tags
3556 :type '(choice
3557 (const :tag "No sorting" nil)
3558 (const :tag "Alphabetical" string<)
3559 (const :tag "Reverse alphabetical" string>)
3560 (function :tag "Custom function" nil)))
3562 (defvar org-tags-history nil
3563 "History of minibuffer reads for tags.")
3564 (defvar org-last-tags-completion-table nil
3565 "The last used completion table for tags.")
3566 (defvar org-after-tags-change-hook nil
3567 "Hook that is run after the tags in a line have changed.")
3569 (defgroup org-properties nil
3570 "Options concerning properties in Org mode."
3571 :tag "Org Properties"
3572 :group 'org)
3574 (defcustom org-property-format "%-10s %s"
3575 "How property key/value pairs should be formatted by `indent-line'.
3576 When `indent-line' hits a property definition, it will format the line
3577 according to this format, mainly to make sure that the values are
3578 lined-up with respect to each other."
3579 :group 'org-properties
3580 :type 'string)
3582 (defcustom org-properties-postprocess-alist nil
3583 "Alist of properties and functions to adjust inserted values.
3584 Elements of this alist must be of the form
3586 ([string] [function])
3588 where [string] must be a property name and [function] must be a
3589 lambda expression: this lambda expression must take one argument,
3590 the value to adjust, and return the new value as a string.
3592 For example, this element will allow the property \"Remaining\"
3593 to be updated wrt the relation between the \"Effort\" property
3594 and the clock summary:
3596 ((\"Remaining\" (lambda(value)
3597 (let ((clocksum (org-clock-sum-current-item))
3598 (effort (org-duration-to-minutes
3599 (org-entry-get (point) \"Effort\"))))
3600 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3601 :group 'org-properties
3602 :version "24.1"
3603 :type '(alist :key-type (string :tag "Property")
3604 :value-type (function :tag "Function")))
3606 (defcustom org-use-property-inheritance nil
3607 "Non-nil means properties apply also for sublevels.
3609 This setting is chiefly used during property searches. Turning it on can
3610 cause significant overhead when doing a search, which is why it is not
3611 on by default.
3613 When nil, only the properties directly given in the current entry count.
3614 When t, every property is inherited. The value may also be a list of
3615 properties that should have inheritance, or a regular expression matching
3616 properties that should be inherited.
3618 However, note that some special properties use inheritance under special
3619 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3620 and the properties ending in \"_ALL\" when they are used as descriptor
3621 for valid values of a property.
3623 Note for programmers:
3624 When querying an entry with `org-entry-get', you can control if inheritance
3625 should be used. By default, `org-entry-get' looks only at the local
3626 properties. You can request inheritance by setting the inherit argument
3627 to t (to force inheritance) or to `selective' (to respect the setting
3628 in this variable)."
3629 :group 'org-properties
3630 :type '(choice
3631 (const :tag "Not" nil)
3632 (const :tag "Always" t)
3633 (repeat :tag "Specific properties" (string :tag "Property"))
3634 (regexp :tag "Properties matched by regexp")))
3636 (defun org-property-inherit-p (property)
3637 "Return a non-nil value if PROPERTY should be inherited."
3638 (cond
3639 ((eq org-use-property-inheritance t) t)
3640 ((not org-use-property-inheritance) nil)
3641 ((stringp org-use-property-inheritance)
3642 (string-match org-use-property-inheritance property))
3643 ((listp org-use-property-inheritance)
3644 (member-ignore-case property org-use-property-inheritance))
3645 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3647 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3648 "The default column format, if no other format has been defined.
3649 This variable can be set on the per-file basis by inserting a line
3651 #+COLUMNS: %25ITEM ....."
3652 :group 'org-properties
3653 :type 'string)
3655 (defcustom org-columns-ellipses ".."
3656 "The ellipses to be used when a field in column view is truncated.
3657 When this is the empty string, as many characters as possible are shown,
3658 but then there will be no visual indication that the field has been truncated.
3659 When this is a string of length N, the last N characters of a truncated
3660 field are replaced by this string. If the column is narrower than the
3661 ellipses string, only part of the ellipses string will be shown."
3662 :group 'org-properties
3663 :type 'string)
3665 (defconst org-global-properties-fixed
3666 '(("VISIBILITY_ALL" . "folded children content all")
3667 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3668 "List of property/value pairs that can be inherited by any entry.
3670 These are fixed values, for the preset properties. The user variable
3671 that can be used to add to this list is `org-global-properties'.
3673 The entries in this list are cons cells where the car is a property
3674 name and cdr is a string with the value. If the value represents
3675 multiple items like an \"_ALL\" property, separate the items by
3676 spaces.")
3678 (defcustom org-global-properties nil
3679 "List of property/value pairs that can be inherited by any entry.
3681 This list will be combined with the constant `org-global-properties-fixed'.
3683 The entries in this list are cons cells where the car is a property
3684 name and cdr is a string with the value.
3686 You can set buffer-local values for the same purpose in the variable
3687 `org-file-properties' this by adding lines like
3689 #+PROPERTY: NAME VALUE"
3690 :group 'org-properties
3691 :type '(repeat
3692 (cons (string :tag "Property")
3693 (string :tag "Value"))))
3695 (defvar-local org-file-properties nil
3696 "List of property/value pairs that can be inherited by any entry.
3697 Valid for the current buffer.
3698 This variable is populated from #+PROPERTY lines.")
3700 (defgroup org-agenda nil
3701 "Options concerning agenda views in Org mode."
3702 :tag "Org Agenda"
3703 :group 'org)
3705 (defvar-local org-category nil
3706 "Variable used by org files to set a category for agenda display.
3707 Such files should use a file variable to set it, for example
3709 # -*- mode: org; org-category: \"ELisp\"
3711 or contain a special line
3713 #+CATEGORY: ELisp
3715 If the file does not specify a category, then file's base name
3716 is used instead.")
3717 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3719 (defcustom org-agenda-files nil
3720 "The files to be used for agenda display.
3722 If an entry is a directory, all files in that directory that are matched
3723 by `org-agenda-file-regexp' will be part of the file list.
3725 If the value of the variable is not a list but a single file name, then
3726 the list of agenda files is actually stored and maintained in that file,
3727 one agenda file per line. In this file paths can be given relative to
3728 `org-directory'. Tilde expansion and environment variable substitution
3729 are also made.
3731 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3732 and removed with `\\[org-remove-file]'."
3733 :group 'org-agenda
3734 :type '(choice
3735 (repeat :tag "List of files and directories" file)
3736 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3738 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3739 "Regular expression to match files for `org-agenda-files'.
3740 If any element in the list in that variable contains a directory instead
3741 of a normal file, all files in that directory that are matched by this
3742 regular expression will be included."
3743 :group 'org-agenda
3744 :type 'regexp)
3746 (defcustom org-agenda-text-search-extra-files nil
3747 "List of extra files to be searched by text search commands.
3748 These files will be searched in addition to the agenda files by the
3749 commands `org-search-view' (`\\[org-agenda] s') \
3750 and `org-occur-in-agenda-files'.
3751 Note that these files will only be searched for text search commands,
3752 not for the other agenda views like todo lists, tag searches or the weekly
3753 agenda. This variable is intended to list notes and possibly archive files
3754 that should also be searched by these two commands.
3755 In fact, if the first element in the list is the symbol `agenda-archives',
3756 then all archive files of all agenda files will be added to the search
3757 scope."
3758 :group 'org-agenda
3759 :type '(set :greedy t
3760 (const :tag "Agenda Archives" agenda-archives)
3761 (repeat :inline t (file))))
3763 (defvaralias 'org-agenda-multi-occur-extra-files
3764 'org-agenda-text-search-extra-files)
3766 (defcustom org-agenda-skip-unavailable-files nil
3767 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3768 A nil value means to remove them, after a query, from the list."
3769 :group 'org-agenda
3770 :type 'boolean)
3772 (defcustom org-calendar-to-agenda-key [?c]
3773 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3774 The command `org-calendar-goto-agenda' will be bound to this key. The
3775 default is the character `c' because then `c' can be used to switch back and
3776 forth between agenda and calendar."
3777 :group 'org-agenda
3778 :type 'sexp)
3780 (defcustom org-calendar-insert-diary-entry-key [?i]
3781 "The key to be installed in `calendar-mode-map' for adding diary entries.
3782 This option is irrelevant until `org-agenda-diary-file' has been configured
3783 to point to an Org file. When that is the case, the command
3784 `org-agenda-diary-entry' will be bound to the key given here, by default
3785 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3786 if you want to continue doing this, you need to change this to a different
3787 key."
3788 :group 'org-agenda
3789 :type 'sexp)
3791 (defcustom org-agenda-diary-file 'diary-file
3792 "File to which to add new entries with the `i' key in agenda and calendar.
3793 When this is the symbol `diary-file', the functionality in the Emacs
3794 calendar will be used to add entries to the `diary-file'. But when this
3795 points to a file, `org-agenda-diary-entry' will be used instead."
3796 :group 'org-agenda
3797 :type '(choice
3798 (const :tag "The standard Emacs diary file" diary-file)
3799 (file :tag "Special Org file diary entries")))
3801 (eval-after-load "calendar"
3802 '(progn
3803 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3804 'org-calendar-goto-agenda)
3805 (add-hook 'calendar-mode-hook
3806 (lambda ()
3807 (unless (eq org-agenda-diary-file 'diary-file)
3808 (define-key calendar-mode-map
3809 org-calendar-insert-diary-entry-key
3810 'org-agenda-diary-entry))))))
3812 (defgroup org-latex nil
3813 "Options for embedding LaTeX code into Org mode."
3814 :tag "Org LaTeX"
3815 :group 'org)
3817 (defcustom org-format-latex-options
3818 '(:foreground default :background default :scale 1.0
3819 :html-foreground "Black" :html-background "Transparent"
3820 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3821 "Options for creating images from LaTeX fragments.
3822 This is a property list with the following properties:
3823 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3824 `default' means use the foreground of the default face.
3825 `auto' means use the foreground from the text face.
3826 :background the background color, or \"Transparent\".
3827 `default' means use the background of the default face.
3828 `auto' means use the background from the text face.
3829 :scale a scaling factor for the size of the images, to get more pixels
3830 :html-foreground, :html-background, :html-scale
3831 the same numbers for HTML export.
3832 :matchers a list indicating which matchers should be used to
3833 find LaTeX fragments. Valid members of this list are:
3834 \"begin\" find environments
3835 \"$1\" find single characters surrounded by $.$
3836 \"$\" find math expressions surrounded by $...$
3837 \"$$\" find math expressions surrounded by $$....$$
3838 \"\\(\" find math expressions surrounded by \\(...\\)
3839 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3840 :group 'org-latex
3841 :type 'plist)
3843 (defcustom org-format-latex-signal-error t
3844 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3845 When nil, just push out a message."
3846 :group 'org-latex
3847 :version "24.1"
3848 :type 'boolean)
3850 (defcustom org-latex-to-mathml-jar-file nil
3851 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3852 Use this to specify additional executable file say a jar file.
3854 When using MathToWeb as the converter, specify the full-path to
3855 your mathtoweb.jar file."
3856 :group 'org-latex
3857 :version "24.1"
3858 :type '(choice
3859 (const :tag "None" nil)
3860 (file :tag "JAR file" :must-match t)))
3862 (defcustom org-latex-to-mathml-convert-command nil
3863 "Command to convert LaTeX fragments to MathML.
3864 Replace format-specifiers in the command as noted below and use
3865 `shell-command' to convert LaTeX to MathML.
3866 %j: Executable file in fully expanded form as specified by
3867 `org-latex-to-mathml-jar-file'.
3868 %I: Input LaTeX file in fully expanded form.
3869 %i: The latex fragment to be converted.
3870 %o: Output MathML file.
3872 This command is used by `org-create-math-formula'.
3874 When using MathToWeb as the converter, set this option to
3875 \"java -jar %j -unicode -force -df %o %I\".
3877 When using LaTeXML set this option to
3878 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3879 :group 'org-latex
3880 :version "24.1"
3881 :type '(choice
3882 (const :tag "None" nil)
3883 (string :tag "\nShell command")))
3885 (defcustom org-preview-latex-default-process 'dvipng
3886 "The default process to convert LaTeX fragments to image files.
3887 All available processes and theirs documents can be found in
3888 `org-preview-latex-process-alist', which see."
3889 :group 'org-latex
3890 :version "26.1"
3891 :package-version '(Org . "9.0")
3892 :type 'symbol)
3894 (defcustom org-preview-latex-process-alist
3895 '((dvipng
3896 :programs ("latex" "dvipng")
3897 :description "dvi > png"
3898 :message "you need to install the programs: latex and dvipng."
3899 :image-input-type "dvi"
3900 :image-output-type "png"
3901 :image-size-adjust (1.0 . 1.0)
3902 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3903 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3904 (dvisvgm
3905 :programs ("latex" "dvisvgm")
3906 :description "dvi > svg"
3907 :message "you need to install the programs: latex and dvisvgm."
3908 :use-xcolor t
3909 :image-input-type "dvi"
3910 :image-output-type "svg"
3911 :image-size-adjust (1.7 . 1.5)
3912 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3913 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3914 (imagemagick
3915 :programs ("latex" "convert")
3916 :description "pdf > png"
3917 :message "you need to install the programs: latex and imagemagick."
3918 :use-xcolor t
3919 :image-input-type "pdf"
3920 :image-output-type "png"
3921 :image-size-adjust (1.0 . 1.0)
3922 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3923 :image-converter
3924 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3925 "Definitions of external processes for LaTeX previewing.
3926 Org mode can use some external commands to generate TeX snippet's images for
3927 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3928 `org-create-formula-image' how to call them.
3930 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3931 PROPERTIES accepts the following attributes:
3933 :programs list of strings, required programs.
3934 :description string, describe the process.
3935 :message string, message it when required programs cannot be found.
3936 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3937 :image-output-type string, output file type of image converter (e.g., \"png\").
3938 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3939 deal with background and foreground color of image.
3940 Otherwise, dvipng style background and foreground color
3941 format are generated. You may then refer to them in
3942 command options with \"%F\" and \"%B\".
3943 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3944 image size showed in buffer and the cdr element is for
3945 HTML file. This option is only useful for process
3946 developers, users should use variable
3947 `org-format-latex-options' instead.
3948 :post-clean list of strings, files matched are to be cleaned up once
3949 the image is generated. When nil, the files with \".dvi\",
3950 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3951 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3952 be cleaned up.
3953 :latex-header list of strings, the LaTeX header of the snippet file.
3954 When nil, the fallback value is used instead, which is
3955 controlled by `org-format-latex-header',
3956 `org-latex-default-packages-alist' and
3957 `org-latex-packages-alist', which see.
3958 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3959 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3960 replaced with values defined below.
3961 :image-converter list of image converter commands strings. Each of them is
3962 given to the shell and supports any of the following
3963 place-holders defined below.
3965 Place-holders used by `:image-converter' and `:latex-compiler':
3967 %f input file name
3968 %b base name of input file
3969 %o base directory of input file
3970 %O absolute output file name
3972 Place-holders only used by `:image-converter':
3974 %F foreground of image
3975 %B background of image
3976 %D dpi, which is used to adjust image size by some processing commands.
3977 %S the image size scale ratio, which is used to adjust image size by some
3978 processing commands."
3979 :group 'org-latex
3980 :version "26.1"
3981 :package-version '(Org . "9.0")
3982 :type '(alist :tag "LaTeX to image backends"
3983 :value-type (plist)))
3985 (defcustom org-preview-latex-image-directory "ltximg/"
3986 "Path to store latex preview images.
3987 A relative path here creates many directories relative to the
3988 processed org files paths. An absolute path puts all preview
3989 images at the same place."
3990 :group 'org-latex
3991 :version "26.1"
3992 :package-version '(Org . "9.0")
3993 :type 'string)
3995 (defun org-format-latex-mathml-available-p ()
3996 "Return t if `org-latex-to-mathml-convert-command' is usable."
3997 (save-match-data
3998 (when (and (boundp 'org-latex-to-mathml-convert-command)
3999 org-latex-to-mathml-convert-command)
4000 (let ((executable (car (split-string
4001 org-latex-to-mathml-convert-command))))
4002 (when (executable-find executable)
4003 (if (string-match
4004 "%j" org-latex-to-mathml-convert-command)
4005 (file-readable-p org-latex-to-mathml-jar-file)
4006 t))))))
4008 (defcustom org-format-latex-header "\\documentclass{article}
4009 \\usepackage[usenames]{color}
4010 \[PACKAGES]
4011 \[DEFAULT-PACKAGES]
4012 \\pagestyle{empty} % do not remove
4013 % The settings below are copied from fullpage.sty
4014 \\setlength{\\textwidth}{\\paperwidth}
4015 \\addtolength{\\textwidth}{-3cm}
4016 \\setlength{\\oddsidemargin}{1.5cm}
4017 \\addtolength{\\oddsidemargin}{-2.54cm}
4018 \\setlength{\\evensidemargin}{\\oddsidemargin}
4019 \\setlength{\\textheight}{\\paperheight}
4020 \\addtolength{\\textheight}{-\\headheight}
4021 \\addtolength{\\textheight}{-\\headsep}
4022 \\addtolength{\\textheight}{-\\footskip}
4023 \\addtolength{\\textheight}{-3cm}
4024 \\setlength{\\topmargin}{1.5cm}
4025 \\addtolength{\\topmargin}{-2.54cm}"
4026 "The document header used for processing LaTeX fragments.
4027 It is imperative that this header make sure that no page number
4028 appears on the page. The package defined in the variables
4029 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4030 will either replace the placeholder \"[PACKAGES]\" in this
4031 header, or they will be appended."
4032 :group 'org-latex
4033 :type 'string)
4035 (defun org-set-packages-alist (var val)
4036 "Set the packages alist and make sure it has 3 elements per entry."
4037 (set var (mapcar (lambda (x)
4038 (if (and (consp x) (= (length x) 2))
4039 (list (car x) (nth 1 x) t)
4041 val)))
4043 (defun org-get-packages-alist (var)
4044 "Get the packages alist and make sure it has 3 elements per entry."
4045 (mapcar (lambda (x)
4046 (if (and (consp x) (= (length x) 2))
4047 (list (car x) (nth 1 x) t)
4049 (default-value var)))
4051 (defcustom org-latex-default-packages-alist
4052 '(("AUTO" "inputenc" t ("pdflatex"))
4053 ("T1" "fontenc" t ("pdflatex"))
4054 ("" "graphicx" t)
4055 ("" "grffile" t)
4056 ("" "longtable" nil)
4057 ("" "wrapfig" nil)
4058 ("" "rotating" nil)
4059 ("normalem" "ulem" t)
4060 ("" "amsmath" t)
4061 ("" "textcomp" t)
4062 ("" "amssymb" t)
4063 ("" "capt-of" nil)
4064 ("" "hyperref" nil))
4065 "Alist of default packages to be inserted in the header.
4067 Change this only if one of the packages here causes an
4068 incompatibility with another package you are using.
4070 The packages in this list are needed by one part or another of
4071 Org mode to function properly:
4073 - inputenc, fontenc: for basic font and character selection
4074 - graphicx: for including images
4075 - grffile: allow periods and spaces in graphics file names
4076 - longtable: For multipage tables
4077 - wrapfig: for figure placement
4078 - rotating: for sideways figures and tables
4079 - ulem: for underline and strike-through
4080 - amsmath: for subscript and superscript and math environments
4081 - textcomp, amssymb: for various symbols used
4082 for interpreting the entities in `org-entities'. You can skip
4083 some of these packages if you don't use any of their symbols.
4084 - capt-of: for captions outside of floats
4085 - hyperref: for cross references
4087 Therefore you should not modify this variable unless you know
4088 what you are doing. The one reason to change it anyway is that
4089 you might be loading some other package that conflicts with one
4090 of the default packages. Each element is either a cell or
4091 a string.
4093 A cell is of the format
4095 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4097 If SNIPPET-FLAG is non-nil, the package also needs to be included
4098 when compiling LaTeX snippets into images for inclusion into
4099 non-LaTeX output. COMPILERS is a list of compilers that should
4100 include the package, see `org-latex-compiler'. If the document
4101 compiler is not in the list, and the list is non-nil, the package
4102 will not be inserted in the final document.
4104 A string will be inserted as-is in the header of the document."
4105 :group 'org-latex
4106 :group 'org-export-latex
4107 :set 'org-set-packages-alist
4108 :get 'org-get-packages-alist
4109 :version "26.1"
4110 :package-version '(Org . "8.3")
4111 :type '(repeat
4112 (choice
4113 (list :tag "options/package pair"
4114 (string :tag "options")
4115 (string :tag "package")
4116 (boolean :tag "Snippet"))
4117 (string :tag "A line of LaTeX"))))
4119 (defcustom org-latex-packages-alist nil
4120 "Alist of packages to be inserted in every LaTeX header.
4122 These will be inserted after `org-latex-default-packages-alist'.
4123 Each element is either a cell or a string.
4125 A cell is of the format:
4127 (\"options\" \"package\" SNIPPET-FLAG)
4129 SNIPPET-FLAG, when non-nil, indicates that this package is also
4130 needed when turning LaTeX snippets into images for inclusion into
4131 non-LaTeX output.
4133 A string will be inserted as-is in the header of the document.
4135 Make sure that you only list packages here which:
4137 - you want in every file;
4138 - do not conflict with the setup in `org-format-latex-header';
4139 - do not conflict with the default packages in
4140 `org-latex-default-packages-alist'."
4141 :group 'org-latex
4142 :group 'org-export-latex
4143 :set 'org-set-packages-alist
4144 :get 'org-get-packages-alist
4145 :type '(repeat
4146 (choice
4147 (list :tag "options/package pair"
4148 (string :tag "options")
4149 (string :tag "package")
4150 (boolean :tag "Snippet"))
4151 (string :tag "A line of LaTeX"))))
4153 (defgroup org-appearance nil
4154 "Settings for Org mode appearance."
4155 :tag "Org Appearance"
4156 :group 'org)
4158 (defcustom org-level-color-stars-only nil
4159 "Non-nil means fontify only the stars in each headline.
4160 When nil, the entire headline is fontified.
4161 Changing it requires restart of `font-lock-mode' to become effective
4162 also in regions already fontified."
4163 :group 'org-appearance
4164 :type 'boolean)
4166 (defcustom org-hide-leading-stars nil
4167 "Non-nil means hide the first N-1 stars in a headline.
4168 This works by using the face `org-hide' for these stars. This
4169 face is white for a light background, and black for a dark
4170 background. You may have to customize the face `org-hide' to
4171 make this work.
4172 Changing it requires restart of `font-lock-mode' to become effective
4173 also in regions already fontified.
4174 You may also set this on a per-file basis by adding one of the following
4175 lines to the buffer:
4177 #+STARTUP: hidestars
4178 #+STARTUP: showstars"
4179 :group 'org-appearance
4180 :type 'boolean)
4182 (defcustom org-hidden-keywords nil
4183 "List of symbols corresponding to keywords to be hidden the org buffer.
4184 For example, a value \\='(title) for this list will make the document's title
4185 appear in the buffer without the initial #+TITLE: keyword."
4186 :group 'org-appearance
4187 :version "24.1"
4188 :type '(set (const :tag "#+AUTHOR" author)
4189 (const :tag "#+DATE" date)
4190 (const :tag "#+EMAIL" email)
4191 (const :tag "#+TITLE" title)))
4193 (defcustom org-custom-properties nil
4194 "List of properties (as strings) with a special meaning.
4195 The default use of these custom properties is to let the user
4196 hide them with `org-toggle-custom-properties-visibility'."
4197 :group 'org-properties
4198 :group 'org-appearance
4199 :version "24.3"
4200 :type '(repeat (string :tag "Property Name")))
4202 (defcustom org-fontify-done-headline nil
4203 "Non-nil means change the face of a headline if it is marked DONE.
4204 Normally, only the TODO/DONE keyword indicates the state of a headline.
4205 When this is non-nil, the headline after the keyword is set to the
4206 `org-headline-done' as an additional indication."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-fontify-emphasized-text t
4211 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4212 Changing this variable requires a restart of Emacs to take effect."
4213 :group 'org-appearance
4214 :type 'boolean)
4216 (defcustom org-fontify-whole-heading-line nil
4217 "Non-nil means fontify the whole line for headings.
4218 This is useful when setting a background color for the
4219 org-level-* faces."
4220 :group 'org-appearance
4221 :type 'boolean)
4223 (defcustom org-highlight-latex-and-related nil
4224 "Non-nil means highlight LaTeX related syntax in the buffer.
4225 When non nil, the value should be a list containing any of the
4226 following symbols:
4227 `latex' Highlight LaTeX snippets and environments.
4228 `script' Highlight subscript and superscript.
4229 `entities' Highlight entities."
4230 :group 'org-appearance
4231 :version "24.4"
4232 :package-version '(Org . "8.0")
4233 :type '(choice
4234 (const :tag "No highlighting" nil)
4235 (set :greedy t :tag "Highlight"
4236 (const :tag "LaTeX snippets and environments" latex)
4237 (const :tag "Subscript and superscript" script)
4238 (const :tag "Entities" entities))))
4240 (defcustom org-hide-emphasis-markers nil
4241 "Non-nil mean font-lock should hide the emphasis marker characters."
4242 :group 'org-appearance
4243 :type 'boolean)
4245 (defcustom org-hide-macro-markers nil
4246 "Non-nil mean font-lock should hide the brackets marking macro calls."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-pretty-entities nil
4251 "Non-nil means show entities as UTF8 characters.
4252 When nil, the \\name form remains in the buffer."
4253 :group 'org-appearance
4254 :version "24.1"
4255 :type 'boolean)
4257 (defcustom org-pretty-entities-include-sub-superscripts t
4258 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4259 :group 'org-appearance
4260 :version "24.1"
4261 :type 'boolean)
4263 (defvar org-emph-re nil
4264 "Regular expression for matching emphasis.
4265 After a match, the match groups contain these elements:
4266 0 The match of the full regular expression, including the characters
4267 before and after the proper match
4268 1 The character before the proper match, or empty at beginning of line
4269 2 The proper match, including the leading and trailing markers
4270 3 The leading marker like * or /, indicating the type of highlighting
4271 4 The text between the emphasis markers, not including the markers
4272 5 The character after the match, empty at the end of a line")
4274 (defvar org-verbatim-re nil
4275 "Regular expression for matching verbatim text.")
4277 (defvar org-emphasis-regexp-components) ; defined just below
4278 (defvar org-emphasis-alist) ; defined just below
4279 (defun org-set-emph-re (var val)
4280 "Set variable and compute the emphasis regular expression."
4281 (set var val)
4282 (when (and (boundp 'org-emphasis-alist)
4283 (boundp 'org-emphasis-regexp-components)
4284 org-emphasis-alist org-emphasis-regexp-components)
4285 (pcase-let*
4286 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4287 (body (if (<= nl 0) body
4288 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4289 (template
4290 (format (concat "\\([%s]\\|^\\)" ;before markers
4291 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4292 "\\([%s]\\|$\\)") ;after markers
4293 pre border border body border post)))
4294 (setq org-emph-re (format template "*/_+"))
4295 (setq org-verbatim-re (format template "=~")))))
4297 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4298 ;; set this option proved cumbersome. See this message/thread:
4299 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4300 (defvar org-emphasis-regexp-components
4301 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4302 "Components used to build the regular expression for emphasis.
4303 This is a list with five entries. Terminology: In an emphasis string
4304 like \" *strong word* \", we call the initial space PREMATCH, the final
4305 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4306 and \"trong wor\" is the body. The different components in this variable
4307 specify what is allowed/forbidden in each part:
4309 pre Chars allowed as prematch. Beginning of line will be allowed too.
4310 post Chars allowed as postmatch. End of line will be allowed too.
4311 border The chars *forbidden* as border characters.
4312 body-regexp A regexp like \".\" to match a body character. Don't use
4313 non-shy groups here, and don't allow newline here.
4314 newline The maximum number of newlines allowed in an emphasis exp.
4316 You need to reload Org or to restart Emacs after setting this.")
4318 (defcustom org-emphasis-alist
4319 '(("*" bold)
4320 ("/" italic)
4321 ("_" underline)
4322 ("=" org-verbatim verbatim)
4323 ("~" org-code verbatim)
4324 ("+" (:strike-through t)))
4325 "Alist of characters and faces to emphasize text.
4326 Text starting and ending with a special character will be emphasized,
4327 for example *bold*, _underlined_ and /italic/. This variable sets the
4328 marker characters and the face to be used by font-lock for highlighting
4329 in Org buffers.
4331 You need to reload Org or to restart Emacs after customizing this."
4332 :group 'org-appearance
4333 :set 'org-set-emph-re
4334 :version "24.4"
4335 :package-version '(Org . "8.0")
4336 :type '(repeat
4337 (list
4338 (string :tag "Marker character")
4339 (choice
4340 (face :tag "Font-lock-face")
4341 (plist :tag "Face property list"))
4342 (option (const verbatim)))))
4344 (defvar org-protecting-blocks '("src" "example" "export")
4345 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4346 This is needed for font-lock setup.")
4348 ;;; Functions and variables from their packages
4349 ;; Declared here to avoid compiler warnings
4350 (defvar mark-active)
4352 ;; Various packages
4353 (declare-function calc-eval "calc" (str &optional separator &rest args))
4354 (declare-function calendar-forward-day "cal-move" (arg))
4355 (declare-function calendar-goto-date "cal-move" (date))
4356 (declare-function calendar-goto-today "cal-move" ())
4357 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4358 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4359 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4360 (declare-function cdlatex-tab "ext:cdlatex" ())
4361 (declare-function dired-get-filename
4362 "dired"
4363 (&optional localp no-error-if-not-filep))
4364 (declare-function iswitchb-read-buffer
4365 "iswitchb"
4366 (prompt &optional
4367 default require-match _predicate start matches-set))
4368 (declare-function org-agenda-change-all-lines
4369 "org-agenda"
4370 (newhead hdmarker &optional fixface just-this))
4371 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4372 "org-agenda"
4373 (&optional end))
4374 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4375 (declare-function org-agenda-format-item
4376 "org-agenda"
4377 (extra txt &optional level category tags dotime
4378 remove-re habitp))
4379 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4380 (declare-function org-agenda-save-markers-for-cut-and-paste
4381 "org-agenda"
4382 (beg end))
4383 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4384 (declare-function org-agenda-skip "org-agenda" ())
4385 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4386 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4387 (declare-function org-indent-mode "org-indent" (&optional arg))
4388 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4389 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4390 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4391 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4392 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4393 (declare-function parse-time-string "parse-time" (string))
4395 (defvar align-mode-rules-list)
4396 (defvar calc-embedded-close-formula)
4397 (defvar calc-embedded-open-formula)
4398 (defvar calc-embedded-open-mode)
4399 (defvar font-lock-unfontify-region-function)
4400 (defvar iswitchb-temp-buflist)
4401 (defvar org-agenda-tags-todo-honor-ignore-options)
4402 (defvar remember-data-file)
4403 (defvar texmathp-why)
4405 ;;;###autoload
4406 (defun turn-on-orgtbl ()
4407 "Unconditionally turn on `orgtbl-mode'."
4408 (require 'org-table)
4409 (orgtbl-mode 1))
4411 (defun org-at-table-p (&optional table-type)
4412 "Non-nil if the cursor is inside an Org table.
4413 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4414 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4415 (or (not (derived-mode-p 'org-mode))
4416 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4417 (and e (or table-type
4418 (eq 'org (org-element-property :type e))))))))
4420 (defun org-at-table.el-p ()
4421 "Non-nil when point is at a table.el table."
4422 (and (org-match-line "[ \t]*[|+]")
4423 (let ((element (org-element-at-point)))
4424 (and (eq (org-element-type element) 'table)
4425 (eq (org-element-property :type element) 'table.el)))))
4427 (defun org-at-table-hline-p ()
4428 "Non-nil when point is inside a hline in a table.
4429 Assume point is already in a table."
4430 (org-match-line org-table-hline-regexp))
4432 (defun org-table-map-tables (function &optional quietly)
4433 "Apply FUNCTION to the start of all tables in the buffer."
4434 (org-with-wide-buffer
4435 (goto-char (point-min))
4436 (while (re-search-forward org-table-any-line-regexp nil t)
4437 (unless quietly
4438 (message "Mapping tables: %d%%"
4439 (floor (* 100.0 (point)) (buffer-size))))
4440 (beginning-of-line 1)
4441 (when (and (looking-at org-table-line-regexp)
4442 ;; Exclude tables in src/example/verbatim/clocktable blocks
4443 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4444 (save-excursion (funcall function))
4445 (or (looking-at org-table-line-regexp)
4446 (forward-char 1)))
4447 (re-search-forward org-table-any-border-regexp nil 1)))
4448 (unless quietly (message "Mapping tables: done")))
4450 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4451 (declare-function org-clock-update-mode-line "org-clock" ())
4452 (declare-function org-resolve-clocks "org-clock"
4453 (&optional also-non-dangling-p prompt last-valid))
4455 (defun org-at-TBLFM-p (&optional pos)
4456 "Non-nil when point (or POS) is in #+TBLFM line."
4457 (save-excursion
4458 (goto-char (or pos (point)))
4459 (beginning-of-line)
4460 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4461 (eq (org-element-type (org-element-at-point)) 'table))))
4463 (defvar org-clock-start-time)
4464 (defvar org-clock-marker (make-marker)
4465 "Marker recording the last clock-in.")
4466 (defvar org-clock-hd-marker (make-marker)
4467 "Marker recording the last clock-in, but the headline position.")
4468 (defvar org-clock-heading ""
4469 "The heading of the current clock entry.")
4470 (defun org-clock-is-active ()
4471 "Return the buffer where the clock is currently running.
4472 Return nil if no clock is running."
4473 (marker-buffer org-clock-marker))
4475 (defun org-check-running-clock ()
4476 "Check if the current buffer contains the running clock.
4477 If yes, offer to stop it and to save the buffer with the changes."
4478 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4479 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4480 (buffer-name))))
4481 (org-clock-out)
4482 (when (y-or-n-p "Save changed buffer?")
4483 (save-buffer))))
4485 (defun org-clocktable-try-shift (dir n)
4486 "Check if this line starts a clock table, if yes, shift the time block."
4487 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4488 (org-clocktable-shift dir n)))
4490 ;;;###autoload
4491 (defun org-clock-persistence-insinuate ()
4492 "Set up hooks for clock persistence."
4493 (require 'org-clock)
4494 (add-hook 'org-mode-hook 'org-clock-load)
4495 (add-hook 'kill-emacs-hook 'org-clock-save))
4497 (defgroup org-archive nil
4498 "Options concerning archiving in Org mode."
4499 :tag "Org Archive"
4500 :group 'org-structure)
4502 (defcustom org-archive-location "%s_archive::"
4503 "The location where subtrees should be archived.
4505 The value of this variable is a string, consisting of two parts,
4506 separated by a double-colon. The first part is a filename and
4507 the second part is a headline.
4509 When the filename is omitted, archiving happens in the same file.
4510 %s in the filename will be replaced by the current file
4511 name (without the directory part). Archiving to a different file
4512 is useful to keep archived entries from contributing to the
4513 Org Agenda.
4515 The archived entries will be filed as subtrees of the specified
4516 headline. When the headline is omitted, the subtrees are simply
4517 filed away at the end of the file, as top-level entries. Also in
4518 the heading you can use %s to represent the file name, this can be
4519 useful when using the same archive for a number of different files.
4521 Here are a few examples:
4522 \"%s_archive::\"
4523 If the current file is Projects.org, archive in file
4524 Projects.org_archive, as top-level trees. This is the default.
4526 \"::* Archived Tasks\"
4527 Archive in the current file, under the top-level headline
4528 \"* Archived Tasks\".
4530 \"~/org/archive.org::\"
4531 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4533 \"~/org/archive.org::* From %s\"
4534 Archive in file ~/org/archive.org (absolute path), under headlines
4535 \"From FILENAME\" where file name is the current file name.
4537 \"~/org/datetree.org::datetree/* Finished Tasks\"
4538 The \"datetree/\" string is special, signifying to archive
4539 items to the datetree. Items are placed in either the CLOSED
4540 date of the item, or the current date if there is no CLOSED date.
4541 The heading will be a subentry to the current date. There doesn't
4542 need to be a heading, but there always needs to be a slash after
4543 datetree. For example, to store archived items directly in the
4544 datetree, use \"~/org/datetree.org::datetree/\".
4546 \"basement::** Finished Tasks\"
4547 Archive in file ./basement (relative path), as level 3 trees
4548 below the level 2 heading \"** Finished Tasks\".
4550 You may set this option on a per-file basis by adding to the buffer a
4551 line like
4553 #+ARCHIVE: basement::** Finished Tasks
4555 You may also define it locally for a subtree by setting an ARCHIVE property
4556 in the entry. If such a property is found in an entry, or anywhere up
4557 the hierarchy, it will be used."
4558 :group 'org-archive
4559 :type 'string)
4561 (defcustom org-agenda-skip-archived-trees t
4562 "Non-nil means the agenda will skip any items located in archived trees.
4563 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4564 variable is no longer recommended, you should leave it at the value t.
4565 Instead, use the key `v' to cycle the archives-mode in the agenda."
4566 :group 'org-archive
4567 :group 'org-agenda-skip
4568 :type 'boolean)
4570 (defcustom org-columns-skip-archived-trees t
4571 "Non-nil means ignore archived trees when creating column view."
4572 :group 'org-archive
4573 :group 'org-properties
4574 :type 'boolean)
4576 (defcustom org-cycle-open-archived-trees nil
4577 "Non-nil means `org-cycle' will open archived trees.
4578 An archived tree is a tree marked with the tag ARCHIVE.
4579 When nil, archived trees will stay folded. You can still open them with
4580 normal outline commands like `show-all', but not with the cycling commands."
4581 :group 'org-archive
4582 :group 'org-cycle
4583 :type 'boolean)
4585 (defcustom org-sparse-tree-open-archived-trees nil
4586 "Non-nil means sparse tree construction shows matches in archived trees.
4587 When nil, matches in these trees are highlighted, but the trees are kept in
4588 collapsed state."
4589 :group 'org-archive
4590 :group 'org-sparse-trees
4591 :type 'boolean)
4593 (defcustom org-sparse-tree-default-date-type nil
4594 "The default date type when building a sparse tree.
4595 When this is nil, a date is a scheduled or a deadline timestamp.
4596 Otherwise, these types are allowed:
4598 all: all timestamps
4599 active: only active timestamps (<...>)
4600 inactive: only inactive timestamps ([...])
4601 scheduled: only scheduled timestamps
4602 deadline: only deadline timestamps"
4603 :type '(choice (const :tag "Scheduled or deadline" nil)
4604 (const :tag "All timestamps" all)
4605 (const :tag "Only active timestamps" active)
4606 (const :tag "Only inactive timestamps" inactive)
4607 (const :tag "Only scheduled timestamps" scheduled)
4608 (const :tag "Only deadline timestamps" deadline)
4609 (const :tag "Only closed timestamps" closed))
4610 :version "26.1"
4611 :package-version '(Org . "8.3")
4612 :group 'org-sparse-trees)
4614 (defun org-cycle-hide-archived-subtrees (state)
4615 "Re-hide all archived subtrees after a visibility state change.
4616 STATE should be one of the symbols listed in the docstring of
4617 `org-cycle-hook'."
4618 (when (and (not org-cycle-open-archived-trees)
4619 (not (memq state '(overview folded))))
4620 (save-excursion
4621 (let* ((globalp (memq state '(contents all)))
4622 (beg (if globalp (point-min) (point)))
4623 (end (if globalp (point-max) (org-end-of-subtree t))))
4624 (org-hide-archived-subtrees beg end)
4625 (goto-char beg)
4626 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4627 (message "%s" (substitute-command-keys
4628 "Subtree is archived and stays closed. Use \
4629 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4631 (defun org-force-cycle-archived ()
4632 "Cycle subtree even if it is archived."
4633 (interactive)
4634 (setq this-command 'org-cycle)
4635 (let ((org-cycle-open-archived-trees t))
4636 (call-interactively 'org-cycle)))
4638 (defun org-hide-archived-subtrees (beg end)
4639 "Re-hide all archived subtrees after a visibility state change."
4640 (org-with-wide-buffer
4641 (let ((case-fold-search nil)
4642 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4643 (goto-char beg)
4644 ;; Include headline point is currently on.
4645 (beginning-of-line)
4646 (while (and (< (point) end) (re-search-forward re end t))
4647 (when (member org-archive-tag (org-get-tags))
4648 (org-flag-subtree t)
4649 (org-end-of-subtree t))))))
4651 (declare-function outline-end-of-heading "outline" ())
4652 (declare-function outline-flag-region "outline" (from to flag))
4653 (defun org-flag-subtree (flag)
4654 (save-excursion
4655 (org-back-to-heading t)
4656 (outline-end-of-heading)
4657 (outline-flag-region (point)
4658 (progn (org-end-of-subtree t) (point))
4659 flag)))
4661 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4663 ;; Declare Column View Code
4665 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4666 (declare-function org-columns-compute "org-colview" (property))
4668 ;; Declare ID code
4670 (declare-function org-id-store-link "org-id")
4671 (declare-function org-id-locations-load "org-id")
4672 (declare-function org-id-locations-save "org-id")
4673 (defvar org-id-track-globally)
4675 ;;; Variables for pre-computed regular expressions, all buffer local
4677 (defvar-local org-todo-regexp nil
4678 "Matches any of the TODO state keywords.
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-not-done-regexp nil
4683 "Matches any of the TODO state keywords except the last one.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-not-done-heading-regexp nil
4688 "Matches a TODO headline that is not done.
4689 Since TODO keywords are case-sensitive, `case-fold-search' is
4690 expected to be bound to nil when matching against this regexp.")
4692 (defvar-local org-todo-line-regexp nil
4693 "Matches a headline and puts TODO state into group 2 if present.
4694 Since TODO keywords are case-sensitive, `case-fold-search' is
4695 expected to be bound to nil when matching against this regexp.")
4697 (defvar-local org-complex-heading-regexp nil
4698 "Matches a headline and puts everything into groups:
4700 group 1: Stars
4701 group 2: The TODO keyword, maybe
4702 group 3: Priority cookie
4703 group 4: True headline
4704 group 5: Tags
4706 Since TODO keywords are case-sensitive, `case-fold-search' is
4707 expected to be bound to nil when matching against this regexp.")
4709 (defvar-local org-complex-heading-regexp-format nil
4710 "Printf format to make regexp to match an exact headline.
4711 This regexp will match the headline of any node which has the
4712 exact headline text that is put into the format, but may have any
4713 TODO state, priority and tags.")
4715 (defvar-local org-todo-line-tags-regexp nil
4716 "Matches a headline and puts TODO state into group 2 if present.
4717 Also put tags into group 4 if tags are present.")
4719 (defconst org-plain-time-of-day-regexp
4720 (concat
4721 "\\(\\<[012]?[0-9]"
4722 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4723 "\\(--?"
4724 "\\(\\<[012]?[0-9]"
4725 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4726 "\\)?")
4727 "Regular expression to match a plain time or time range.
4728 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4729 groups carry important information:
4730 0 the full match
4731 1 the first time, range or not
4732 8 the second time, if it is a range.")
4734 (defconst org-plain-time-extension-regexp
4735 (concat
4736 "\\(\\<[012]?[0-9]"
4737 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4738 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4739 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4740 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4741 groups carry important information:
4742 0 the full match
4743 7 hours of duration
4744 9 minutes of duration")
4746 (defconst org-stamp-time-of-day-regexp
4747 (concat
4748 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4749 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4750 "\\(--?"
4751 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4752 "Regular expression to match a timestamp time or time range.
4753 After a match, the following groups carry important information:
4754 0 the full match
4755 1 date plus weekday, for back referencing to make sure both times are on the same day
4756 2 the first time, range or not
4757 4 the second time, if it is a range.")
4759 (defconst org-startup-options
4760 '(("fold" org-startup-folded t)
4761 ("overview" org-startup-folded t)
4762 ("nofold" org-startup-folded nil)
4763 ("showall" org-startup-folded nil)
4764 ("showeverything" org-startup-folded showeverything)
4765 ("content" org-startup-folded content)
4766 ("indent" org-startup-indented t)
4767 ("noindent" org-startup-indented nil)
4768 ("hidestars" org-hide-leading-stars t)
4769 ("showstars" org-hide-leading-stars nil)
4770 ("odd" org-odd-levels-only t)
4771 ("oddeven" org-odd-levels-only nil)
4772 ("align" org-startup-align-all-tables t)
4773 ("noalign" org-startup-align-all-tables nil)
4774 ("shrink" org-startup-shrink-all-tables t)
4775 ("inlineimages" org-startup-with-inline-images t)
4776 ("noinlineimages" org-startup-with-inline-images nil)
4777 ("latexpreview" org-startup-with-latex-preview t)
4778 ("nolatexpreview" org-startup-with-latex-preview nil)
4779 ("customtime" org-display-custom-times t)
4780 ("logdone" org-log-done time)
4781 ("lognotedone" org-log-done note)
4782 ("nologdone" org-log-done nil)
4783 ("lognoteclock-out" org-log-note-clock-out t)
4784 ("nolognoteclock-out" org-log-note-clock-out nil)
4785 ("logrepeat" org-log-repeat state)
4786 ("lognoterepeat" org-log-repeat note)
4787 ("logdrawer" org-log-into-drawer t)
4788 ("nologdrawer" org-log-into-drawer nil)
4789 ("logstatesreversed" org-log-states-order-reversed t)
4790 ("nologstatesreversed" org-log-states-order-reversed nil)
4791 ("nologrepeat" org-log-repeat nil)
4792 ("logreschedule" org-log-reschedule time)
4793 ("lognotereschedule" org-log-reschedule note)
4794 ("nologreschedule" org-log-reschedule nil)
4795 ("logredeadline" org-log-redeadline time)
4796 ("lognoteredeadline" org-log-redeadline note)
4797 ("nologredeadline" org-log-redeadline nil)
4798 ("logrefile" org-log-refile time)
4799 ("lognoterefile" org-log-refile note)
4800 ("nologrefile" org-log-refile nil)
4801 ("fninline" org-footnote-define-inline t)
4802 ("nofninline" org-footnote-define-inline nil)
4803 ("fnlocal" org-footnote-section nil)
4804 ("fnauto" org-footnote-auto-label t)
4805 ("fnprompt" org-footnote-auto-label nil)
4806 ("fnconfirm" org-footnote-auto-label confirm)
4807 ("fnplain" org-footnote-auto-label plain)
4808 ("fnadjust" org-footnote-auto-adjust t)
4809 ("nofnadjust" org-footnote-auto-adjust nil)
4810 ("constcgs" constants-unit-system cgs)
4811 ("constSI" constants-unit-system SI)
4812 ("noptag" org-tag-persistent-alist nil)
4813 ("hideblocks" org-hide-block-startup t)
4814 ("nohideblocks" org-hide-block-startup nil)
4815 ("beamer" org-startup-with-beamer-mode t)
4816 ("entitiespretty" org-pretty-entities t)
4817 ("entitiesplain" org-pretty-entities nil))
4818 "Variable associated with STARTUP options for org-mode.
4819 Each element is a list of three items: the startup options (as written
4820 in the #+STARTUP line), the corresponding variable, and the value to set
4821 this variable to if the option is found. An optional forth element PUSH
4822 means to push this value onto the list in the variable.")
4824 (defcustom org-group-tags t
4825 "When non-nil (the default), use group tags.
4826 This can be turned on/off through `org-toggle-tags-groups'."
4827 :group 'org-tags
4828 :group 'org-startup
4829 :type 'boolean)
4831 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4833 (defun org-toggle-tags-groups ()
4834 "Toggle support for group tags.
4835 Support for group tags is controlled by the option
4836 `org-group-tags', which is non-nil by default."
4837 (interactive)
4838 (setq org-group-tags (not org-group-tags))
4839 (cond ((and (derived-mode-p 'org-agenda-mode)
4840 org-group-tags)
4841 (org-agenda-redo))
4842 ((derived-mode-p 'org-mode)
4843 (let ((org-inhibit-startup t)) (org-mode))))
4844 (message "Groups tags support has been turned %s"
4845 (if org-group-tags "on" "off")))
4847 (defun org-set-regexps-and-options (&optional tags-only)
4848 "Precompute regular expressions used in the current buffer.
4849 When optional argument TAGS-ONLY is non-nil, only compute tags
4850 related expressions."
4851 (when (derived-mode-p 'org-mode)
4852 (let ((alist (org--setup-collect-keywords
4853 (org-make-options-regexp
4854 (append '("FILETAGS" "TAGS" "SETUPFILE")
4855 (and (not tags-only)
4856 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4857 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4858 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4859 ;; Startup options. Get this early since it does change
4860 ;; behavior for other options (e.g., tags).
4861 (let ((startup (cdr (assq 'startup alist))))
4862 (dolist (option startup)
4863 (let ((entry (assoc-string option org-startup-options t)))
4864 (when entry
4865 (let ((var (nth 1 entry))
4866 (val (nth 2 entry)))
4867 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4868 (unless (listp (symbol-value var))
4869 (set (make-local-variable var) nil))
4870 (add-to-list var val)))))))
4871 (setq-local org-file-tags
4872 (mapcar #'org-add-prop-inherited
4873 (cdr (assq 'filetags alist))))
4874 (setq org-current-tag-alist
4875 (append org-tag-persistent-alist
4876 (let ((tags (cdr (assq 'tags alist))))
4877 (if tags (org-tag-string-to-alist tags)
4878 org-tag-alist))))
4879 (setq org-tag-groups-alist
4880 (org-tag-alist-to-groups org-current-tag-alist))
4881 (unless tags-only
4882 ;; File properties.
4883 (setq-local org-file-properties (cdr (assq 'property alist)))
4884 ;; Archive location.
4885 (let ((archive (cdr (assq 'archive alist))))
4886 (when archive (setq-local org-archive-location archive)))
4887 ;; Category.
4888 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4889 (when cat
4890 (setq-local org-category (intern cat))
4891 (setq-local org-file-properties
4892 (org--update-property-plist
4893 "CATEGORY" cat org-file-properties))))
4894 ;; Columns.
4895 (let ((column (cdr (assq 'columns alist))))
4896 (when column (setq-local org-columns-default-format column)))
4897 ;; Constants.
4898 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4899 ;; Link abbreviations.
4900 (let ((links (cdr (assq 'link alist))))
4901 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4902 ;; Priorities.
4903 (let ((priorities (cdr (assq 'priorities alist))))
4904 (when priorities
4905 (setq-local org-highest-priority (nth 0 priorities))
4906 (setq-local org-lowest-priority (nth 1 priorities))
4907 (setq-local org-default-priority (nth 2 priorities))))
4908 ;; Scripts.
4909 (let ((scripts (assq 'scripts alist)))
4910 (when scripts
4911 (setq-local org-use-sub-superscripts (cdr scripts))))
4912 ;; TODO keywords.
4913 (setq-local org-todo-kwd-alist nil)
4914 (setq-local org-todo-key-alist nil)
4915 (setq-local org-todo-key-trigger nil)
4916 (setq-local org-todo-keywords-1 nil)
4917 (setq-local org-done-keywords nil)
4918 (setq-local org-todo-heads nil)
4919 (setq-local org-todo-sets nil)
4920 (setq-local org-todo-log-states nil)
4921 (let ((todo-sequences
4922 (or (nreverse (cdr (assq 'todo alist)))
4923 (let ((d (default-value 'org-todo-keywords)))
4924 (if (not (stringp (car d))) d
4925 ;; XXX: Backward compatibility code.
4926 (list (cons org-todo-interpretation d)))))))
4927 (dolist (sequence todo-sequences)
4928 (let* ((sequence (or (run-hook-with-args-until-success
4929 'org-todo-setup-filter-hook sequence)
4930 sequence))
4931 (sequence-type (car sequence))
4932 (keywords (cdr sequence))
4933 (sep (member "|" keywords))
4934 names alist)
4935 (dolist (k (remove "|" keywords))
4936 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4938 (error "Invalid TODO keyword %s" k))
4939 (let ((name (match-string 1 k))
4940 (key (match-string 2 k))
4941 (log (org-extract-log-state-settings k)))
4942 (push name names)
4943 (push (cons name (and key (string-to-char key))) alist)
4944 (when log (push log org-todo-log-states))))
4945 (let* ((names (nreverse names))
4946 (done (if sep (org-remove-keyword-keys (cdr sep))
4947 (last names)))
4948 (head (car names))
4949 (tail (list sequence-type head (car done) (org-last done))))
4950 (add-to-list 'org-todo-heads head 'append)
4951 (push names org-todo-sets)
4952 (setq org-done-keywords (append org-done-keywords done nil))
4953 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4954 (setq org-todo-key-alist
4955 (append org-todo-key-alist
4956 (and alist
4957 (append '((:startgroup))
4958 (nreverse alist)
4959 '((:endgroup))))))
4960 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4961 (setq org-todo-sets (nreverse org-todo-sets)
4962 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4963 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4964 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4965 ;; Compute the regular expressions and other local variables.
4966 ;; Using `org-outline-regexp-bol' would complicate them much,
4967 ;; because of the fixed white space at the end of that string.
4968 (unless org-done-keywords
4969 (setq org-done-keywords
4970 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4971 (setq org-not-done-keywords
4972 (org-delete-all org-done-keywords
4973 (copy-sequence org-todo-keywords-1))
4974 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4975 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4976 org-not-done-heading-regexp
4977 (format org-heading-keyword-regexp-format org-not-done-regexp)
4978 org-todo-line-regexp
4979 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4980 org-complex-heading-regexp
4981 (concat "^\\(\\*+\\)"
4982 "\\(?: +" org-todo-regexp "\\)?"
4983 "\\(?: +\\(\\[#.\\]\\)\\)?"
4984 "\\(?: +\\(.*?\\)\\)??"
4985 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4986 "[ \t]*$")
4987 org-complex-heading-regexp-format
4988 (concat "^\\(\\*+\\)"
4989 "\\(?: +" org-todo-regexp "\\)?"
4990 "\\(?: +\\(\\[#.\\]\\)\\)?"
4991 "\\(?: +"
4992 ;; Stats cookies can be stuck to body.
4993 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4994 "\\(%s\\)"
4995 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4996 "\\)"
4997 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4998 "[ \t]*$")
4999 org-todo-line-tags-regexp
5000 (concat "^\\(\\*+\\)"
5001 "\\(?: +" org-todo-regexp "\\)?"
5002 "\\(?: +\\(.*?\\)\\)??"
5003 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5004 "[ \t]*$"))
5005 (org-compute-latex-and-related-regexp)))))
5007 (defun org--setup-collect-keywords (regexp &optional files alist)
5008 "Return setup keywords values as an alist.
5010 REGEXP matches a subset of setup keywords. FILES is a list of
5011 file names already visited. It is used to avoid circular setup
5012 files. ALIST, when non-nil, is the alist computed so far.
5014 Return value contains the following keys: `archive', `category',
5015 `columns', `constants', `filetags', `link', `priorities',
5016 `property', `scripts', `startup', `tags' and `todo'."
5017 (org-with-wide-buffer
5018 (goto-char (point-min))
5019 (let ((case-fold-search t))
5020 (while (re-search-forward regexp nil t)
5021 (let ((element (org-element-at-point)))
5022 (when (eq (org-element-type element) 'keyword)
5023 (let ((key (org-element-property :key element))
5024 (value (org-element-property :value element)))
5025 (cond
5026 ((equal key "ARCHIVE")
5027 (when (org-string-nw-p value)
5028 (push (cons 'archive value) alist)))
5029 ((equal key "CATEGORY") (push (cons 'category value) alist))
5030 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5031 ((equal key "CONSTANTS")
5032 (let* ((constants (assq 'constants alist))
5033 (store (cdr constants)))
5034 (dolist (pair (split-string value))
5035 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5036 pair)
5037 (let* ((name (match-string 1 pair))
5038 (value (match-string 2 pair))
5039 (old (assoc name store)))
5040 (if old (setcdr old value)
5041 (push (cons name value) store)))))
5042 (if constants (setcdr constants store)
5043 (push (cons 'constants store) alist))))
5044 ((equal key "FILETAGS")
5045 (when (org-string-nw-p value)
5046 (let ((old (assq 'filetags alist))
5047 (new (apply #'nconc
5048 (mapcar (lambda (x) (org-split-string x ":"))
5049 (split-string value)))))
5050 (if old (setcdr old (append new (cdr old)))
5051 (push (cons 'filetags new) alist)))))
5052 ((equal key "LINK")
5053 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5054 (let ((links (assq 'link alist))
5055 (pair (cons (match-string-no-properties 1 value)
5056 (match-string-no-properties 2 value))))
5057 (if links (push pair (cdr links))
5058 (push (list 'link pair) alist)))))
5059 ((equal key "OPTIONS")
5060 (when (and (org-string-nw-p value)
5061 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5062 (push (cons 'scripts (read (match-string 1 value))) alist)))
5063 ((equal key "PRIORITIES")
5064 (push (cons 'priorities
5065 (let ((prio (split-string value)))
5066 (if (< (length prio) 3) '(?A ?C ?B)
5067 (mapcar #'string-to-char prio))))
5068 alist))
5069 ((equal key "PROPERTY")
5070 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5071 (let* ((property (assq 'property alist))
5072 (value (org--update-property-plist
5073 (match-string-no-properties 1 value)
5074 (match-string-no-properties 2 value)
5075 (cdr property))))
5076 (if property (setcdr property value)
5077 (push (cons 'property value) alist)))))
5078 ((equal key "STARTUP")
5079 (let ((startup (assq 'startup alist)))
5080 (if startup
5081 (setcdr startup
5082 (append (cdr startup) (split-string value)))
5083 (push (cons 'startup (split-string value)) alist))))
5084 ((equal key "TAGS")
5085 (let ((tag-cell (assq 'tags alist)))
5086 (if tag-cell
5087 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5088 (push (cons 'tags value) alist))))
5089 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5090 (let ((todo (assq 'todo alist))
5091 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5092 (split-string value))))
5093 (if todo (push value (cdr todo))
5094 (push (list 'todo value) alist))))
5095 ((equal key "SETUPFILE")
5096 (unless buffer-read-only ; Do not check in Gnus messages.
5097 (let ((f (and (org-string-nw-p value)
5098 (expand-file-name
5099 (org-unbracket-string "\"" "\"" value)))))
5100 (when (and f (file-readable-p f) (not (member f files)))
5101 (with-temp-buffer
5102 (setq default-directory (file-name-directory f))
5103 (insert-file-contents f)
5104 (setq alist
5105 ;; Fake Org mode to benefit from cache
5106 ;; without recurring needlessly.
5107 (let ((major-mode 'org-mode))
5108 (org--setup-collect-keywords
5109 regexp (cons f files) alist)))))))))))))))
5110 alist)
5112 (defun org-tag-string-to-alist (s)
5113 "Return tag alist associated to string S.
5114 S is a value for TAGS keyword or produced with
5115 `org-tag-alist-to-string'. Return value is an alist suitable for
5116 `org-tag-alist' or `org-tag-persistent-alist'."
5117 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5118 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5119 "\\|{.+?}\\)" ; regular expression
5120 "\\(?:(\\(.\\))\\)?\\'"))
5121 alist group-flag)
5122 (dolist (tokens lines (cdr (nreverse alist)))
5123 (push '(:newline) alist)
5124 (while tokens
5125 (let ((token (pop tokens)))
5126 (pcase token
5127 ("{"
5128 (push '(:startgroup) alist)
5129 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5130 ("}"
5131 (push '(:endgroup) alist)
5132 (setq group-flag nil))
5133 ("["
5134 (push '(:startgrouptag) alist)
5135 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5136 ("]"
5137 (push '(:endgrouptag) alist)
5138 (setq group-flag nil))
5139 (":"
5140 (push '(:grouptags) alist))
5141 ((guard (string-match tag-re token))
5142 (let ((tag (match-string 1 token))
5143 (key (and (match-beginning 2)
5144 (string-to-char (match-string 2 token)))))
5145 ;; Push all tags in groups, no matter if they already
5146 ;; appear somewhere else in the list.
5147 (when (or group-flag (not (assoc tag alist)))
5148 (push (cons tag key) alist))))))))))
5150 (defun org-tag-alist-to-string (alist &optional skip-key)
5151 "Return tag string associated to ALIST.
5153 ALIST is an alist, as defined in `org-tag-alist' or
5154 `org-tag-persistent-alist', or produced with
5155 `org-tag-string-to-alist'.
5157 Return value is a string suitable as a value for \"TAGS\"
5158 keyword.
5160 When optional argument SKIP-KEY is non-nil, skip selection keys
5161 next to tags."
5162 (mapconcat (lambda (token)
5163 (pcase token
5164 (`(:startgroup) "{")
5165 (`(:endgroup) "}")
5166 (`(:startgrouptag) "[")
5167 (`(:endgrouptag) "]")
5168 (`(:grouptags) ":")
5169 (`(:newline) "\\n")
5170 ((and
5171 (guard (not skip-key))
5172 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5173 (format "%s(%c)" tag key))
5174 (`(,(and tag (pred stringp)) . ,_) tag)
5175 (_ (user-error "Invalid tag token: %S" token))))
5176 alist
5177 " "))
5179 (defun org-tag-alist-to-groups (alist)
5180 "Return group alist from tag ALIST.
5181 ALIST is an alist, as defined in `org-tag-alist' or
5182 `org-tag-persistent-alist', or produced with
5183 `org-tag-string-to-alist'. Return value is an alist following
5184 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5185 a string, summarizing TAGS, as a list of strings."
5186 (let (groups group-status current-group)
5187 (dolist (token alist (nreverse groups))
5188 (pcase token
5189 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5190 (`(,(or :endgroup :endgrouptag))
5191 (when (eq group-status 'append)
5192 (push (nreverse current-group) groups))
5193 (setq group-status nil))
5194 (`(:grouptags) (setq group-status 'append))
5195 ((and `(,tag . ,_) (guard group-status))
5196 (if (eq group-status 'append) (push tag current-group)
5197 (setq current-group (list tag))))
5198 (_ nil)))))
5200 (defvar org--file-cache (make-hash-table :test #'equal)
5201 "Hash table to store contents of files referenced via a URL.
5202 This is the cache of file URLs read using `org-file-contents'.")
5204 (defun org-reset-file-cache ()
5205 "Reset the cache of files downloaded by `org-file-contents'."
5206 (clrhash org--file-cache))
5208 (defun org-file-url-p (file)
5209 "Non-nil if FILE is a URL."
5210 (require 'ffap)
5211 (string-match-p ffap-url-regexp file))
5213 (defun org-file-contents (file &optional noerror nocache)
5214 "Return the contents of FILE, as a string.
5216 FILE can be a file name or URL.
5218 If FILE is a URL, download the contents. If the URL contents are
5219 already cached in the `org--file-cache' hash table, the download step
5220 is skipped.
5222 If NOERROR is non-nil, ignore the error when unable to read the FILE
5223 from file or URL.
5225 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5226 is available. This option applies only if FILE is a URL."
5227 (let* ((is-url (org-file-url-p file))
5228 (cache (and is-url
5229 (not nocache)
5230 (gethash file org--file-cache))))
5231 (cond
5232 (cache)
5233 (is-url
5234 (with-current-buffer (url-retrieve-synchronously file)
5235 (goto-char (point-min))
5236 ;; Move point to after the url-retrieve header.
5237 (search-forward "\n\n" nil :move)
5238 ;; Search for the success code only in the url-retrieve header.
5239 (if (save-excursion
5240 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5241 ;; Update the cache `org--file-cache' and return contents.
5242 (puthash file
5243 (buffer-substring-no-properties (point) (point-max))
5244 org--file-cache)
5245 (funcall (if noerror #'message #'user-error)
5246 "Unable to fetch file from %S"
5247 file))))
5249 (with-temp-buffer
5250 (condition-case nil
5251 (progn
5252 (insert-file-contents file)
5253 (buffer-string))
5254 (file-error
5255 (funcall (if noerror #'message #'user-error)
5256 "Unable to read file %S"
5257 file))))))))
5259 (defun org-extract-log-state-settings (x)
5260 "Extract the log state setting from a TODO keyword string.
5261 This will extract info from a string like \"WAIT(w@/!)\"."
5262 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5263 (let ((kw (match-string 1 x))
5264 (log1 (and (match-end 3) (match-string 3 x)))
5265 (log2 (and (match-end 4) (match-string 4 x))))
5266 (and (or log1 log2)
5267 (list kw
5268 (and log1 (if (equal log1 "!") 'time 'note))
5269 (and log2 (if (equal log2 "!") 'time 'note)))))))
5271 (defun org-remove-keyword-keys (list)
5272 "Remove a pair of parenthesis at the end of each string in LIST."
5273 (mapcar (lambda (x)
5274 (if (string-match "(.*)$" x)
5275 (substring x 0 (match-beginning 0))
5277 list))
5279 (defun org-assign-fast-keys (alist)
5280 "Assign fast keys to a keyword-key alist.
5281 Respect keys that are already there."
5282 (let (new e (alt ?0))
5283 (while (setq e (pop alist))
5284 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5285 (cdr e)) ;; Key already assigned.
5286 (push e new)
5287 (let ((clist (string-to-list (downcase (car e))))
5288 (used (append new alist)))
5289 (when (= (car clist) ?@)
5290 (pop clist))
5291 (while (and clist (rassoc (car clist) used))
5292 (pop clist))
5293 (unless clist
5294 (while (rassoc alt used)
5295 (cl-incf alt)))
5296 (push (cons (car e) (or (car clist) alt)) new))))
5297 (nreverse new)))
5299 ;;; Some variables used in various places
5301 (defvar org-window-configuration nil
5302 "Used in various places to store a window configuration.")
5303 (defvar org-selected-window nil
5304 "Used in various places to store a window configuration.")
5305 (defvar org-finish-function nil
5306 "Function to be called when `C-c C-c' is used.
5307 This is for getting out of special buffers like capture.")
5308 (defvar org-last-state)
5310 ;; Defined somewhere in this file, but used before definition.
5311 (defvar org-entities) ;; defined in org-entities.el
5312 (defvar org-struct-menu)
5313 (defvar org-org-menu)
5314 (defvar org-tbl-menu)
5316 ;;;; Define the Org mode
5318 ;; We use a before-change function to check if a table might need
5319 ;; an update.
5320 (defvar org-table-may-need-update t
5321 "Indicates that a table might need an update.
5322 This variable is set by `org-before-change-function'.
5323 `org-table-align' sets it back to nil.")
5324 (defun org-before-change-function (_beg _end)
5325 "Every change indicates that a table might need an update."
5326 (setq org-table-may-need-update t))
5327 (defvar org-mode-map)
5328 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5329 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5330 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5331 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5332 (defvar org-table-buffer-is-an nil)
5334 (defvar bidi-paragraph-direction)
5335 (defvar buffer-face-mode-face)
5337 (require 'outline)
5339 ;; Other stuff we need.
5340 (require 'time-date)
5341 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5342 (require 'easymenu)
5343 (autoload 'easy-menu-add "easymenu")
5344 (require 'overlay)
5346 ;; (require 'org-macs) moved higher up in the file before it is first used
5347 (require 'org-entities)
5348 ;; (require 'org-compat) moved higher up in the file before it is first used
5349 (require 'org-faces)
5350 (require 'org-list)
5351 (require 'org-pcomplete)
5352 (require 'org-src)
5353 (require 'org-footnote)
5354 (require 'org-macro)
5356 ;; babel
5357 (require 'ob)
5359 ;;;###autoload
5360 (define-derived-mode org-mode outline-mode "Org"
5361 "Outline-based notes management and organizer, alias
5362 \"Carsten's outline-mode for keeping track of everything.\"
5364 Org mode develops organizational tasks around a NOTES file which
5365 contains information about projects as plain text. Org mode is
5366 implemented on top of Outline mode, which is ideal to keep the content
5367 of large files well structured. It supports ToDo items, deadlines and
5368 time stamps, which magically appear in the diary listing of the Emacs
5369 calendar. Tables are easily created with a built-in table editor.
5370 Plain text URL-like links connect to websites, emails (VM), Usenet
5371 messages (Gnus), BBDB entries, and any files related to the project.
5372 For printing and sharing of notes, an Org file (or a part of it)
5373 can be exported as a structured ASCII or HTML file.
5375 The following commands are available:
5377 \\{org-mode-map}"
5379 ;; Get rid of Outline menus, they are not needed
5380 ;; Need to do this here because define-derived-mode sets up
5381 ;; the keymap so late. Still, it is a waste to call this each time
5382 ;; we switch another buffer into Org mode.
5383 (define-key org-mode-map [menu-bar headings] 'undefined)
5384 (define-key org-mode-map [menu-bar hide] 'undefined)
5385 (define-key org-mode-map [menu-bar show] 'undefined)
5387 (org-load-modules-maybe)
5388 (org-install-agenda-files-menu)
5389 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5390 (add-to-invisibility-spec '(org-hide-block . t))
5391 (setq-local outline-regexp org-outline-regexp)
5392 (setq-local outline-level 'org-outline-level)
5393 (setq bidi-paragraph-direction 'left-to-right)
5394 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5395 (unless org-display-table
5396 (setq org-display-table (make-display-table)))
5397 (set-display-table-slot
5398 org-display-table 4
5399 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5400 org-ellipsis)))
5401 (setq buffer-display-table org-display-table))
5402 (org-set-regexps-and-options)
5403 (org-set-font-lock-defaults)
5404 (when (and org-tag-faces (not org-tags-special-faces-re))
5405 ;; tag faces set outside customize.... force initialization.
5406 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5407 ;; Calc embedded
5408 (setq-local calc-embedded-open-mode "# ")
5409 ;; Modify a few syntax entries
5410 (modify-syntax-entry ?@ "w")
5411 (modify-syntax-entry ?\" "\"")
5412 (modify-syntax-entry ?\\ "_")
5413 (modify-syntax-entry ?~ "_")
5414 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5415 ;; Activate before-change-function
5416 (setq-local org-table-may-need-update t)
5417 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5418 ;; Check for running clock before killing a buffer
5419 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5420 ;; Initialize macros templates.
5421 (org-macro-initialize-templates)
5422 ;; Initialize radio targets.
5423 (org-update-radio-target-regexp)
5424 ;; Indentation.
5425 (setq-local indent-line-function 'org-indent-line)
5426 (setq-local indent-region-function 'org-indent-region)
5427 ;; Filling and auto-filling.
5428 (org-setup-filling)
5429 ;; Comments.
5430 (org-setup-comments-handling)
5431 ;; Initialize cache.
5432 (org-element-cache-reset)
5433 ;; Beginning/end of defun
5434 (setq-local beginning-of-defun-function 'org-backward-element)
5435 (setq-local end-of-defun-function
5436 (lambda ()
5437 (if (not (org-at-heading-p))
5438 (org-forward-element)
5439 (org-forward-element)
5440 (forward-char -1))))
5441 ;; Next error for sparse trees
5442 (setq-local next-error-function 'org-occur-next-match)
5443 ;; Make sure dependence stuff works reliably, even for users who set it
5444 ;; too late :-(
5445 (if org-enforce-todo-dependencies
5446 (add-hook 'org-blocker-hook
5447 'org-block-todo-from-children-or-siblings-or-parent)
5448 (remove-hook 'org-blocker-hook
5449 'org-block-todo-from-children-or-siblings-or-parent))
5450 (if org-enforce-todo-checkbox-dependencies
5451 (add-hook 'org-blocker-hook
5452 'org-block-todo-from-checkboxes)
5453 (remove-hook 'org-blocker-hook
5454 'org-block-todo-from-checkboxes))
5456 ;; Align options lines
5457 (setq-local
5458 align-mode-rules-list
5459 '((org-in-buffer-settings
5460 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5461 (modes . '(org-mode)))))
5463 ;; Imenu
5464 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5466 ;; Make isearch reveal context
5467 (setq-local outline-isearch-open-invisible-function
5468 (lambda (&rest _) (org-show-context 'isearch)))
5470 ;; Setup the pcomplete hooks
5471 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5472 (setq-local pcomplete-command-name-function 'org-command-at-point)
5473 (setq-local pcomplete-default-completion-function 'ignore)
5474 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5475 (setq-local pcomplete-termination-string "")
5476 (setq-local buffer-face-mode-face 'org-default)
5478 ;; If empty file that did not turn on Org mode automatically, make
5479 ;; it to.
5480 (when (and org-insert-mode-line-in-empty-file
5481 (called-interactively-p 'any)
5482 (= (point-min) (point-max)))
5483 (insert "# -*- mode: org -*-\n\n"))
5484 (unless org-inhibit-startup
5485 (org-unmodified
5486 (when org-startup-with-beamer-mode (org-beamer-mode))
5487 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5488 (org-table-map-tables
5489 (cond ((and org-startup-align-all-tables
5490 org-startup-shrink-all-tables)
5491 (lambda () (org-table-align) (org-table-shrink)))
5492 (org-startup-align-all-tables #'org-table-align)
5493 (t #'org-table-shrink))
5495 (when org-startup-with-inline-images (org-display-inline-images))
5496 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5497 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5498 (when org-startup-truncated (setq truncate-lines t))
5499 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5500 (org-refresh-effort-properties)))
5501 ;; Try to set `org-hide' face correctly.
5502 (let ((foreground (org-find-invisible-foreground)))
5503 (when foreground
5504 (set-face-foreground 'org-hide foreground))))
5506 ;; Update `customize-package-emacs-version-alist'
5507 (add-to-list 'customize-package-emacs-version-alist
5508 '(Org ("8.0" . "24.4")
5509 ("8.1" . "24.4")
5510 ("8.2" . "24.4")
5511 ("8.2.7" . "24.4")
5512 ("8.3" . "26.1")
5513 ("9.0" . "26.1")
5514 ("9.1" . "26.1")
5515 ("9.2" . "27.1")))
5517 (defvar org-mode-transpose-word-syntax-table
5518 (let ((st (make-syntax-table text-mode-syntax-table)))
5519 (dolist (c org-emphasis-alist st)
5520 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5522 (when (fboundp 'abbrev-table-put)
5523 (abbrev-table-put org-mode-abbrev-table
5524 :parents (list text-mode-abbrev-table)))
5526 (defun org-find-invisible-foreground ()
5527 (let ((candidates (remove
5528 "unspecified-bg"
5529 (nconc
5530 (list (face-background 'default)
5531 (face-background 'org-default))
5532 (mapcar
5533 (lambda (alist)
5534 (when (boundp alist)
5535 (cdr (assq 'background-color (symbol-value alist)))))
5536 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5537 (list (face-foreground 'org-hide))))))
5538 (car (remove nil candidates))))
5540 (defun org-current-time (&optional rounding-minutes past)
5541 "Current time, possibly rounded to ROUNDING-MINUTES.
5542 When ROUNDING-MINUTES is not an integer, fall back on the car of
5543 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5544 the rounding returns a past time."
5545 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5546 (car org-time-stamp-rounding-minutes)))
5547 (time (decode-time)) res)
5548 (if (< r 1)
5549 (current-time)
5550 (setq res
5551 (apply 'encode-time
5552 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5553 (nthcdr 2 time))))
5554 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5555 (seconds-to-time (- (float-time res) (* r 60)))
5556 res))))
5558 (defun org-today ()
5559 "Return today date, considering `org-extend-today-until'."
5560 (time-to-days
5561 (time-subtract (current-time)
5562 (list 0 (* 3600 org-extend-today-until) 0))))
5564 ;;;; Font-Lock stuff, including the activators
5566 (defvar org-mouse-map (make-sparse-keymap))
5567 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5568 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5569 (when org-mouse-1-follows-link
5570 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5571 (when org-tab-follows-link
5572 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5573 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5575 (require 'font-lock)
5577 (defconst org-non-link-chars "]\t\n\r<>")
5578 (defvar org-link-types-re nil
5579 "Matches a link that has a url-like prefix like \"http:\"")
5580 (defvar org-link-re-with-space nil
5581 "Matches a link with spaces, optional angular brackets around it.")
5582 (defvar org-link-re-with-space2 nil
5583 "Matches a link with spaces, optional angular brackets around it.")
5584 (defvar org-link-re-with-space3 nil
5585 "Matches a link with spaces, only for internal part in bracket links.")
5586 (defvar org-angle-link-re nil
5587 "Matches link with angular brackets, spaces are allowed.")
5588 (defvar org-plain-link-re nil
5589 "Matches plain link, without spaces.")
5590 (defvar org-bracket-link-regexp nil
5591 "Matches a link in double brackets.")
5592 (defvar org-bracket-link-analytic-regexp nil
5593 "Regular expression used to analyze links.
5594 Here is what the match groups contain after a match:
5595 1: http:
5596 2: http
5597 3: path
5598 4: [desc]
5599 5: desc")
5600 (defvar org-bracket-link-analytic-regexp++ nil
5601 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5602 (defvar org-any-link-re nil
5603 "Regular expression matching any link.")
5605 (defconst org-match-sexp-depth 3
5606 "Number of stacked braces for sub/superscript matching.")
5608 (defun org-create-multibrace-regexp (left right n)
5609 "Create a regular expression which will match a balanced sexp.
5610 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5611 as single character strings.
5612 The regexp returned will match the entire expression including the
5613 delimiters. It will also define a single group which contains the
5614 match except for the outermost delimiters. The maximum depth of
5615 stacked delimiters is N. Escaping delimiters is not possible."
5616 (let* ((nothing (concat "[^" left right "]*?"))
5617 (or "\\|")
5618 (re nothing)
5619 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5620 (while (> n 1)
5621 (setq n (1- n)
5622 re (concat re or next)
5623 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5624 (concat left "\\(" re "\\)" right)))
5626 (defconst org-match-substring-regexp
5627 (concat
5628 "\\(\\S-\\)\\([_^]\\)\\("
5629 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5630 "\\|"
5631 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5632 "\\|"
5633 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5634 "The regular expression matching a sub- or superscript.")
5636 (defconst org-match-substring-with-braces-regexp
5637 (concat
5638 "\\(\\S-\\)\\([_^]\\)"
5639 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5640 "The regular expression matching a sub- or superscript, forcing braces.")
5642 (defun org-make-link-regexps ()
5643 "Update the link regular expressions.
5644 This should be called after the variable `org-link-parameters' has changed."
5645 (let ((types-re (regexp-opt (org-link-types) t)))
5646 (setq org-link-types-re
5647 (concat "\\`" types-re ":")
5648 org-link-re-with-space
5649 (concat "<?" types-re ":"
5650 "\\([^" org-non-link-chars " ]"
5651 "[^" org-non-link-chars "]*"
5652 "[^" org-non-link-chars " ]\\)>?")
5653 org-link-re-with-space2
5654 (concat "<?" types-re ":"
5655 "\\([^" org-non-link-chars " ]"
5656 "[^\t\n\r]*"
5657 "[^" org-non-link-chars " ]\\)>?")
5658 org-link-re-with-space3
5659 (concat "<?" types-re ":"
5660 "\\([^" org-non-link-chars " ]"
5661 "[^\t\n\r]*\\)")
5662 org-angle-link-re
5663 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5664 types-re)
5665 org-plain-link-re
5666 (concat
5667 "\\<" types-re ":"
5668 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5669 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5670 org-bracket-link-regexp
5671 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5672 org-bracket-link-analytic-regexp
5673 (concat
5674 "\\[\\["
5675 "\\(" types-re ":\\)?"
5676 "\\([^]]+\\)"
5677 "\\]"
5678 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5679 "\\]")
5680 org-bracket-link-analytic-regexp++
5681 (concat
5682 "\\[\\["
5683 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5684 "\\([^]]+\\)"
5685 "\\]"
5686 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5687 "\\]")
5688 org-any-link-re
5689 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5690 org-angle-link-re "\\)\\|\\("
5691 org-plain-link-re "\\)"))))
5693 (org-make-link-regexps)
5695 (defvar org-emph-face nil)
5697 (defun org-do-emphasis-faces (limit)
5698 "Run through the buffer and emphasize strings."
5699 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5700 (car org-emphasis-regexp-components))))
5701 (catch :exit
5702 (while (re-search-forward quick-re limit t)
5703 (let* ((marker (match-string 2))
5704 (verbatim? (member marker '("~" "="))))
5705 (when (save-excursion
5706 (goto-char (match-beginning 0))
5707 (and
5708 ;; Do not match table hlines.
5709 (not (and (equal marker "+")
5710 (org-match-line
5711 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5712 ;; Match full emphasis markup regexp.
5713 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5714 ;; Do not span over paragraph boundaries.
5715 (not (string-match-p org-element-paragraph-separate
5716 (match-string 2)))
5717 ;; Do not span over cells in table rows.
5718 (not (and (save-match-data (org-match-line "[ \t]*|"))
5719 (string-match-p "|" (match-string 4))))))
5720 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5721 (font-lock-prepend-text-property
5722 (match-beginning 2) (match-end 2) 'face face)
5723 (when verbatim?
5724 (org-remove-flyspell-overlays-in
5725 (match-beginning 0) (match-end 0)))
5726 (add-text-properties (match-beginning 2) (match-end 2)
5727 '(font-lock-multiline t org-emphasis t))
5728 (when org-hide-emphasis-markers
5729 (add-text-properties (match-end 4) (match-beginning 5)
5730 '(invisible org-link))
5731 (add-text-properties (match-beginning 3) (match-end 3)
5732 '(invisible org-link)))
5733 (throw :exit t))))))))
5735 (defun org-emphasize (&optional char)
5736 "Insert or change an emphasis, i.e. a font like bold or italic.
5737 If there is an active region, change that region to a new emphasis.
5738 If there is no region, just insert the marker characters and position
5739 the cursor between them.
5740 CHAR should be the marker character. If it is a space, it means to
5741 remove the emphasis of the selected region.
5742 If CHAR is not given (for example in an interactive call) it will be
5743 prompted for."
5744 (interactive)
5745 (let ((erc org-emphasis-regexp-components)
5746 (string "") beg end move s)
5747 (if (org-region-active-p)
5748 (setq beg (region-beginning)
5749 end (region-end)
5750 string (buffer-substring beg end))
5751 (setq move t))
5753 (unless char
5754 (message "Emphasis marker or tag: [%s]"
5755 (mapconcat #'car org-emphasis-alist ""))
5756 (setq char (read-char-exclusive)))
5757 (if (equal char ?\s)
5758 (setq s ""
5759 move nil)
5760 (unless (assoc (char-to-string char) org-emphasis-alist)
5761 (user-error "No such emphasis marker: \"%c\"" char))
5762 (setq s (char-to-string char)))
5763 (while (and (> (length string) 1)
5764 (equal (substring string 0 1) (substring string -1))
5765 (assoc (substring string 0 1) org-emphasis-alist))
5766 (setq string (substring string 1 -1)))
5767 (setq string (concat s string s))
5768 (when beg (delete-region beg end))
5769 (unless (or (bolp)
5770 (string-match (concat "[" (nth 0 erc) "\n]")
5771 (char-to-string (char-before (point)))))
5772 (insert " "))
5773 (unless (or (eobp)
5774 (string-match (concat "[" (nth 1 erc) "\n]")
5775 (char-to-string (char-after (point)))))
5776 (insert " ") (backward-char 1))
5777 (insert string)
5778 (and move (backward-char 1))))
5780 (defconst org-nonsticky-props
5781 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5783 (defsubst org-rear-nonsticky-at (pos)
5784 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5786 (defun org-activate-links (limit)
5787 "Add link properties to links.
5788 This includes angle, plain, and bracket links."
5789 (catch :exit
5790 (while (re-search-forward org-any-link-re limit t)
5791 (let* ((start (match-beginning 0))
5792 (end (match-end 0))
5793 (style (cond ((eq ?< (char-after start)) 'angle)
5794 ((eq ?\[ (char-after (1+ start))) 'bracket)
5795 (t 'plain))))
5796 (when (and (memq style org-highlight-links)
5797 ;; Do not confuse plain links with tags.
5798 (not (and (eq style 'plain)
5799 (let ((face (get-text-property
5800 (max (1- start) (point-min)) 'face)))
5801 (if (consp face) (memq 'org-tag face)
5802 (eq 'org-tag face))))))
5803 (let* ((link-object (save-excursion
5804 (goto-char start)
5805 (save-match-data (org-element-link-parser))))
5806 (link (org-element-property :raw-link link-object))
5807 (type (org-element-property :type link-object))
5808 (path (org-element-property :path link-object))
5809 (properties ;for link's visible part
5810 (list
5811 'face (pcase (org-link-get-parameter type :face)
5812 ((and (pred functionp) face) (funcall face path))
5813 ((and (pred facep) face) face)
5814 ((and (pred consp) face) face) ;anonymous
5815 (_ 'org-link))
5816 'mouse-face (or (org-link-get-parameter type :mouse-face)
5817 'highlight)
5818 'keymap (or (org-link-get-parameter type :keymap)
5819 org-mouse-map)
5820 'help-echo (pcase (org-link-get-parameter type :help-echo)
5821 ((and (pred stringp) echo) echo)
5822 ((and (pred functionp) echo) echo)
5823 (_ (concat "LINK: " link)))
5824 'htmlize-link (pcase (org-link-get-parameter type
5825 :htmlize-link)
5826 ((and (pred functionp) f) (funcall f))
5827 (_ `(:uri ,link)))
5828 'font-lock-multiline t)))
5829 (org-remove-flyspell-overlays-in start end)
5830 (org-rear-nonsticky-at end)
5831 (if (not (eq 'bracket style))
5832 (add-text-properties start end properties)
5833 ;; Handle invisible parts in bracket links.
5834 (remove-text-properties start end '(invisible nil))
5835 (let ((hidden
5836 (append `(invisible
5837 ,(or (org-link-get-parameter type :display)
5838 'org-link))
5839 properties))
5840 (visible-start (or (match-beginning 4) (match-beginning 2)))
5841 (visible-end (or (match-end 4) (match-end 2))))
5842 (add-text-properties start visible-start hidden)
5843 (add-text-properties visible-start visible-end properties)
5844 (add-text-properties visible-end end hidden)
5845 (org-rear-nonsticky-at visible-start)
5846 (org-rear-nonsticky-at visible-end)))
5847 (let ((f (org-link-get-parameter type :activate-func)))
5848 (when (functionp f)
5849 (funcall f start end path (eq style 'bracket))))
5850 (throw :exit t))))) ;signal success
5851 nil))
5853 (defun org-activate-code (limit)
5854 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5855 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5856 (remove-text-properties (match-beginning 0) (match-end 0)
5857 '(display t invisible t intangible t))
5860 (defcustom org-src-fontify-natively t
5861 "When non-nil, fontify code in code blocks.
5862 See also the `org-block' face."
5863 :type 'boolean
5864 :version "26.1"
5865 :package-version '(Org . "8.3")
5866 :group 'org-appearance
5867 :group 'org-babel)
5869 (defcustom org-allow-promoting-top-level-subtree nil
5870 "When non-nil, allow promoting a top level subtree.
5871 The leading star of the top level headline will be replaced
5872 by a #."
5873 :type 'boolean
5874 :version "24.1"
5875 :group 'org-appearance)
5877 (defun org-fontify-meta-lines-and-blocks (limit)
5878 (condition-case nil
5879 (org-fontify-meta-lines-and-blocks-1 limit)
5880 (error (message "org-mode fontification error in %S at %d"
5881 (current-buffer)
5882 (line-number-at-pos)))))
5884 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5885 "Fontify #+ lines and blocks."
5886 (let ((case-fold-search t))
5887 (when (re-search-forward
5888 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5889 limit t)
5890 (let ((beg (match-beginning 0))
5891 (block-start (match-end 0))
5892 (block-end nil)
5893 (lang (match-string 7))
5894 (beg1 (line-beginning-position 2))
5895 (dc1 (downcase (match-string 2)))
5896 (dc3 (downcase (match-string 3)))
5897 end end1 quoting block-type)
5898 (cond
5899 ((and (match-end 4) (equal dc3 "+begin"))
5900 ;; Truly a block
5901 (setq block-type (downcase (match-string 5))
5902 quoting (member block-type org-protecting-blocks))
5903 (when (re-search-forward
5904 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5905 nil t) ;; on purpose, we look further than LIMIT
5906 (setq end (min (point-max) (match-end 0))
5907 end1 (min (point-max) (1- (match-beginning 0))))
5908 (setq block-end (match-beginning 0))
5909 (when quoting
5910 (org-remove-flyspell-overlays-in beg1 end1)
5911 (remove-text-properties beg end
5912 '(display t invisible t intangible t)))
5913 (add-text-properties
5914 beg end '(font-lock-fontified t font-lock-multiline t))
5915 (add-text-properties beg beg1 '(face org-meta-line))
5916 (org-remove-flyspell-overlays-in beg beg1)
5917 (add-text-properties ; For end_src
5918 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in end1 end)
5920 (cond
5921 ((and lang (not (string= lang "")) org-src-fontify-natively)
5922 (org-src-font-lock-fontify-block lang block-start block-end)
5923 (add-text-properties beg1 block-end '(src-block t)))
5924 (quoting
5925 (add-text-properties beg1 (min (point-max) (1+ end1))
5926 (list 'face
5927 (list :inherit
5928 (let ((face-name
5929 (intern (format "org-block-%s" lang))))
5930 (append (and (facep face-name) (list face-name))
5931 '(org-block))))))) ; end of source block
5932 ((not org-fontify-quote-and-verse-blocks))
5933 ((string= block-type "quote")
5934 (add-face-text-property
5935 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5936 ((string= block-type "verse")
5937 (add-face-text-property
5938 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5939 (add-text-properties beg beg1 '(face org-block-begin-line))
5940 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5941 '(face org-block-end-line))
5943 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5944 (org-remove-flyspell-overlays-in
5945 (match-beginning 0)
5946 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5947 (add-text-properties
5948 beg (match-end 3)
5949 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5950 '(font-lock-fontified t invisible t)
5951 '(font-lock-fontified t face org-document-info-keyword)))
5952 (add-text-properties
5953 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5954 (if (string-equal dc1 "+title:")
5955 '(font-lock-fontified t face org-document-title)
5956 '(font-lock-fontified t face org-document-info))))
5957 ((string-prefix-p "+caption" dc1)
5958 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5959 (remove-text-properties (match-beginning 0) (match-end 0)
5960 '(display t invisible t intangible t))
5961 ;; Handle short captions.
5962 (save-excursion
5963 (beginning-of-line)
5964 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5965 (add-text-properties (line-beginning-position) (match-end 1)
5966 '(font-lock-fontified t face org-meta-line))
5967 (add-text-properties (match-end 0) (line-end-position)
5968 '(font-lock-fontified t face org-block))
5970 ((member dc3 '(" " ""))
5971 (org-remove-flyspell-overlays-in beg (match-end 0))
5972 (add-text-properties
5973 beg (match-end 0)
5974 '(font-lock-fontified t face font-lock-comment-face)))
5975 (t ;; just any other in-buffer setting, but not indented
5976 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5977 (remove-text-properties (match-beginning 0) (match-end 0)
5978 '(display t invisible t intangible t))
5979 (add-text-properties beg (match-end 0)
5980 '(font-lock-fontified t face org-meta-line))
5981 t))))))
5983 (defun org-fontify-drawers (limit)
5984 "Fontify drawers."
5985 (when (re-search-forward org-drawer-regexp limit t)
5986 (add-text-properties
5987 (match-beginning 0) (match-end 0)
5988 '(font-lock-fontified t face org-special-keyword))
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (defun org-fontify-macros (limit)
5993 "Fontify macros."
5994 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5995 (add-text-properties
5996 (match-beginning 0) (match-end 0)
5997 '(font-lock-fontified t face org-macro))
5998 (when org-hide-macro-markers
5999 (add-text-properties (match-end 2) (match-beginning 2)
6000 '(invisible t))
6001 (add-text-properties (match-beginning 1) (match-end 1)
6002 '(invisible t)))
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6006 (defun org-activate-footnote-links (limit)
6007 "Add text properties for footnotes."
6008 (let ((fn (org-footnote-next-reference-or-definition limit)))
6009 (when fn
6010 (let* ((beg (nth 1 fn))
6011 (end (nth 2 fn))
6012 (label (car fn))
6013 (referencep (/= (line-beginning-position) beg)))
6014 (when (and referencep (nth 3 fn))
6015 (save-excursion
6016 (goto-char beg)
6017 (search-forward (or label "fn:"))
6018 (org-remove-flyspell-overlays-in beg (match-end 0))))
6019 (add-text-properties beg end
6020 (list 'mouse-face 'highlight
6021 'keymap org-mouse-map
6022 'help-echo
6023 (if referencep "Footnote reference"
6024 "Footnote definition")
6025 'font-lock-fontified t
6026 'font-lock-multiline t
6027 'face 'org-footnote))))))
6029 (defun org-activate-dates (limit)
6030 "Add text properties for dates."
6031 (when (and (re-search-forward org-tsr-regexp-both limit t)
6032 (not (equal (char-before (match-beginning 0)) 91)))
6033 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (add-text-properties (match-beginning 0) (match-end 0)
6035 (list 'mouse-face 'highlight
6036 'keymap org-mouse-map))
6037 (org-rear-nonsticky-at (match-end 0))
6038 (when org-display-custom-times
6039 ;; If it's a date range, activate custom time for second date.
6040 (when (match-end 3)
6041 (org-display-custom-time (match-beginning 3) (match-end 3)))
6042 (org-display-custom-time (match-beginning 1) (match-end 1)))
6045 (defvar-local org-target-link-regexp nil
6046 "Regular expression matching radio targets in plain text.")
6048 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6049 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6050 border border border))
6051 "Regular expression matching a link target.")
6053 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6054 "Regular expression matching a radio target.")
6056 (defconst org-any-target-regexp
6057 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6058 "Regular expression matching any target.")
6060 (defun org-activate-target-links (limit)
6061 "Add text properties for target matches."
6062 (when org-target-link-regexp
6063 (let ((case-fold-search t))
6064 (when (re-search-forward org-target-link-regexp limit t)
6065 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6066 (add-text-properties (match-beginning 1) (match-end 1)
6067 (list 'mouse-face 'highlight
6068 'keymap org-mouse-map
6069 'help-echo "Radio target link"
6070 'org-linked-text t))
6071 (org-rear-nonsticky-at (match-end 1))
6072 t))))
6074 (defun org-update-radio-target-regexp ()
6075 "Find all radio targets in this file and update the regular expression.
6076 Also refresh fontification if needed."
6077 (interactive)
6078 (let ((old-regexp org-target-link-regexp)
6079 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6080 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6081 (targets
6082 (org-with-wide-buffer
6083 (goto-char (point-min))
6084 (let (rtn)
6085 (while (re-search-forward org-radio-target-regexp nil t)
6086 ;; Make sure point is really within the object.
6087 (backward-char)
6088 (let ((obj (org-element-context)))
6089 (when (eq (org-element-type obj) 'radio-target)
6090 (cl-pushnew (org-element-property :value obj) rtn
6091 :test #'equal))))
6092 rtn))))
6093 (setq org-target-link-regexp
6094 (and targets
6095 (concat before-re
6096 (mapconcat
6097 (lambda (x)
6098 (replace-regexp-in-string
6099 " +" "\\s-+" (regexp-quote x) t t))
6100 targets
6101 "\\|")
6102 after-re)))
6103 (unless (equal old-regexp org-target-link-regexp)
6104 ;; Clean-up cache.
6105 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6106 ((not org-target-link-regexp) old-regexp)
6108 (concat before-re
6109 (mapconcat
6110 (lambda (re)
6111 (substring re (length before-re)
6112 (- (length after-re))))
6113 (list old-regexp org-target-link-regexp)
6114 "\\|")
6115 after-re)))))
6116 (org-with-wide-buffer
6117 (goto-char (point-min))
6118 (while (re-search-forward regexp nil t)
6119 (org-element-cache-refresh (match-beginning 1)))))
6120 ;; Re fontify buffer.
6121 (when (memq 'radio org-highlight-links)
6122 (org-restart-font-lock)))))
6124 (defvar org-latex-and-related-regexp nil
6125 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6127 (defun org-compute-latex-and-related-regexp ()
6128 "Compute regular expression for LaTeX, entities and sub/superscript.
6129 Result depends on variable `org-highlight-latex-and-related'."
6130 (setq-local
6131 org-latex-and-related-regexp
6132 (let* ((re-sub
6133 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6134 ((eq org-use-sub-superscripts '{})
6135 (list org-match-substring-with-braces-regexp))
6136 (org-use-sub-superscripts (list org-match-substring-regexp))))
6137 (re-latex
6138 (when (memq 'latex org-highlight-latex-and-related)
6139 (let ((matchers (plist-get org-format-latex-options :matchers)))
6140 (delq nil
6141 (mapcar (lambda (x)
6142 (and (member (car x) matchers) (nth 1 x)))
6143 org-latex-regexps)))))
6144 (re-entities
6145 (when (memq 'entities org-highlight-latex-and-related)
6146 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6147 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6149 (defun org-do-latex-and-related (limit)
6150 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6151 LIMIT bounds the search for syntax to highlight. Stop at first
6152 highlighted object, if any. Return t if some highlighting was
6153 done, nil otherwise."
6154 (when (org-string-nw-p org-latex-and-related-regexp)
6155 (catch 'found
6156 (while (re-search-forward org-latex-and-related-regexp limit t)
6157 (unless
6158 (cl-some
6159 (lambda (f)
6160 (memq f '(org-code org-verbatim underline org-special-keyword)))
6161 (save-excursion
6162 (goto-char (1+ (match-beginning 0)))
6163 (face-at-point nil t)))
6164 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6165 '(?_ ?^))
6167 0)))
6168 (font-lock-prepend-text-property
6169 (+ offset (match-beginning 0)) (match-end 0)
6170 'face 'org-latex-and-related)
6171 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6172 '(font-lock-multiline t)))
6173 (throw 'found t)))
6174 nil)))
6176 (defun org-restart-font-lock ()
6177 "Restart `font-lock-mode', to force refontification."
6178 (when (and (boundp 'font-lock-mode) font-lock-mode)
6179 (font-lock-mode -1)
6180 (font-lock-mode 1)))
6182 (defun org-activate-tags (limit)
6183 (when (re-search-forward
6184 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6185 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6186 (add-text-properties (match-beginning 1) (match-end 1)
6187 (list 'mouse-face 'highlight
6188 'keymap org-mouse-map))
6189 (org-rear-nonsticky-at (match-end 1))
6192 (defun org-outline-level ()
6193 "Compute the outline level of the heading at point.
6195 If this is called at a normal headline, the level is the number
6196 of stars. Use `org-reduced-level' to remove the effect of
6197 `org-odd-levels'. Unlike to `org-current-level', this function
6198 takes into consideration inlinetasks."
6199 (org-with-wide-buffer
6200 (end-of-line)
6201 (if (re-search-backward org-outline-regexp-bol nil t)
6202 (1- (- (match-end 0) (match-beginning 0)))
6203 0)))
6205 (defvar org-font-lock-keywords nil)
6207 (defsubst org-re-property (property &optional literal allow-null value)
6208 "Return a regexp matching a PROPERTY line.
6210 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6211 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6212 non-nil, match properties even without a value.
6214 Match group 3 is set to the value when it exists. If there is no
6215 value and ALLOW-NULL is non-nil, it is set to the empty string.
6217 With optional argument VALUE, match only property lines with
6218 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6219 unless LITERAL is non-nil."
6220 (concat
6221 "^\\(?4:[ \t]*\\)"
6222 (format "\\(?1::\\(?2:%s\\):\\)"
6223 (if literal property (regexp-quote property)))
6224 (cond (value
6225 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6226 (if literal value (regexp-quote value))))
6227 (allow-null
6228 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6230 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6232 (defconst org-property-re
6233 (org-re-property "\\S-+" 'literal t)
6234 "Regular expression matching a property line.
6235 There are four matching groups:
6236 1: :PROPKEY: including the leading and trailing colon,
6237 2: PROPKEY without the leading and trailing colon,
6238 3: PROPVAL without leading or trailing spaces,
6239 4: the indentation of the current line,
6240 5: trailing whitespace.")
6242 (defvar org-font-lock-hook nil
6243 "Functions to be called for special font lock stuff.")
6245 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6247 (defvar org-font-lock-set-keywords-hook nil
6248 "Functions that can manipulate `org-font-lock-extra-keywords'.
6249 This is called after `org-font-lock-extra-keywords' is defined, but before
6250 it is installed to be used by font lock. This can be useful if something
6251 needs to be inserted at a specific position in the font-lock sequence.")
6253 (defun org-font-lock-hook (limit)
6254 "Run `org-font-lock-hook' within LIMIT."
6255 (run-hook-with-args 'org-font-lock-hook limit))
6257 (defun org-set-font-lock-defaults ()
6258 "Set font lock defaults for the current buffer."
6259 (let* ((em org-fontify-emphasized-text)
6260 (lk org-highlight-links)
6261 (org-font-lock-extra-keywords
6262 (list
6263 ;; Call the hook
6264 '(org-font-lock-hook)
6265 ;; Headlines
6266 `(,(if org-fontify-whole-heading-line
6267 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6268 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6269 (1 (org-get-level-face 1))
6270 (2 (org-get-level-face 2))
6271 (3 (org-get-level-face 3)))
6272 ;; Table lines
6273 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6274 (1 'org-table t))
6275 ;; Table internals
6276 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6277 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6278 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6279 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6280 ;; Drawers
6281 '(org-fontify-drawers)
6282 ;; Properties
6283 (list org-property-re
6284 '(1 'org-special-keyword t)
6285 '(3 'org-property-value t))
6286 ;; Link related fontification.
6287 '(org-activate-links)
6288 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6289 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6290 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6291 (when (memq 'footnote lk) '(org-activate-footnote-links))
6292 ;; Targets.
6293 (list org-any-target-regexp '(0 'org-target t))
6294 ;; Diary sexps.
6295 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6296 ;; Macro
6297 '(org-fontify-macros)
6298 ;; TODO keyword
6299 (list (format org-heading-keyword-regexp-format
6300 org-todo-regexp)
6301 '(2 (org-get-todo-face 2) t))
6302 ;; DONE
6303 (if org-fontify-done-headline
6304 (list (format org-heading-keyword-regexp-format
6305 (concat
6306 "\\(?:"
6307 (mapconcat 'regexp-quote org-done-keywords "\\|")
6308 "\\)"))
6309 '(2 'org-headline-done t))
6310 nil)
6311 ;; Priorities
6312 '(org-font-lock-add-priority-faces)
6313 ;; Tags
6314 '(org-font-lock-add-tag-faces)
6315 ;; Tags groups
6316 (when (and org-group-tags org-tag-groups-alist)
6317 (list (concat org-outline-regexp-bol ".+\\(:"
6318 (regexp-opt (mapcar 'car org-tag-groups-alist))
6319 ":\\).*$")
6320 '(1 'org-tag-group prepend)))
6321 ;; Special keywords
6322 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6323 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6324 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6325 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6326 ;; Emphasis
6327 (when em '(org-do-emphasis-faces))
6328 ;; Checkboxes
6329 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6330 1 'org-checkbox prepend)
6331 (when (cdr (assq 'checkbox org-list-automatic-rules))
6332 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6333 (0 (org-get-checkbox-statistics-face) t)))
6334 ;; Description list items
6335 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6336 1 'org-list-dt prepend)
6337 ;; ARCHIVEd headings
6338 (list (concat
6339 org-outline-regexp-bol
6340 "\\(.*:" org-archive-tag ":.*\\)")
6341 '(1 'org-archived prepend))
6342 ;; Specials
6343 '(org-do-latex-and-related)
6344 '(org-fontify-entities)
6345 '(org-raise-scripts)
6346 ;; Code
6347 '(org-activate-code (1 'org-code t))
6348 ;; COMMENT
6349 (list (format
6350 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6351 org-todo-regexp
6352 org-comment-string)
6353 '(9 'org-special-keyword t))
6354 ;; Blocks and meta lines
6355 '(org-fontify-meta-lines-and-blocks))))
6356 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6357 (run-hooks 'org-font-lock-set-keywords-hook)
6358 ;; Now set the full font-lock-keywords
6359 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6360 (setq-local font-lock-defaults
6361 '(org-font-lock-keywords t nil nil backward-paragraph))
6362 (kill-local-variable 'font-lock-keywords)
6363 nil))
6365 (defun org-toggle-pretty-entities ()
6366 "Toggle the composition display of entities as UTF8 characters."
6367 (interactive)
6368 (setq-local org-pretty-entities (not org-pretty-entities))
6369 (org-restart-font-lock)
6370 (if org-pretty-entities
6371 (message "Entities are now displayed as UTF8 characters")
6372 (save-restriction
6373 (widen)
6374 (decompose-region (point-min) (point-max))
6375 (message "Entities are now displayed as plain text"))))
6377 (defvar-local org-custom-properties-overlays nil
6378 "List of overlays used for custom properties.")
6380 (defun org-toggle-custom-properties-visibility ()
6381 "Display or hide properties in `org-custom-properties'."
6382 (interactive)
6383 (if org-custom-properties-overlays
6384 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6385 (setq org-custom-properties-overlays nil))
6386 (when org-custom-properties
6387 (org-with-wide-buffer
6388 (goto-char (point-min))
6389 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6390 (while (re-search-forward regexp nil t)
6391 (let ((end (cdr (save-match-data (org-get-property-block)))))
6392 (when (and end (< (point) end))
6393 ;; Hide first custom property in current drawer.
6394 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6395 (overlay-put o 'invisible t)
6396 (overlay-put o 'org-custom-property t)
6397 (push o org-custom-properties-overlays))
6398 ;; Hide additional custom properties in the same drawer.
6399 (while (re-search-forward regexp end t)
6400 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6401 (overlay-put o 'invisible t)
6402 (overlay-put o 'org-custom-property t)
6403 (push o org-custom-properties-overlays)))))
6404 ;; Each entry is limited to a single property drawer.
6405 (outline-next-heading)))))))
6407 (defun org-fontify-entities (limit)
6408 "Find an entity to fontify."
6409 (let (ee)
6410 (when org-pretty-entities
6411 (catch 'match
6412 ;; "\_ "-family is left out on purpose. Only the first one,
6413 ;; i.e., "\_ ", could be fontified anyway, and it would be
6414 ;; confusing when adding a second white space character.
6415 (while (re-search-forward
6416 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6417 limit t)
6418 (when (and (not (org-at-comment-p))
6419 (setq ee (org-entity-get (match-string 1)))
6420 (= (length (nth 6 ee)) 1))
6421 (let* ((end (if (equal (match-string 2) "{}")
6422 (match-end 2)
6423 (match-end 1))))
6424 (add-text-properties
6425 (match-beginning 0) end
6426 (list 'font-lock-fontified t))
6427 (compose-region (match-beginning 0) end
6428 (nth 6 ee) nil)
6429 (backward-char 1)
6430 (throw 'match t))))
6431 nil))))
6433 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6434 "Fontify string S like in Org mode."
6435 (with-temp-buffer
6436 (insert s)
6437 (let ((org-odd-levels-only odd-levels))
6438 (org-mode)
6439 (org-font-lock-ensure)
6440 (buffer-string))))
6442 (defvar org-m nil)
6443 (defvar org-l nil)
6444 (defvar org-f nil)
6445 (defun org-get-level-face (n)
6446 "Get the right face for match N in font-lock matching of headlines."
6447 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6448 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6449 (if org-cycle-level-faces
6450 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6451 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6452 (cond
6453 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6454 ((eq n 2) org-f)
6455 (t (unless org-level-color-stars-only org-f))))
6457 (defun org-face-from-face-or-color (context inherit face-or-color)
6458 "Create a face list that inherits INHERIT, but sets the foreground color.
6459 When FACE-OR-COLOR is not a string, just return it."
6460 (if (stringp face-or-color)
6461 (list :inherit inherit
6462 (cdr (assoc context org-faces-easy-properties))
6463 face-or-color)
6464 face-or-color))
6466 (defun org-get-todo-face (kwd)
6467 "Get the right face for a TODO keyword KWD.
6468 If KWD is a number, get the corresponding match group."
6469 (when (numberp kwd) (setq kwd (match-string kwd)))
6470 (or (org-face-from-face-or-color
6471 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6472 (and (member kwd org-done-keywords) 'org-done)
6473 'org-todo))
6475 (defun org-get-priority-face (priority)
6476 "Get the right face for PRIORITY.
6477 PRIORITY is a character."
6478 (or (org-face-from-face-or-color
6479 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6480 'org-priority))
6482 (defun org-get-tag-face (tag)
6483 "Get the right face for TAG.
6484 If TAG is a number, get the corresponding match group."
6485 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6486 (or (org-face-from-face-or-color
6487 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6488 'org-tag)))
6490 (defun org-font-lock-add-priority-faces (limit)
6491 "Add the special priority faces."
6492 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6493 (add-text-properties
6494 (match-beginning 1) (match-end 1)
6495 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6496 'font-lock-fontified t))))
6498 (defun org-font-lock-add-tag-faces (limit)
6499 "Add the special tag faces."
6500 (when (and org-tag-faces org-tags-special-faces-re)
6501 (while (re-search-forward org-tags-special-faces-re limit t)
6502 (add-text-properties (match-beginning 1) (match-end 1)
6503 (list 'face (org-get-tag-face 1)
6504 'font-lock-fontified t))
6505 (backward-char 1))))
6507 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6508 "Remove fontification and activation overlays from links."
6509 (font-lock-default-unfontify-region beg end)
6510 (let* ((buffer-undo-list t)
6511 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6512 (inhibit-modification-hooks t)
6513 deactivate-mark buffer-file-name buffer-file-truename)
6514 (decompose-region beg end)
6515 (remove-text-properties beg end
6516 '(mouse-face t keymap t org-linked-text t
6517 invisible t intangible t
6518 org-emphasis t))
6519 (org-remove-font-lock-display-properties beg end)))
6521 (defconst org-script-display '(((raise -0.3) (height 0.7))
6522 ((raise 0.3) (height 0.7))
6523 ((raise -0.5))
6524 ((raise 0.5)))
6525 "Display properties for showing superscripts and subscripts.")
6527 (defun org-remove-font-lock-display-properties (beg end)
6528 "Remove specific display properties that have been added by font lock.
6529 The will remove the raise properties that are used to show superscripts
6530 and subscripts."
6531 (let (next prop)
6532 (while (< beg end)
6533 (setq next (next-single-property-change beg 'display nil end)
6534 prop (get-text-property beg 'display))
6535 (when (member prop org-script-display)
6536 (put-text-property beg next 'display nil))
6537 (setq beg next))))
6539 (defun org-raise-scripts (limit)
6540 "Add raise properties to sub/superscripts."
6541 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6542 (re-search-forward
6543 (if (eq org-use-sub-superscripts t)
6544 org-match-substring-regexp
6545 org-match-substring-with-braces-regexp)
6546 limit t))
6547 (let* ((pos (point)) table-p comment-p
6548 (mpos (match-beginning 3))
6549 (emph-p (get-text-property mpos 'org-emphasis))
6550 (link-p (get-text-property mpos 'mouse-face))
6551 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6552 (goto-char (point-at-bol))
6553 (setq table-p (looking-at-p org-table-dataline-regexp)
6554 comment-p (looking-at-p "^[ \t]*#[ +]"))
6555 (goto-char pos)
6556 ;; Handle a_b^c
6557 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6558 (unless (or comment-p emph-p link-p keyw-p)
6559 (put-text-property (match-beginning 3) (match-end 0)
6560 'display
6561 (if (equal (char-after (match-beginning 2)) ?^)
6562 (nth (if table-p 3 1) org-script-display)
6563 (nth (if table-p 2 0) org-script-display)))
6564 (add-text-properties (match-beginning 2) (match-end 2)
6565 (list 'invisible t))
6566 (when (and (eq (char-after (match-beginning 3)) ?{)
6567 (eq (char-before (match-end 3)) ?}))
6568 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6569 (list 'invisible t))
6570 (add-text-properties (1- (match-end 3)) (match-end 3)
6571 (list 'invisible t))))
6572 t)))
6574 ;;;; Visibility cycling, including org-goto and indirect buffer
6576 ;;; Cycling
6578 (defvar-local org-cycle-global-status nil)
6579 (put 'org-cycle-global-status 'org-state t)
6580 (defvar-local org-cycle-subtree-status nil)
6581 (put 'org-cycle-subtree-status 'org-state t)
6583 (defvar org-inlinetask-min-level)
6585 (defun org-unlogged-message (&rest args)
6586 "Display a message, but avoid logging it in the *Messages* buffer."
6587 (let ((message-log-max nil))
6588 (apply 'message args)))
6590 ;;;###autoload
6591 (defun org-cycle (&optional arg)
6592 "TAB-action and visibility cycling for Org mode.
6594 This is the command invoked in Org mode by the `TAB' key. Its main
6595 purpose is outline visibility cycling, but it also invokes other actions
6596 in special contexts.
6598 When this function is called with a `\\[universal-argument]' prefix, rotate \
6599 the entire
6600 buffer through 3 states (global cycling)
6601 1. OVERVIEW: Show only top-level headlines.
6602 2. CONTENTS: Show all headlines of all levels, but no body text.
6603 3. SHOW ALL: Show everything.
6605 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6606 switch to the startup visibility,
6607 determined by the variable `org-startup-folded', and by any VISIBILITY
6608 properties in the buffer.
6610 With a `\\[universal-argument] \\[universal-argument] \
6611 \\[universal-argument]' prefix argument, show the entire buffer, including
6612 any drawers.
6614 When inside a table, re-align the table and move to the next field.
6616 When point is at the beginning of a headline, rotate the subtree started
6617 by this line through 3 different states (local cycling)
6618 1. FOLDED: Only the main headline is shown.
6619 2. CHILDREN: The main headline and the direct children are shown.
6620 From this state, you can move to one of the children
6621 and zoom in further.
6622 3. SUBTREE: Show the entire subtree, including body text.
6623 If there is no subtree, switch directly from CHILDREN to FOLDED.
6625 When point is at the beginning of an empty headline and the variable
6626 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6627 of the headline by demoting and promoting it to likely levels. This
6628 speeds up creation document structure by pressing `TAB' once or several
6629 times right after creating a new headline.
6631 When there is a numeric prefix, go up to a heading with level ARG, do
6632 a `show-subtree' and return to the previous cursor position. If ARG
6633 is negative, go up that many levels.
6635 When point is not at the beginning of a headline, execute the global
6636 binding for `TAB', which is re-indenting the line. See the option
6637 `org-cycle-emulate-tab' for details.
6639 As a special case, if point is at the beginning of the buffer and there is
6640 no headline in line 1, this function will act as if called with prefix arg
6641 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6642 prefix arg, but only
6643 if the variable `org-cycle-global-at-bob' is t."
6644 (interactive "P")
6645 (org-load-modules-maybe)
6646 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6647 (and org-cycle-level-after-item/entry-creation
6648 (or (org-cycle-level)
6649 (org-cycle-item-indentation))))
6650 (let* ((limit-level
6651 (or org-cycle-max-level
6652 (and (boundp 'org-inlinetask-min-level)
6653 org-inlinetask-min-level
6654 (1- org-inlinetask-min-level))))
6655 (nstars (and limit-level
6656 (if org-odd-levels-only
6657 (and limit-level (1- (* limit-level 2)))
6658 limit-level)))
6659 (org-outline-regexp
6660 (if (not (derived-mode-p 'org-mode))
6661 outline-regexp
6662 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6663 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6664 (not (looking-at org-outline-regexp))))
6665 (org-cycle-hook
6666 (if bob-special
6667 (delq 'org-optimize-window-after-visibility-change
6668 (copy-sequence org-cycle-hook))
6669 org-cycle-hook))
6670 (pos (point)))
6672 (cond
6674 ((equal arg '(16))
6675 (setq last-command 'dummy)
6676 (org-set-startup-visibility)
6677 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6679 ((equal arg '(64))
6680 (outline-show-all)
6681 (org-unlogged-message "Entire buffer visible, including drawers"))
6683 ((equal arg '(4)) (org-cycle-internal-global))
6685 ;; Try hiding block at point.
6686 ((org-hide-block-toggle-maybe))
6688 ;; Try cdlatex TAB completion
6689 ((org-try-cdlatex-tab))
6691 ;; Table: enter it or move to the next field.
6692 ((org-at-table-p 'any)
6693 (if (org-at-table.el-p)
6694 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6695 Use `\\[org-edit-special]' to edit table.el tables"))
6696 (if arg (org-table-edit-field t)
6697 (org-table-justify-field-maybe)
6698 (call-interactively 'org-table-next-field))))
6700 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6702 ;; Global cycling: delegate to `org-cycle-internal-global'.
6703 (bob-special (org-cycle-internal-global))
6705 ;; Drawers: delegate to `org-flag-drawer'.
6706 ((save-excursion
6707 (beginning-of-line 1)
6708 (looking-at org-drawer-regexp))
6709 (org-flag-drawer ; toggle block visibility
6710 (not (get-char-property (match-end 0) 'invisible))))
6712 ;; Show-subtree, ARG levels up from here.
6713 ((integerp arg)
6714 (save-excursion
6715 (org-back-to-heading)
6716 (outline-up-heading (if (< arg 0) (- arg)
6717 (- (funcall outline-level) arg)))
6718 (org-show-subtree)))
6720 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6721 ((and (featurep 'org-inlinetask)
6722 (org-inlinetask-at-task-p)
6723 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6724 (org-inlinetask-toggle-visibility))
6726 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6727 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6728 (save-excursion (move-beginning-of-line 1)
6729 (looking-at org-outline-regexp)))
6730 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6731 (org-cycle-internal-local))
6733 ;; From there: TAB emulation and template completion.
6734 (buffer-read-only (org-back-to-heading))
6736 ((run-hook-with-args-until-success
6737 'org-tab-after-check-for-cycling-hook))
6739 ((run-hook-with-args-until-success
6740 'org-tab-before-tab-emulation-hook))
6742 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6743 (or (not (bolp))
6744 (not (looking-at org-outline-regexp))))
6745 (call-interactively (global-key-binding "\t")))
6747 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6748 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6749 (or (and (eq org-cycle-emulate-tab 'white)
6750 (= (match-end 0) (point-at-eol)))
6751 (and (eq org-cycle-emulate-tab 'whitestart)
6752 (>= (match-end 0) pos))))
6754 (eq org-cycle-emulate-tab t))
6755 (call-interactively (global-key-binding "\t")))
6757 (t (save-excursion
6758 (org-back-to-heading)
6759 (org-cycle)))))))
6761 (defun org-cycle-internal-global ()
6762 "Do the global cycling action."
6763 ;; Hack to avoid display of messages for .org attachments in Gnus
6764 (let ((ga (string-match "\\*fontification" (buffer-name))))
6765 (cond
6766 ((and (eq last-command this-command)
6767 (eq org-cycle-global-status 'overview))
6768 ;; We just created the overview - now do table of contents
6769 ;; This can be slow in very large buffers, so indicate action
6770 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6771 (unless ga (org-unlogged-message "CONTENTS..."))
6772 (org-content)
6773 (unless ga (org-unlogged-message "CONTENTS...done"))
6774 (setq org-cycle-global-status 'contents)
6775 (run-hook-with-args 'org-cycle-hook 'contents))
6777 ((and (eq last-command this-command)
6778 (eq org-cycle-global-status 'contents))
6779 ;; We just showed the table of contents - now show everything
6780 (run-hook-with-args 'org-pre-cycle-hook 'all)
6781 (outline-show-all)
6782 (unless ga (org-unlogged-message "SHOW ALL"))
6783 (setq org-cycle-global-status 'all)
6784 (run-hook-with-args 'org-cycle-hook 'all))
6787 ;; Default action: go to overview
6788 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6789 (org-overview)
6790 (unless ga (org-unlogged-message "OVERVIEW"))
6791 (setq org-cycle-global-status 'overview)
6792 (run-hook-with-args 'org-cycle-hook 'overview)))))
6794 (defvar org-called-with-limited-levels nil
6795 "Non-nil when `org-with-limited-levels' is currently active.")
6797 (defun org-cycle-internal-local ()
6798 "Do the local cycling action."
6799 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6800 ;; First, determine end of headline (EOH), end of subtree or item
6801 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6802 (save-excursion
6803 (if (org-at-item-p)
6804 (progn
6805 (beginning-of-line)
6806 (setq struct (org-list-struct))
6807 (setq eoh (point-at-eol))
6808 (setq eos (org-list-get-item-end-before-blank (point) struct))
6809 (setq has-children (org-list-has-child-p (point) struct)))
6810 (org-back-to-heading)
6811 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6812 (setq eos (save-excursion (org-end-of-subtree t t)
6813 (when (bolp) (backward-char)) (point)))
6814 (setq has-children
6815 (or (save-excursion
6816 (let ((level (funcall outline-level)))
6817 (outline-next-heading)
6818 (and (org-at-heading-p t)
6819 (> (funcall outline-level) level))))
6820 (save-excursion
6821 (org-list-search-forward (org-item-beginning-re) eos t)))))
6822 ;; Determine end invisible part of buffer (EOL)
6823 (beginning-of-line 2)
6824 (while (and (not (eobp)) ;This is like `next-line'.
6825 (get-char-property (1- (point)) 'invisible))
6826 (goto-char (next-single-char-property-change (point) 'invisible))
6827 (and (eolp) (beginning-of-line 2)))
6828 (setq eol (point)))
6829 ;; Find out what to do next and set `this-command'
6830 (cond
6831 ((= eos eoh)
6832 ;; Nothing is hidden behind this heading
6833 (unless (org-before-first-heading-p)
6834 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6835 (org-unlogged-message "EMPTY ENTRY")
6836 (setq org-cycle-subtree-status nil)
6837 (save-excursion
6838 (goto-char eos)
6839 (outline-next-heading)
6840 (when (org-invisible-p) (org-flag-heading nil))))
6841 ((and (or (>= eol eos)
6842 (not (string-match "\\S-" (buffer-substring eol eos))))
6843 (or has-children
6844 (not (setq children-skipped
6845 org-cycle-skip-children-state-if-no-children))))
6846 ;; Entire subtree is hidden in one line: children view
6847 (unless (org-before-first-heading-p)
6848 (run-hook-with-args 'org-pre-cycle-hook 'children))
6849 (if (org-at-item-p)
6850 (org-list-set-item-visibility (point-at-bol) struct 'children)
6851 (org-show-entry)
6852 (org-with-limited-levels (org-show-children))
6853 ;; FIXME: This slows down the func way too much.
6854 ;; How keep drawers hidden in subtree anyway?
6855 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6856 ;; (org-cycle-hide-drawers 'subtree))
6858 ;; Fold every list in subtree to top-level items.
6859 (when (eq org-cycle-include-plain-lists 'integrate)
6860 (save-excursion
6861 (org-back-to-heading)
6862 (while (org-list-search-forward (org-item-beginning-re) eos t)
6863 (beginning-of-line 1)
6864 (let* ((struct (org-list-struct))
6865 (prevs (org-list-prevs-alist struct))
6866 (end (org-list-get-bottom-point struct)))
6867 (dolist (e (org-list-get-all-items (point) struct prevs))
6868 (org-list-set-item-visibility e struct 'folded))
6869 (goto-char (if (< end eos) end eos)))))))
6870 (org-unlogged-message "CHILDREN")
6871 (save-excursion
6872 (goto-char eos)
6873 (outline-next-heading)
6874 (when (org-invisible-p) (org-flag-heading nil)))
6875 (setq org-cycle-subtree-status 'children)
6876 (unless (org-before-first-heading-p)
6877 (run-hook-with-args 'org-cycle-hook 'children)))
6878 ((or children-skipped
6879 (and (eq last-command this-command)
6880 (eq org-cycle-subtree-status 'children)))
6881 ;; We just showed the children, or no children are there,
6882 ;; now show everything.
6883 (unless (org-before-first-heading-p)
6884 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6885 (outline-flag-region eoh eos nil)
6886 (org-unlogged-message
6887 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6888 (setq org-cycle-subtree-status 'subtree)
6889 (unless (org-before-first-heading-p)
6890 (run-hook-with-args 'org-cycle-hook 'subtree)))
6892 ;; Default action: hide the subtree.
6893 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6894 (outline-flag-region eoh eos t)
6895 (org-unlogged-message "FOLDED")
6896 (setq org-cycle-subtree-status 'folded)
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-cycle-hook 'folded))))))
6900 ;;;###autoload
6901 (defun org-global-cycle (&optional arg)
6902 "Cycle the global visibility. For details see `org-cycle'.
6903 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6904 With a numeric prefix, show all headlines up to that level."
6905 (interactive "P")
6906 (let ((org-cycle-include-plain-lists
6907 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6908 (cond
6909 ((integerp arg)
6910 (outline-show-all)
6911 (outline-hide-sublevels arg)
6912 (setq org-cycle-global-status 'contents))
6913 ((equal arg '(4))
6914 (org-set-startup-visibility)
6915 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6917 (org-cycle '(4))))))
6919 (defun org-set-startup-visibility ()
6920 "Set the visibility required by startup options and properties."
6921 (cond
6922 ((eq org-startup-folded t)
6923 (org-overview))
6924 ((eq org-startup-folded 'content)
6925 (org-content))
6926 ((or (eq org-startup-folded 'showeverything)
6927 (eq org-startup-folded nil))
6928 (outline-show-all)))
6929 (unless (eq org-startup-folded 'showeverything)
6930 (when org-hide-block-startup (org-hide-block-all))
6931 (org-set-visibility-according-to-property 'no-cleanup)
6932 (org-cycle-hide-archived-subtrees 'all)
6933 (org-cycle-hide-drawers 'all)
6934 (org-cycle-show-empty-lines t)))
6936 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6937 "Switch subtree visibilities according to :VISIBILITY: property."
6938 (interactive)
6939 (org-with-wide-buffer
6940 (goto-char (point-min))
6941 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6942 (if (not (org-at-property-p)) (outline-next-heading)
6943 (let ((state (match-string 3)))
6944 (save-excursion
6945 (org-back-to-heading t)
6946 (outline-hide-subtree)
6947 (org-reveal)
6948 (cond
6949 ((equal state "folded")
6950 (outline-hide-subtree))
6951 ((equal state "children")
6952 (org-show-hidden-entry)
6953 (org-show-children))
6954 ((equal state "content")
6955 (save-excursion
6956 (save-restriction
6957 (org-narrow-to-subtree)
6958 (org-content))))
6959 ((member state '("all" "showall"))
6960 (outline-show-subtree)))))))
6961 (unless no-cleanup
6962 (org-cycle-hide-archived-subtrees 'all)
6963 (org-cycle-hide-drawers 'all)
6964 (org-cycle-show-empty-lines 'all))))
6966 ;; This function uses outline-regexp instead of the more fundamental
6967 ;; org-outline-regexp so that org-cycle-global works outside of Org
6968 ;; buffers, where outline-regexp is needed.
6969 (defun org-overview ()
6970 "Switch to overview mode, showing only top-level headlines.
6971 This shows all headlines with a level equal or greater than the level
6972 of the first headline in the buffer. This is important, because if the
6973 first headline is not level one, then (hide-sublevels 1) gives confusing
6974 results."
6975 (interactive)
6976 (save-excursion
6977 (let ((level
6978 (save-excursion
6979 (goto-char (point-min))
6980 (when (re-search-forward (concat "^" outline-regexp) nil t)
6981 (goto-char (match-beginning 0))
6982 (funcall outline-level)))))
6983 (and level (outline-hide-sublevels level)))))
6985 (defun org-content (&optional arg)
6986 "Show all headlines in the buffer, like a table of contents.
6987 With numerical argument N, show content up to level N."
6988 (interactive "P")
6989 (org-overview)
6990 (save-excursion
6991 ;; Visit all headings and show their offspring
6992 (and (integerp arg) (org-overview))
6993 (goto-char (point-max))
6994 (catch 'exit
6995 (while (and (progn (condition-case nil
6996 (outline-previous-visible-heading 1)
6997 (error (goto-char (point-min))))
6999 (looking-at org-outline-regexp))
7000 (if (integerp arg)
7001 (org-show-children (1- arg))
7002 (outline-show-branches))
7003 (when (bobp) (throw 'exit nil))))))
7005 (defun org-optimize-window-after-visibility-change (state)
7006 "Adjust the window after a change in outline visibility.
7007 This function is the default value of the hook `org-cycle-hook'."
7008 (when (get-buffer-window (current-buffer))
7009 (cond
7010 ((eq state 'content) nil)
7011 ((eq state 'all) nil)
7012 ((eq state 'folded) nil)
7013 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7014 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7016 (defun org-remove-empty-overlays-at (pos)
7017 "Remove outline overlays that do not contain non-white stuff."
7018 (dolist (o (overlays-at pos))
7019 (and (eq 'outline (overlay-get o 'invisible))
7020 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7021 (overlay-end o))))
7022 (delete-overlay o))))
7024 (defun org-clean-visibility-after-subtree-move ()
7025 "Fix visibility issues after moving a subtree."
7026 ;; First, find a reasonable region to look at:
7027 ;; Start two siblings above, end three below
7028 (let* ((beg (save-excursion
7029 (and (org-get-last-sibling)
7030 (org-get-last-sibling))
7031 (point)))
7032 (end (save-excursion
7033 (and (org-get-next-sibling)
7034 (org-get-next-sibling)
7035 (org-get-next-sibling))
7036 (if (org-at-heading-p)
7037 (point-at-eol)
7038 (point))))
7039 (level (looking-at "\\*+"))
7040 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7041 (save-excursion
7042 (save-restriction
7043 (narrow-to-region beg end)
7044 (when re
7045 ;; Properly fold already folded siblings
7046 (goto-char (point-min))
7047 (while (re-search-forward re nil t)
7048 (when (and (not (org-invisible-p))
7049 (save-excursion
7050 (goto-char (point-at-eol)) (org-invisible-p)))
7051 (outline-hide-entry))))
7052 (org-cycle-show-empty-lines 'overview)
7053 (org-cycle-hide-drawers 'overview)))))
7055 (defun org-cycle-show-empty-lines (state)
7056 "Show empty lines above all visible headlines.
7057 The region to be covered depends on STATE when called through
7058 `org-cycle-hook'. Lisp program can use t for STATE to get the
7059 entire buffer covered. Note that an empty line is only shown if there
7060 are at least `org-cycle-separator-lines' empty lines before the headline."
7061 (when (/= org-cycle-separator-lines 0)
7062 (save-excursion
7063 (let* ((n (abs org-cycle-separator-lines))
7064 (re (cond
7065 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7066 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7067 (t (let ((ns (number-to-string (- n 2))))
7068 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7069 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7070 beg end)
7071 (cond
7072 ((memq state '(overview contents t))
7073 (setq beg (point-min) end (point-max)))
7074 ((memq state '(children folded))
7075 (setq beg (point)
7076 end (progn (org-end-of-subtree t t)
7077 (line-beginning-position 2)))))
7078 (when beg
7079 (goto-char beg)
7080 (while (re-search-forward re end t)
7081 (unless (get-char-property (match-end 1) 'invisible)
7082 (let ((e (match-end 1))
7083 (b (if (>= org-cycle-separator-lines 0)
7084 (match-beginning 1)
7085 (save-excursion
7086 (goto-char (match-beginning 0))
7087 (skip-chars-backward " \t\n")
7088 (line-end-position)))))
7089 (outline-flag-region b e nil))))))))
7090 ;; Never hide empty lines at the end of the file.
7091 (save-excursion
7092 (goto-char (point-max))
7093 (outline-previous-heading)
7094 (outline-end-of-heading)
7095 (when (and (looking-at "[ \t\n]+")
7096 (= (match-end 0) (point-max)))
7097 (outline-flag-region (point) (match-end 0) nil))))
7099 (defun org-show-empty-lines-in-parent ()
7100 "Move to the parent and re-show empty lines before visible headlines."
7101 (save-excursion
7102 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7103 (org-cycle-show-empty-lines context))))
7105 (defun org-files-list ()
7106 "Return `org-agenda-files' list, plus all open Org files.
7107 This is useful for operations that need to scan all of a user's
7108 open and agenda-wise Org files."
7109 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7110 (dolist (buf (buffer-list))
7111 (with-current-buffer buf
7112 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7113 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7114 files))
7116 (defsubst org-entry-beginning-position ()
7117 "Return the beginning position of the current entry."
7118 (save-excursion (org-back-to-heading t) (point)))
7120 (defsubst org-entry-end-position ()
7121 "Return the end position of the current entry."
7122 (save-excursion (outline-next-heading) (point)))
7124 (defun org-cycle-hide-drawers (state &optional exceptions)
7125 "Re-hide all drawers after a visibility state change.
7126 STATE should be one of the symbols listed in the docstring of
7127 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7128 a list of strings specifying which drawers should not be hidden."
7129 (when (and (derived-mode-p 'org-mode)
7130 (not (memq state '(overview folded contents))))
7131 (save-excursion
7132 (let* ((globalp (eq state 'all))
7133 (beg (if globalp (point-min) (point)))
7134 (end (if globalp (point-max)
7135 (if (eq state 'children)
7136 (save-excursion (outline-next-heading) (point))
7137 (org-end-of-subtree t)))))
7138 (goto-char beg)
7139 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7140 (unless (member-ignore-case (match-string 1) exceptions)
7141 (let ((drawer (org-element-at-point)))
7142 (when (memq (org-element-type drawer) '(drawer property-drawer))
7143 (org-flag-drawer t drawer)
7144 ;; Make sure to skip drawer entirely or we might flag
7145 ;; it another time when matching its ending line with
7146 ;; `org-drawer-regexp'.
7147 (goto-char (org-element-property :end drawer))))))))))
7149 (defun org-flag-drawer (flag &optional element)
7150 "When FLAG is non-nil, hide the drawer we are at.
7151 Otherwise make it visible. When optional argument ELEMENT is
7152 a parsed drawer, as returned by `org-element-at-point', hide or
7153 show that drawer instead."
7154 (let ((drawer (or element
7155 (and (save-excursion
7156 (beginning-of-line)
7157 (looking-at-p org-drawer-regexp))
7158 (org-element-at-point)))))
7159 (when (memq (org-element-type drawer) '(drawer property-drawer))
7160 (let ((post (org-element-property :post-affiliated drawer)))
7161 (save-excursion
7162 (outline-flag-region
7163 (progn (goto-char post) (line-end-position))
7164 (progn (goto-char (org-element-property :end drawer))
7165 (skip-chars-backward " \r\t\n")
7166 (line-end-position))
7167 flag))
7168 ;; When the drawer is hidden away, make sure point lies in
7169 ;; a visible part of the buffer.
7170 (when (and flag (> (line-beginning-position) post))
7171 (goto-char post))))))
7173 (defun org-subtree-end-visible-p ()
7174 "Is the end of the current subtree visible?"
7175 (pos-visible-in-window-p
7176 (save-excursion (org-end-of-subtree t) (point))))
7178 (defun org-first-headline-recenter ()
7179 "Move cursor to the first headline and recenter the headline."
7180 (let ((window (get-buffer-window)))
7181 (when window
7182 (goto-char (point-min))
7183 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7184 (set-window-start window (line-beginning-position))))))
7186 ;;; Saving and restoring visibility
7188 (defun org-outline-overlay-data (&optional use-markers)
7189 "Return a list of the locations of all outline overlays.
7190 These are overlays with the `invisible' property value `outline'.
7191 The return value is a list of cons cells, with start and stop
7192 positions for each overlay.
7193 If USE-MARKERS is set, return the positions as markers."
7194 (let (beg end)
7195 (org-with-wide-buffer
7196 (delq nil
7197 (mapcar (lambda (o)
7198 (when (eq (overlay-get o 'invisible) 'outline)
7199 (setq beg (overlay-start o)
7200 end (overlay-end o))
7201 (and beg end (> end beg)
7202 (if use-markers
7203 (cons (copy-marker beg)
7204 (copy-marker end t))
7205 (cons beg end)))))
7206 (overlays-in (point-min) (point-max)))))))
7208 (defun org-set-outline-overlay-data (data)
7209 "Create visibility overlays for all positions in DATA.
7210 DATA should have been made by `org-outline-overlay-data'."
7211 (org-with-wide-buffer
7212 (outline-show-all)
7213 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7215 ;;; Folding of blocks
7217 (defvar-local org-hide-block-overlays nil
7218 "Overlays hiding blocks.")
7220 (defun org-block-map (function &optional start end)
7221 "Call FUNCTION at the head of all source blocks in the current buffer.
7222 Optional arguments START and END can be used to limit the range."
7223 (let ((start (or start (point-min)))
7224 (end (or end (point-max))))
7225 (save-excursion
7226 (goto-char start)
7227 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7228 (save-excursion
7229 (save-match-data
7230 (goto-char (match-beginning 0))
7231 (funcall function)))))))
7233 (defun org-hide-block-toggle-all ()
7234 "Toggle the visibility of all blocks in the current buffer."
7235 (org-block-map 'org-hide-block-toggle))
7237 (defun org-hide-block-all ()
7238 "Fold all blocks in the current buffer."
7239 (interactive)
7240 (org-show-block-all)
7241 (org-block-map 'org-hide-block-toggle-maybe))
7243 (defun org-show-block-all ()
7244 "Unfold all blocks in the current buffer."
7245 (interactive)
7246 (mapc #'delete-overlay org-hide-block-overlays)
7247 (setq org-hide-block-overlays nil))
7249 (defun org-hide-block-toggle-maybe ()
7250 "Toggle visibility of block at point.
7251 Unlike to `org-hide-block-toggle', this function does not throw
7252 an error. Return a non-nil value when toggling is successful."
7253 (interactive)
7254 (ignore-errors (org-hide-block-toggle)))
7256 (defun org-hide-block-toggle (&optional force)
7257 "Toggle the visibility of the current block.
7258 When optional argument FORCE is `off', make block visible. If it
7259 is non-nil, hide it unconditionally. Throw an error when not at
7260 a block. Return a non-nil value when toggling is successful."
7261 (interactive)
7262 (let ((element (org-element-at-point)))
7263 (unless (memq (org-element-type element)
7264 '(center-block comment-block dynamic-block example-block
7265 export-block quote-block special-block
7266 src-block verse-block))
7267 (user-error "Not at a block"))
7268 (let* ((start (save-excursion
7269 (goto-char (org-element-property :post-affiliated element))
7270 (line-end-position)))
7271 (end (save-excursion
7272 (goto-char (org-element-property :end element))
7273 (skip-chars-backward " \r\t\n")
7274 (line-end-position)))
7275 (overlays (overlays-at start)))
7276 (cond
7277 ;; Do nothing when not before or at the block opening line or
7278 ;; at the block closing line.
7279 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7280 ((and (not (eq force 'off))
7281 (not (memq t (mapcar
7282 (lambda (o)
7283 (eq (overlay-get o 'invisible) 'org-hide-block))
7284 overlays))))
7285 (let ((ov (make-overlay start end)))
7286 (overlay-put ov 'invisible 'org-hide-block)
7287 ;; Make the block accessible to `isearch'.
7288 (overlay-put
7289 ov 'isearch-open-invisible
7290 (lambda (ov)
7291 (when (memq ov org-hide-block-overlays)
7292 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7293 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7294 (delete-overlay ov))))
7295 (push ov org-hide-block-overlays)
7296 ;; When the block is hidden away, make sure point is left in
7297 ;; a visible part of the buffer.
7298 (when (> (line-beginning-position) start)
7299 (goto-char start)
7300 (beginning-of-line))
7301 ;; Signal successful toggling.
7303 ((or (not force) (eq force 'off))
7304 (dolist (ov overlays t)
7305 (when (memq ov org-hide-block-overlays)
7306 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7307 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7308 (delete-overlay ov))))))))
7310 ;; Remove overlays when changing major mode
7311 (add-hook 'org-mode-hook
7312 (lambda () (add-hook 'change-major-mode-hook
7313 'org-show-block-all 'append 'local)))
7315 ;;; Indirect buffer display of subtrees
7317 (defvar org-indirect-dedicated-frame nil
7318 "This is the frame being used for indirect tree display.")
7319 (defvar org-last-indirect-buffer nil)
7321 (defun org-tree-to-indirect-buffer (&optional arg)
7322 "Create indirect buffer and narrow it to current subtree.
7324 With a numerical prefix ARG, go up to this level and then take that tree.
7325 If ARG is negative, go up that many levels.
7327 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7328 indirect buffer previously made with this command, to avoid proliferation of
7329 indirect buffers. However, when you call the command with a \
7330 `\\[universal-argument]' prefix, or
7331 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7332 so that you can work with several indirect buffers at the same time. If
7333 `org-indirect-buffer-display' is `dedicated-frame', the \
7334 `\\[universal-argument]' prefix also
7335 requests that a new frame be made for the new buffer, so that the dedicated
7336 frame is not changed."
7337 (interactive "P")
7338 (let ((cbuf (current-buffer))
7339 (cwin (selected-window))
7340 (pos (point))
7341 beg end level heading ibuf)
7342 (save-excursion
7343 (org-back-to-heading t)
7344 (when (numberp arg)
7345 (setq level (org-outline-level))
7346 (when (< arg 0) (setq arg (+ level arg)))
7347 (while (> (setq level (org-outline-level)) arg)
7348 (org-up-heading-safe)))
7349 (setq beg (point)
7350 heading (org-get-heading 'no-tags))
7351 (org-end-of-subtree t t)
7352 (when (org-at-heading-p) (backward-char 1))
7353 (setq end (point)))
7354 (when (and (buffer-live-p org-last-indirect-buffer)
7355 (not (eq org-indirect-buffer-display 'new-frame))
7356 (not arg))
7357 (kill-buffer org-last-indirect-buffer))
7358 (setq ibuf (org-get-indirect-buffer cbuf heading)
7359 org-last-indirect-buffer ibuf)
7360 (cond
7361 ((or (eq org-indirect-buffer-display 'new-frame)
7362 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7363 (select-frame (make-frame))
7364 (delete-other-windows)
7365 (pop-to-buffer-same-window ibuf)
7366 (org-set-frame-title heading))
7367 ((eq org-indirect-buffer-display 'dedicated-frame)
7368 (raise-frame
7369 (select-frame (or (and org-indirect-dedicated-frame
7370 (frame-live-p org-indirect-dedicated-frame)
7371 org-indirect-dedicated-frame)
7372 (setq org-indirect-dedicated-frame (make-frame)))))
7373 (delete-other-windows)
7374 (pop-to-buffer-same-window ibuf)
7375 (org-set-frame-title (concat "Indirect: " heading)))
7376 ((eq org-indirect-buffer-display 'current-window)
7377 (pop-to-buffer-same-window ibuf))
7378 ((eq org-indirect-buffer-display 'other-window)
7379 (pop-to-buffer ibuf))
7380 (t (error "Invalid value")))
7381 (narrow-to-region beg end)
7382 (outline-show-all)
7383 (goto-char pos)
7384 (run-hook-with-args 'org-cycle-hook 'all)
7385 (and (window-live-p cwin) (select-window cwin))))
7387 (defun org-get-indirect-buffer (&optional buffer heading)
7388 (setq buffer (or buffer (current-buffer)))
7389 (let ((n 1) (base (buffer-name buffer)) bname)
7390 (while (buffer-live-p
7391 (get-buffer
7392 (setq bname
7393 (concat base "-"
7394 (if heading (concat heading "-" (number-to-string n))
7395 (number-to-string n))))))
7396 (setq n (1+ n)))
7397 (condition-case nil
7398 (make-indirect-buffer buffer bname 'clone)
7399 (error (make-indirect-buffer buffer bname)))))
7401 (defun org-set-frame-title (title)
7402 "Set the title of the current frame to the string TITLE."
7403 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7405 ;;;; Structure editing
7407 ;;; Inserting headlines
7409 (defun org--line-empty-p (n)
7410 "Is the Nth next line empty?
7412 Counts the current line as N = 1 and the previous line as N = 0;
7413 see `beginning-of-line'."
7414 (save-excursion
7415 (and (not (bobp))
7416 (or (beginning-of-line n) t)
7417 (save-match-data
7418 (looking-at "[ \t]*$")))))
7420 (defun org-previous-line-empty-p ()
7421 "Is the previous line a blank line?
7422 When NEXT is non-nil, check the next line instead."
7423 (org--line-empty-p 0))
7425 (defun org-next-line-empty-p ()
7426 "Is the previous line a blank line?
7427 When NEXT is non-nil, check the next line instead."
7428 (org--line-empty-p 2))
7430 (defun org--blank-before-heading-p (&optional parent)
7431 "Non-nil when an empty line should precede a new heading here.
7432 When optional argument PARENT is non-nil, consider parent
7433 headline instead of current one."
7434 (pcase (assq 'heading org-blank-before-new-entry)
7435 (`(heading . auto)
7436 (save-excursion
7437 (org-with-limited-levels
7438 (unless (and (org-before-first-heading-p)
7439 (not (outline-next-heading)))
7440 (org-back-to-heading t)
7441 (when parent (org-up-heading-safe))
7442 (cond ((not (bobp))
7443 (org-previous-line-empty-p))
7444 ((outline-next-heading)
7445 (org-previous-line-empty-p))
7446 ;; Ignore trailing spaces on last buffer line.
7447 ((progn (skip-chars-backward " \t") (bolp))
7448 (org-previous-line-empty-p))
7449 (t nil))))))
7450 (`(heading . ,value) value)
7451 (_ nil)))
7453 (defun org-insert-heading (&optional arg invisible-ok top)
7454 "Insert a new heading or an item with the same depth at point.
7456 If point is at the beginning of a heading, insert a new heading
7457 or a new headline above the current one. When at the beginning
7458 of a regular line of text, turn it into a heading.
7460 If point is in the middle of a line, split it and create a new
7461 headline with the text in the current line after point (see
7462 `org-M-RET-may-split-line' on how to modify this behavior). As
7463 a special case, on a headline, splitting can only happen on the
7464 title itself. E.g., this excludes breaking stars or tags.
7466 With a `\\[universal-argument]' prefix, set \
7467 `org-insert-heading-respect-content' to
7468 a non-nil value for the duration of the command. This forces the
7469 insertion of a heading after the current subtree, independently
7470 on the location of point.
7472 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7473 insert the heading at the end of the tree
7474 above the current heading. For example, if point is within a
7475 2nd-level heading, then it will insert a 2nd-level heading at
7476 the end of the 1st-level parent subtree.
7478 When INVISIBLE-OK is set, stop at invisible headlines when going
7479 back. This is important for non-interactive uses of the
7480 command.
7482 When optional argument TOP is non-nil, insert a level 1 heading,
7483 unconditionally."
7484 (interactive "P")
7485 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7486 (level (org-current-level))
7487 (stars (make-string (if (and level (not top)) level 1) ?*)))
7488 (cond
7489 ((or org-insert-heading-respect-content
7490 (member arg '((4) (16)))
7491 (and (not invisible-ok)
7492 (invisible-p (max (1- (point)) (point-min)))))
7493 ;; Position point at the location of insertion.
7494 (if (not level) ;before first headline
7495 (org-with-limited-levels (outline-next-heading))
7496 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7497 ;; is nil.
7498 (org-with-limited-levels (org-back-to-heading invisible-ok))
7499 (cond ((equal arg '(16))
7500 (org-up-heading-safe)
7501 (org-end-of-subtree t t))
7503 (org-end-of-subtree t t))))
7504 (unless (bolp) (insert "\n")) ;ensure final newline
7505 (unless (and blank? (org-previous-line-empty-p))
7506 (org-N-empty-lines-before-current (if blank? 1 0)))
7507 (insert stars " \n")
7508 (forward-char -1))
7509 ;; At a headline...
7510 ((org-at-heading-p)
7511 (cond ((bolp)
7512 (when blank? (save-excursion (insert "\n")))
7513 (save-excursion (insert stars " \n"))
7514 (unless (and blank? (org-previous-line-empty-p))
7515 (org-N-empty-lines-before-current (if blank? 1 0)))
7516 (end-of-line))
7517 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7518 (org-match-line org-complex-heading-regexp)
7519 (org-pos-in-match-range (point) 4))
7520 ;; Grab the text that should moved to the new headline.
7521 ;; Preserve tags.
7522 (let ((split (delete-and-extract-region (point) (match-end 4))))
7523 (if (looking-at "[ \t]*$") (replace-match "")
7524 (org-set-tags nil t))
7525 (end-of-line)
7526 (when blank? (insert "\n"))
7527 (insert "\n" stars " ")
7528 (when (org-string-nw-p split) (insert split))
7529 (when (eobp) (save-excursion (insert "\n")))))
7531 (end-of-line)
7532 (when blank? (insert "\n"))
7533 (insert "\n" stars " ")
7534 (when (eobp) (save-excursion (insert "\n"))))))
7535 ;; On regular text, turn line into a headline or split, if
7536 ;; appropriate.
7537 ((bolp)
7538 (insert stars " ")
7539 (unless (and blank? (org-previous-line-empty-p))
7540 (org-N-empty-lines-before-current (if blank? 1 0))))
7542 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7543 (end-of-line))
7544 (insert "\n" stars " ")
7545 (unless (and blank? (org-previous-line-empty-p))
7546 (org-N-empty-lines-before-current (if blank? 1 0))))))
7547 (run-hooks 'org-insert-heading-hook))
7549 (defun org-N-empty-lines-before-current (n)
7550 "Make the number of empty lines before current exactly N.
7551 So this will delete or add empty lines."
7552 (let ((column (current-column)))
7553 (beginning-of-line)
7554 (unless (bobp)
7555 (let ((start (save-excursion
7556 (skip-chars-backward " \r\t\n")
7557 (line-end-position))))
7558 (delete-region start (line-end-position 0))))
7559 (insert (make-string n ?\n))
7560 (move-to-column column)))
7562 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7563 "Return the heading of the current entry, without the stars.
7564 When NO-TAGS is non-nil, don't include tags.
7565 When NO-TODO is non-nil, don't include TODO keywords.
7566 When NO-PRIORITY is non-nil, don't include priority cookie.
7567 When NO-COMMENT is non-nil, don't include COMMENT string."
7568 (save-excursion
7569 (org-back-to-heading t)
7570 (let ((case-fold-search nil))
7571 (looking-at org-complex-heading-regexp)
7572 (let ((todo (and (not no-todo) (match-string 2)))
7573 (priority (and (not no-priority) (match-string 3)))
7574 (headline (pcase (match-string 4)
7575 (`nil "")
7576 ((and (guard no-comment) h)
7577 (replace-regexp-in-string
7578 (eval-when-compile
7579 (format "\\`%s[ \t]+" org-comment-string))
7580 "" h))
7581 (h h)))
7582 (tags (and (not no-tags) (match-string 5))))
7583 (mapconcat #'identity
7584 (delq nil (list todo priority headline tags))
7585 " ")))))
7587 (defvar orgstruct-mode) ; defined below
7589 (defun org-heading-components ()
7590 "Return the components of the current heading.
7591 This is a list with the following elements:
7592 - the level as an integer
7593 - the reduced level, different if `org-odd-levels-only' is set.
7594 - the TODO keyword, or nil
7595 - the priority character, like ?A, or nil if no priority is given
7596 - the headline text itself, or the tags string if no headline text
7597 - the tags string, or nil."
7598 (save-excursion
7599 (org-back-to-heading t)
7600 (when (let (case-fold-search)
7601 (looking-at
7602 (if orgstruct-mode
7603 org-heading-regexp
7604 org-complex-heading-regexp)))
7605 (if orgstruct-mode
7606 (list (length (match-string 1))
7607 (org-reduced-level (length (match-string 1)))
7610 (match-string 2)
7611 nil)
7612 (list (length (match-string 1))
7613 (org-reduced-level (length (match-string 1)))
7614 (match-string-no-properties 2)
7615 (and (match-end 3) (aref (match-string 3) 2))
7616 (match-string-no-properties 4)
7617 (match-string-no-properties 5))))))
7619 (defun org-get-entry ()
7620 "Get the entry text, after heading, entire subtree."
7621 (save-excursion
7622 (org-back-to-heading t)
7623 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7625 (defun org-edit-headline (&optional heading)
7626 "Edit the current headline.
7627 Set it to HEADING when provided."
7628 (interactive)
7629 (org-with-wide-buffer
7630 (org-back-to-heading t)
7631 (let ((case-fold-search nil))
7632 (when (looking-at org-complex-heading-regexp)
7633 (let* ((old (match-string-no-properties 4))
7634 (new (save-match-data
7635 (org-trim (or heading (read-string "Edit: " old))))))
7636 (unless (equal old new)
7637 (if old (replace-match new t t nil 4)
7638 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7639 (insert " " new))
7640 (org-set-tags nil t)
7641 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7643 (defun org-insert-heading-after-current ()
7644 "Insert a new heading with same level as current, after current subtree."
7645 (interactive)
7646 (org-back-to-heading)
7647 (org-insert-heading)
7648 (org-move-subtree-down)
7649 (end-of-line 1))
7651 (defun org-insert-heading-respect-content (&optional invisible-ok)
7652 "Insert heading with `org-insert-heading-respect-content' set to t."
7653 (interactive)
7654 (org-insert-heading '(4) invisible-ok))
7656 (defun org-insert-todo-heading-respect-content (&optional force-state)
7657 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7658 (interactive)
7659 (org-insert-todo-heading force-state '(4)))
7661 (defun org-insert-todo-heading (arg &optional force-heading)
7662 "Insert a new heading with the same level and TODO state as current heading.
7664 If the heading has no TODO state, or if the state is DONE, use
7665 the first state (TODO by default). Also with one prefix arg,
7666 force first state. With two prefix args, force inserting at the
7667 end of the parent subtree.
7669 When called at a plain list item, insert a new item with an
7670 unchecked check box."
7671 (interactive "P")
7672 (when (or force-heading (not (org-insert-item 'checkbox)))
7673 (org-insert-heading (or (and (equal arg '(16)) '(16))
7674 force-heading))
7675 (save-excursion
7676 (org-forward-heading-same-level -1)
7677 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7678 (let* ((new-mark-x
7679 (if (or (equal arg '(4))
7680 (not (match-beginning 2))
7681 (member (match-string 2) org-done-keywords))
7682 (car org-todo-keywords-1)
7683 (match-string 2)))
7684 (new-mark
7686 (run-hook-with-args-until-success
7687 'org-todo-get-default-hook new-mark-x nil)
7688 new-mark-x)))
7689 (beginning-of-line 1)
7690 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7691 (if org-treat-insert-todo-heading-as-state-change
7692 (org-todo new-mark)
7693 (insert new-mark " "))))
7694 (when org-provide-todo-statistics
7695 (org-update-parent-todo-statistics))))
7697 (defun org-insert-subheading (arg)
7698 "Insert a new subheading and demote it.
7699 Works for outline headings and for plain lists alike."
7700 (interactive "P")
7701 (org-insert-heading arg)
7702 (cond
7703 ((org-at-heading-p) (org-do-demote))
7704 ((org-at-item-p) (org-indent-item))))
7706 (defun org-insert-todo-subheading (arg)
7707 "Insert a new subheading with TODO keyword or checkbox and demote it.
7708 Works for outline headings and for plain lists alike."
7709 (interactive "P")
7710 (org-insert-todo-heading arg)
7711 (cond
7712 ((org-at-heading-p) (org-do-demote))
7713 ((org-at-item-p) (org-indent-item))))
7715 ;;; Promotion and Demotion
7717 (defvar org-after-demote-entry-hook nil
7718 "Hook run after an entry has been demoted.
7719 The cursor will be at the beginning of the entry.
7720 When a subtree is being demoted, the hook will be called for each node.")
7722 (defvar org-after-promote-entry-hook nil
7723 "Hook run after an entry has been promoted.
7724 The cursor will be at the beginning of the entry.
7725 When a subtree is being promoted, the hook will be called for each node.")
7727 (defun org-promote-subtree ()
7728 "Promote the entire subtree.
7729 See also `org-promote'."
7730 (interactive)
7731 (save-excursion
7732 (org-with-limited-levels (org-map-tree 'org-promote)))
7733 (org-fix-position-after-promote))
7735 (defun org-demote-subtree ()
7736 "Demote the entire subtree.
7737 See `org-demote' and `org-promote'."
7738 (interactive)
7739 (save-excursion
7740 (org-with-limited-levels (org-map-tree 'org-demote)))
7741 (org-fix-position-after-promote))
7743 (defun org-do-promote ()
7744 "Promote the current heading higher up the tree.
7745 If the region is active in `transient-mark-mode', promote all
7746 headings in the region."
7747 (interactive)
7748 (save-excursion
7749 (if (org-region-active-p)
7750 (org-map-region 'org-promote (region-beginning) (region-end))
7751 (org-promote)))
7752 (org-fix-position-after-promote))
7754 (defun org-do-demote ()
7755 "Demote the current heading lower down the tree.
7756 If the region is active in `transient-mark-mode', demote all
7757 headings in the region."
7758 (interactive)
7759 (save-excursion
7760 (if (org-region-active-p)
7761 (org-map-region 'org-demote (region-beginning) (region-end))
7762 (org-demote)))
7763 (org-fix-position-after-promote))
7765 (defun org-fix-position-after-promote ()
7766 "Fix cursor position and indentation after demoting/promoting."
7767 (let ((pos (point)))
7768 (when (save-excursion
7769 (beginning-of-line)
7770 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7771 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7772 (cond ((eobp) (insert " "))
7773 ((eolp) (insert " "))
7774 ((equal (char-after) ?\s) (forward-char 1))))))
7776 (defun org-current-level ()
7777 "Return the level of the current entry, or nil if before the first headline.
7778 The level is the number of stars at the beginning of the
7779 headline. Use `org-reduced-level' to remove the effect of
7780 `org-odd-levels'. Unlike to `org-outline-level', this function
7781 ignores inlinetasks."
7782 (let ((level (org-with-limited-levels (org-outline-level))))
7783 (and (> level 0) level)))
7785 (defun org-get-previous-line-level ()
7786 "Return the outline depth of the last headline before the current line.
7787 Returns 0 for the first headline in the buffer, and nil if before the
7788 first headline."
7789 (and (org-current-level)
7790 (or (and (/= (line-beginning-position) (point-min))
7791 (save-excursion (beginning-of-line 0) (org-current-level)))
7792 0)))
7794 (defun org-reduced-level (l)
7795 "Compute the effective level of a heading.
7796 This takes into account the setting of `org-odd-levels-only'."
7797 (cond
7798 ((zerop l) 0)
7799 (org-odd-levels-only (1+ (floor (/ l 2))))
7800 (t l)))
7802 (defun org-level-increment ()
7803 "Return the number of stars that will be added or removed at a
7804 time to headlines when structure editing, based on the value of
7805 `org-odd-levels-only'."
7806 (if org-odd-levels-only 2 1))
7808 (defun org-get-valid-level (level &optional change)
7809 "Rectify a level change under the influence of `org-odd-levels-only'.
7810 LEVEL is a current level, CHANGE is by how much the level should
7811 be modified. Even if CHANGE is nil, LEVEL may be returned
7812 modified because even level numbers will become the next higher
7813 odd number. Returns values greater than 0."
7814 (if org-odd-levels-only
7815 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7816 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7817 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7818 (max 1 (+ level (or change 0)))))
7820 (defun org-promote ()
7821 "Promote the current heading higher up the tree."
7822 (org-with-wide-buffer
7823 (org-back-to-heading t)
7824 (let* ((after-change-functions (remq 'flyspell-after-change-function
7825 after-change-functions))
7826 (level (save-match-data (funcall outline-level)))
7827 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7828 (diff (abs (- level (length up-head) -1))))
7829 (cond
7830 ((and (= level 1) org-allow-promoting-top-level-subtree)
7831 (replace-match "# " nil t))
7832 ((= level 1)
7833 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7834 (t (replace-match up-head nil t)))
7835 (unless (= level 1)
7836 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7837 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7838 (run-hooks 'org-after-promote-entry-hook))))
7840 (defun org-demote ()
7841 "Demote the current heading lower down the tree."
7842 (org-with-wide-buffer
7843 (org-back-to-heading t)
7844 (let* ((after-change-functions (remq 'flyspell-after-change-function
7845 after-change-functions))
7846 (level (save-match-data (funcall outline-level)))
7847 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7848 (diff (abs (- level (length down-head) -1))))
7849 (replace-match down-head nil t)
7850 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7851 (when org-adapt-indentation (org-fixup-indentation diff))
7852 (run-hooks 'org-after-demote-entry-hook))))
7854 (defun org-cycle-level ()
7855 "Cycle the level of an empty headline through possible states.
7856 This goes first to child, then to parent, level, then up the hierarchy.
7857 After top level, it switches back to sibling level."
7858 (interactive)
7859 (let ((org-adapt-indentation nil))
7860 (when (org-point-at-end-of-empty-headline)
7861 (setq this-command 'org-cycle-level) ; Only needed for caching
7862 (let ((cur-level (org-current-level))
7863 (prev-level (org-get-previous-line-level)))
7864 (cond
7865 ;; If first headline in file, promote to top-level.
7866 ((= prev-level 0)
7867 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7868 do (org-do-promote)))
7869 ;; If same level as prev, demote one.
7870 ((= prev-level cur-level)
7871 (org-do-demote))
7872 ;; If parent is top-level, promote to top level if not already.
7873 ((= prev-level 1)
7874 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7875 do (org-do-promote)))
7876 ;; If top-level, return to prev-level.
7877 ((= cur-level 1)
7878 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7879 do (org-do-demote)))
7880 ;; If less than prev-level, promote one.
7881 ((< cur-level prev-level)
7882 (org-do-promote))
7883 ;; If deeper than prev-level, promote until higher than
7884 ;; prev-level.
7885 ((> cur-level prev-level)
7886 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7887 do (org-do-promote))))
7888 t))))
7890 (defun org-map-tree (fun)
7891 "Call FUN for every heading underneath the current one."
7892 (org-back-to-heading t)
7893 (let ((level (funcall outline-level)))
7894 (save-excursion
7895 (funcall fun)
7896 (while (and (progn
7897 (outline-next-heading)
7898 (> (funcall outline-level) level))
7899 (not (eobp)))
7900 (funcall fun)))))
7902 (defun org-map-region (fun beg end)
7903 "Call FUN for every heading between BEG and END."
7904 (let ((org-ignore-region t))
7905 (save-excursion
7906 (setq end (copy-marker end))
7907 (goto-char beg)
7908 (when (and (re-search-forward org-outline-regexp-bol nil t)
7909 (< (point) end))
7910 (funcall fun))
7911 (while (and (progn
7912 (outline-next-heading)
7913 (< (point) end))
7914 (not (eobp)))
7915 (funcall fun)))))
7917 (defun org-fixup-indentation (diff)
7918 "Change the indentation in the current entry by DIFF.
7920 DIFF is an integer. Indentation is done according to the
7921 following rules:
7923 - Planning information and property drawers are always indented
7924 according to the new level of the headline;
7926 - Footnote definitions and their contents are ignored;
7928 - Inlinetasks' boundaries are not shifted;
7930 - Empty lines are ignored;
7932 - Other lines' indentation are shifted by DIFF columns, unless
7933 it would introduce a structural change in the document, in
7934 which case no shifting is done at all.
7936 Assume point is at a heading or an inlinetask beginning."
7937 (org-with-wide-buffer
7938 (narrow-to-region (line-beginning-position)
7939 (save-excursion
7940 (if (org-with-limited-levels (org-at-heading-p))
7941 (org-with-limited-levels (outline-next-heading))
7942 (org-inlinetask-goto-end))
7943 (point)))
7944 (forward-line)
7945 ;; Indent properly planning info and property drawer.
7946 (when (looking-at-p org-planning-line-re)
7947 (org-indent-line)
7948 (forward-line))
7949 (when (looking-at org-property-drawer-re)
7950 (goto-char (match-end 0))
7951 (forward-line)
7952 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7953 (catch 'no-shift
7954 (when (zerop diff) (throw 'no-shift nil))
7955 ;; If DIFF is negative, first check if a shift is possible at all
7956 ;; (e.g., it doesn't break structure). This can only happen if
7957 ;; some contents are not properly indented.
7958 (let ((case-fold-search t))
7959 (when (< diff 0)
7960 (let ((diff (- diff))
7961 (forbidden-re (concat org-outline-regexp
7962 "\\|"
7963 (substring org-footnote-definition-re 1))))
7964 (save-excursion
7965 (while (not (eobp))
7966 (cond
7967 ((looking-at-p "[ \t]*$") (forward-line))
7968 ((and (looking-at-p org-footnote-definition-re)
7969 (let ((e (org-element-at-point)))
7970 (and (eq (org-element-type e) 'footnote-definition)
7971 (goto-char (org-element-property :end e))))))
7972 ((looking-at-p org-outline-regexp) (forward-line))
7973 ;; Give up if shifting would move before column 0 or
7974 ;; if it would introduce a headline or a footnote
7975 ;; definition.
7977 (skip-chars-forward " \t")
7978 (let ((ind (current-column)))
7979 (when (or (< ind diff)
7980 (and (= ind diff) (looking-at-p forbidden-re)))
7981 (throw 'no-shift nil)))
7982 ;; Ignore contents of example blocks and source
7983 ;; blocks if their indentation is meant to be
7984 ;; preserved. Jump to block's closing line.
7985 (beginning-of-line)
7986 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7987 (let ((e (org-element-at-point)))
7988 (and (memq (org-element-type e)
7989 '(example-block src-block))
7990 (or org-src-preserve-indentation
7991 (org-element-property :preserve-indent e))
7992 (goto-char (org-element-property :end e))
7993 (progn (skip-chars-backward " \r\t\n")
7994 (beginning-of-line)
7995 t))))
7996 (forward-line))))))))
7997 ;; Shift lines but footnote definitions, inlinetasks boundaries
7998 ;; by DIFF. Also skip contents of source or example blocks
7999 ;; when indentation is meant to be preserved.
8000 (while (not (eobp))
8001 (cond
8002 ((and (looking-at-p org-footnote-definition-re)
8003 (let ((e (org-element-at-point)))
8004 (and (eq (org-element-type e) 'footnote-definition)
8005 (goto-char (org-element-property :end e))))))
8006 ((looking-at-p org-outline-regexp) (forward-line))
8007 ((looking-at-p "[ \t]*$") (forward-line))
8009 (indent-line-to (+ (org-get-indentation) diff))
8010 (beginning-of-line)
8011 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8012 (let ((e (org-element-at-point)))
8013 (and (memq (org-element-type e)
8014 '(example-block src-block))
8015 (or org-src-preserve-indentation
8016 (org-element-property :preserve-indent e))
8017 (goto-char (org-element-property :end e))
8018 (progn (skip-chars-backward " \r\t\n")
8019 (beginning-of-line)
8020 t))))
8021 (forward-line)))))))))
8023 (defun org-convert-to-odd-levels ()
8024 "Convert an Org file with all levels allowed to one with odd levels.
8025 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8026 level 5 etc."
8027 (interactive)
8028 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8029 (let ((outline-level 'org-outline-level)
8030 (org-odd-levels-only nil) n)
8031 (save-excursion
8032 (goto-char (point-min))
8033 (while (re-search-forward "^\\*\\*+ " nil t)
8034 (setq n (- (length (match-string 0)) 2))
8035 (while (>= (setq n (1- n)) 0)
8036 (org-demote))
8037 (end-of-line 1))))))
8039 (defun org-convert-to-oddeven-levels ()
8040 "Convert an Org file with only odd levels to one with odd/even levels.
8041 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8042 file contains a section with an even level, conversion would
8043 destroy the structure of the file. An error is signaled in this
8044 case."
8045 (interactive)
8046 (goto-char (point-min))
8047 ;; First check if there are no even levels
8048 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8049 (org-show-set-visibility 'canonical)
8050 (error "Not all levels are odd in this file. Conversion not possible"))
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8052 (let ((outline-regexp org-outline-regexp)
8053 (outline-level 'org-outline-level)
8054 (org-odd-levels-only nil) n)
8055 (save-excursion
8056 (goto-char (point-min))
8057 (while (re-search-forward "^\\*\\*+ " nil t)
8058 (setq n (/ (1- (length (match-string 0))) 2))
8059 (while (>= (setq n (1- n)) 0)
8060 (org-promote))
8061 (end-of-line 1))))))
8063 (defun org-tr-level (n)
8064 "Make N odd if required."
8065 (if org-odd-levels-only (1+ (/ n 2)) n))
8067 ;;; Vertical tree motion, cutting and pasting of subtrees
8069 (defun org-move-subtree-up (&optional arg)
8070 "Move the current subtree up past ARG headlines of the same level."
8071 (interactive "p")
8072 (org-move-subtree-down (- (prefix-numeric-value arg))))
8074 (defun org-move-subtree-down (&optional arg)
8075 "Move the current subtree down past ARG headlines of the same level."
8076 (interactive "p")
8077 (setq arg (prefix-numeric-value arg))
8078 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8079 'org-get-last-sibling))
8080 (ins-point (make-marker))
8081 (cnt (abs arg))
8082 (col (current-column))
8083 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8084 ;; Select the tree
8085 (org-back-to-heading)
8086 (setq beg0 (point))
8087 (save-excursion
8088 (setq ne-beg (org-back-over-empty-lines))
8089 (setq beg (point)))
8090 (save-match-data
8091 (save-excursion (outline-end-of-heading)
8092 (setq folded (org-invisible-p)))
8093 (progn (org-end-of-subtree nil t)
8094 (unless (eobp) (backward-char))))
8095 (outline-next-heading)
8096 (setq ne-end (org-back-over-empty-lines))
8097 (setq end (point))
8098 (goto-char beg0)
8099 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8100 ;; include less whitespace
8101 (save-excursion
8102 (goto-char beg)
8103 (forward-line (- ne-beg ne-end))
8104 (setq beg (point))))
8105 ;; Find insertion point, with error handling
8106 (while (> cnt 0)
8107 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8108 (progn (goto-char beg0)
8109 (user-error "Cannot move past superior level or buffer limit")))
8110 (setq cnt (1- cnt)))
8111 (when (> arg 0)
8112 ;; Moving forward - still need to move over subtree
8113 (org-end-of-subtree t t)
8114 (save-excursion
8115 (org-back-over-empty-lines)
8116 (or (bolp) (newline))))
8117 (setq ne-ins (org-back-over-empty-lines))
8118 (move-marker ins-point (point))
8119 (setq txt (buffer-substring beg end))
8120 (org-save-markers-in-region beg end)
8121 (delete-region beg end)
8122 (org-remove-empty-overlays-at beg)
8123 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8124 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8125 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8126 (let ((bbb (point)))
8127 (insert-before-markers txt)
8128 (org-reinstall-markers-in-region bbb)
8129 (move-marker ins-point bbb))
8130 (or (bolp) (insert "\n"))
8131 (setq ins-end (point))
8132 (goto-char ins-point)
8133 (org-skip-whitespace)
8134 (when (and (< arg 0)
8135 (org-first-sibling-p)
8136 (> ne-ins ne-beg))
8137 ;; Move whitespace back to beginning
8138 (save-excursion
8139 (goto-char ins-end)
8140 (let ((kill-whole-line t))
8141 (kill-line (- ne-ins ne-beg)) (point)))
8142 (insert (make-string (- ne-ins ne-beg) ?\n)))
8143 (move-marker ins-point nil)
8144 (if folded
8145 (outline-hide-subtree)
8146 (org-show-entry)
8147 (org-show-children)
8148 (org-cycle-hide-drawers 'children))
8149 (org-clean-visibility-after-subtree-move)
8150 ;; move back to the initial column we were at
8151 (move-to-column col)))
8153 (defvar org-subtree-clip ""
8154 "Clipboard for cut and paste of subtrees.
8155 This is actually only a copy of the kill, because we use the normal kill
8156 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8158 (defvar org-subtree-clip-folded nil
8159 "Was the last copied subtree folded?
8160 This is used to fold the tree back after pasting.")
8162 (defun org-cut-subtree (&optional n)
8163 "Cut the current subtree into the clipboard.
8164 With prefix arg N, cut this many sequential subtrees.
8165 This is a short-hand for marking the subtree and then cutting it."
8166 (interactive "p")
8167 (org-copy-subtree n 'cut))
8169 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8170 "Copy the current subtree it in the clipboard.
8171 With prefix arg N, copy this many sequential subtrees.
8172 This is a short-hand for marking the subtree and then copying it.
8173 If CUT is non-nil, actually cut the subtree.
8174 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8175 of some markers in the region, even if CUT is non-nil. This is
8176 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8177 (interactive "p")
8178 (let (beg end folded (beg0 (point)))
8179 (if (called-interactively-p 'any)
8180 (org-back-to-heading nil) ; take what looks like a subtree
8181 (org-back-to-heading t)) ; take what is really there
8182 (setq beg (point))
8183 (skip-chars-forward " \t\r\n")
8184 (save-match-data
8185 (if nosubtrees
8186 (outline-next-heading)
8187 (save-excursion (outline-end-of-heading)
8188 (setq folded (org-invisible-p)))
8189 (ignore-errors (org-forward-heading-same-level (1- n) t))
8190 (org-end-of-subtree t t)))
8191 ;; Include the end of an inlinetask
8192 (when (and (featurep 'org-inlinetask)
8193 (looking-at-p (concat (org-inlinetask-outline-regexp)
8194 "END[ \t]*$")))
8195 (end-of-line))
8196 (setq end (point))
8197 (goto-char beg0)
8198 (when (> end beg)
8199 (setq org-subtree-clip-folded folded)
8200 (when (or cut force-store-markers)
8201 (org-save-markers-in-region beg end))
8202 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8203 (setq org-subtree-clip (current-kill 0))
8204 (message "%s: Subtree(s) with %d characters"
8205 (if cut "Cut" "Copied")
8206 (length org-subtree-clip)))))
8208 (defun org-paste-subtree (&optional level tree for-yank remove)
8209 "Paste the clipboard as a subtree, with modification of headline level.
8210 The entire subtree is promoted or demoted in order to match a new headline
8211 level.
8213 If the cursor is at the beginning of a headline, the same level as
8214 that headline is used to paste the tree.
8216 If not, the new level is derived from the *visible* headings
8217 before and after the insertion point, and taken to be the inferior headline
8218 level of the two. So if the previous visible heading is level 3 and the
8219 next is level 4 (or vice versa), level 4 will be used for insertion.
8220 This makes sure that the subtree remains an independent subtree and does
8221 not swallow low level entries.
8223 You can also force a different level, either by using a numeric prefix
8224 argument, or by inserting the heading marker by hand. For example, if the
8225 cursor is after \"*****\", then the tree will be shifted to level 5.
8227 If optional TREE is given, use this text instead of the kill ring.
8229 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8230 move back over whitespace before inserting, and move point to the end of
8231 the inserted text when done.
8233 When REMOVE is non-nil, remove the subtree from the clipboard."
8234 (interactive "P")
8235 (setq tree (or tree (and kill-ring (current-kill 0))))
8236 (unless (org-kill-is-subtree-p tree)
8237 (user-error "%s"
8238 (substitute-command-keys
8239 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8240 (org-with-limited-levels
8241 (let* ((visp (not (org-invisible-p)))
8242 (txt tree)
8243 (^re_ "\\(\\*+\\)[ \t]*")
8244 (old-level (if (string-match org-outline-regexp-bol txt)
8245 (- (match-end 0) (match-beginning 0) 1)
8246 -1))
8247 (force-level (cond (level (prefix-numeric-value level))
8248 ((and (looking-at "[ \t]*$")
8249 (string-match
8250 "^\\*+$" (buffer-substring
8251 (point-at-bol) (point))))
8252 (- (match-end 0) (match-beginning 0)))
8253 ((and (bolp)
8254 (looking-at org-outline-regexp))
8255 (- (match-end 0) (point) 1))))
8256 (previous-level (save-excursion
8257 (condition-case nil
8258 (progn
8259 (outline-previous-visible-heading 1)
8260 (if (looking-at ^re_)
8261 (- (match-end 0) (match-beginning 0) 1)
8263 (error 1))))
8264 (next-level (save-excursion
8265 (condition-case nil
8266 (progn
8267 (or (looking-at org-outline-regexp)
8268 (outline-next-visible-heading 1))
8269 (if (looking-at ^re_)
8270 (- (match-end 0) (match-beginning 0) 1)
8272 (error 1))))
8273 (new-level (or force-level (max previous-level next-level)))
8274 (shift (if (or (= old-level -1)
8275 (= new-level -1)
8276 (= old-level new-level))
8278 (- new-level old-level)))
8279 (delta (if (> shift 0) -1 1))
8280 (func (if (> shift 0) 'org-demote 'org-promote))
8281 (org-odd-levels-only nil)
8282 beg end newend)
8283 ;; Remove the forced level indicator
8284 (when force-level
8285 (delete-region (point-at-bol) (point)))
8286 ;; Paste
8287 (beginning-of-line (if (bolp) 1 2))
8288 (setq beg (point))
8289 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8290 (insert-before-markers txt)
8291 (unless (string-suffix-p "\n" txt) (insert "\n"))
8292 (setq newend (point))
8293 (org-reinstall-markers-in-region beg)
8294 (setq end (point))
8295 (goto-char beg)
8296 (skip-chars-forward " \t\n\r")
8297 (setq beg (point))
8298 (when (and (org-invisible-p) visp)
8299 (save-excursion (outline-show-heading)))
8300 ;; Shift if necessary
8301 (unless (= shift 0)
8302 (save-restriction
8303 (narrow-to-region beg end)
8304 (while (not (= shift 0))
8305 (org-map-region func (point-min) (point-max))
8306 (setq shift (+ delta shift)))
8307 (goto-char (point-min))
8308 (setq newend (point-max))))
8309 (when (or (called-interactively-p 'interactive) for-yank)
8310 (message "Clipboard pasted as level %d subtree" new-level))
8311 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8312 kill-ring
8313 (eq org-subtree-clip (current-kill 0))
8314 org-subtree-clip-folded)
8315 ;; The tree was folded before it was killed/copied
8316 (outline-hide-subtree))
8317 (and for-yank (goto-char newend))
8318 (and remove (setq kill-ring (cdr kill-ring))))))
8320 (defun org-kill-is-subtree-p (&optional txt)
8321 "Check if the current kill is an outline subtree, or a set of trees.
8322 Returns nil if kill does not start with a headline, or if the first
8323 headline level is not the largest headline level in the tree.
8324 So this will actually accept several entries of equal levels as well,
8325 which is OK for `org-paste-subtree'.
8326 If optional TXT is given, check this string instead of the current kill."
8327 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8328 (re (org-get-limited-outline-regexp))
8329 (^re (concat "^" re))
8330 (start-level (and kill
8331 (string-match
8332 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8333 kill)
8334 (- (match-end 2) (match-beginning 2) 1)))
8335 (start (1+ (or (match-beginning 2) -1))))
8336 (if (not start-level)
8337 (progn
8338 nil) ;; does not even start with a heading
8339 (catch 'exit
8340 (while (setq start (string-match ^re kill (1+ start)))
8341 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8342 (throw 'exit nil)))
8343 t))))
8345 (defvar org-markers-to-move nil
8346 "Markers that should be moved with a cut-and-paste operation.
8347 Those markers are stored together with their positions relative to
8348 the start of the region.")
8350 (defun org-save-markers-in-region (beg end)
8351 "Check markers in region.
8352 If these markers are between BEG and END, record their position relative
8353 to BEG, so that after moving the block of text, we can put the markers back
8354 into place.
8355 This function gets called just before an entry or tree gets cut from the
8356 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8357 called immediately, to move the markers with the entries."
8358 (setq org-markers-to-move nil)
8359 (when (featurep 'org-clock)
8360 (org-clock-save-markers-for-cut-and-paste beg end))
8361 (when (featurep 'org-agenda)
8362 (org-agenda-save-markers-for-cut-and-paste beg end)))
8364 (defun org-check-and-save-marker (marker beg end)
8365 "Check if MARKER is between BEG and END.
8366 If yes, remember the marker and the distance to BEG."
8367 (when (and (marker-buffer marker)
8368 (equal (marker-buffer marker) (current-buffer))
8369 (>= marker beg) (< marker end))
8370 (push (cons marker (- marker beg)) org-markers-to-move)))
8372 (defun org-reinstall-markers-in-region (beg)
8373 "Move all remembered markers to their position relative to BEG."
8374 (dolist (x org-markers-to-move)
8375 (move-marker (car x) (+ beg (cdr x))))
8376 (setq org-markers-to-move nil))
8378 (defun org-narrow-to-subtree ()
8379 "Narrow buffer to the current subtree."
8380 (interactive)
8381 (save-excursion
8382 (save-match-data
8383 (org-with-limited-levels
8384 (narrow-to-region
8385 (progn (org-back-to-heading t) (point))
8386 (progn (org-end-of-subtree t t)
8387 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8388 (point)))))))
8390 (defun org-narrow-to-block ()
8391 "Narrow buffer to the current block."
8392 (interactive)
8393 (let* ((case-fold-search t)
8394 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8395 "^[ \t]*#\\+end_.*")))
8396 (if blockp
8397 (narrow-to-region (car blockp) (cdr blockp))
8398 (user-error "Not in a block"))))
8400 (defun org-clone-subtree-with-time-shift (n &optional shift)
8401 "Clone the task (subtree) at point N times.
8402 The clones will be inserted as siblings.
8404 In interactive use, the user will be prompted for the number of
8405 clones to be produced. If the entry has a timestamp, the user
8406 will also be prompted for a time shift, which may be a repeater
8407 as used in time stamps, for example `+3d'. To disable this,
8408 you can call the function with a universal prefix argument.
8410 When a valid repeater is given and the entry contains any time
8411 stamps, the clones will become a sequence in time, with time
8412 stamps in the subtree shifted for each clone produced. If SHIFT
8413 is nil or the empty string, time stamps will be left alone. The
8414 ID property of the original subtree is removed.
8416 In each clone, all the CLOCK entries will be removed. This
8417 prevents Org from considering that the clocked times overlap.
8419 If the original subtree did contain time stamps with a repeater,
8420 the following will happen:
8421 - the repeater will be removed in each clone
8422 - an additional clone will be produced, with the current, unshifted
8423 date(s) in the entry.
8424 - the original entry will be placed *after* all the clones, with
8425 repeater intact.
8426 - the start days in the repeater in the original entry will be shifted
8427 to past the last clone.
8428 In this way you can spell out a number of instances of a repeating task,
8429 and still retain the repeater to cover future instances of the task.
8431 As described above, N+1 clones are produced when the original
8432 subtree has a repeater. Setting N to 0, then, can be used to
8433 remove the repeater from a subtree and create a shifted clone
8434 with the original repeater."
8435 (interactive "nNumber of clones to produce: ")
8436 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8437 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8438 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8439 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8440 (shift
8441 (or shift
8442 (if (and (not (equal current-prefix-arg '(4)))
8443 (save-excursion
8444 (goto-char beg)
8445 (re-search-forward org-ts-regexp-both end-of-tree t)))
8446 (read-from-minibuffer
8447 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8448 ""))) ;No time shift
8449 (doshift
8450 (and (org-string-nw-p shift)
8451 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8452 shift)
8453 (user-error "Invalid shift specification %s" shift)))))
8454 (goto-char end-of-tree)
8455 (unless (bolp) (insert "\n"))
8456 (let* ((end (point))
8457 (template (buffer-substring beg end))
8458 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8459 (shift-what (pcase (and doshift (match-string 2 shift))
8460 (`nil nil)
8461 ("d" 'day)
8462 ("w" (setq shift-n (* 7 shift-n)) 'day)
8463 ("m" 'month)
8464 ("y" 'year)
8465 (_ (error "Unsupported time unit"))))
8466 (nmin 1)
8467 (nmax n)
8468 (n-no-remove -1)
8469 (idprop (org-entry-get nil "ID")))
8470 (when (and doshift
8471 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8472 template))
8473 (delete-region beg end)
8474 (setq end beg)
8475 (setq nmin 0)
8476 (setq nmax (1+ nmax))
8477 (setq n-no-remove nmax))
8478 (goto-char end)
8479 (cl-loop for n from nmin to nmax do
8480 (insert
8481 ;; Prepare clone.
8482 (with-temp-buffer
8483 (insert template)
8484 (org-mode)
8485 (goto-char (point-min))
8486 (org-show-subtree)
8487 (and idprop (if org-clone-delete-id
8488 (org-entry-delete nil "ID")
8489 (org-id-get-create t)))
8490 (unless (= n 0)
8491 (while (re-search-forward org-clock-line-re nil t)
8492 (delete-region (line-beginning-position)
8493 (line-beginning-position 2)))
8494 (goto-char (point-min))
8495 (while (re-search-forward org-drawer-regexp nil t)
8496 (org-remove-empty-drawer-at (point))))
8497 (goto-char (point-min))
8498 (when doshift
8499 (while (re-search-forward org-ts-regexp-both nil t)
8500 (org-timestamp-change (* n shift-n) shift-what))
8501 (unless (= n n-no-remove)
8502 (goto-char (point-min))
8503 (while (re-search-forward org-ts-regexp nil t)
8504 (save-excursion
8505 (goto-char (match-beginning 0))
8506 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8507 (delete-region (match-beginning 1) (match-end 1)))))))
8508 (buffer-string)))))
8509 (goto-char beg)))
8511 ;;; Outline Sorting
8513 (defun org-sort (&optional with-case)
8514 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8515 Optional argument WITH-CASE means sort case-sensitively."
8516 (interactive "P")
8517 (org-call-with-arg
8518 (cond ((org-at-table-p) #'org-table-sort-lines)
8519 ((org-at-item-p) #'org-sort-list)
8520 (t #'org-sort-entries))
8521 with-case))
8523 (defun org-sort-remove-invisible (s)
8524 "Remove invisible part of links and emphasis markers from string S."
8525 (remove-text-properties 0 (length s) org-rm-props s)
8526 (replace-regexp-in-string
8527 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8528 (replace-regexp-in-string
8529 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8530 (org-link-display-format s)
8531 t t) t t))
8533 (defvar org-priority-regexp) ; defined later in the file
8535 (defvar org-after-sorting-entries-or-items-hook nil
8536 "Hook that is run after a bunch of entries or items have been sorted.
8537 When children are sorted, the cursor is in the parent line when this
8538 hook gets called. When a region or a plain list is sorted, the cursor
8539 will be in the first entry of the sorted region/list.")
8541 (defun org-sort-entries
8542 (&optional with-case sorting-type getkey-func compare-func property
8543 interactive?)
8544 "Sort entries on a certain level of an outline tree.
8545 If there is an active region, the entries in the region are sorted.
8546 Else, if the cursor is before the first entry, sort the top-level items.
8547 Else, the children of the entry at point are sorted.
8549 Sorting can be alphabetically, numerically, by date/time as given by
8550 a time stamp, by a property, by priority order, or by a custom function.
8552 The command prompts for the sorting type unless it has been given to the
8553 function through the SORTING-TYPE argument, which needs to be a character,
8554 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8555 the precise meaning of each character:
8557 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8558 c By creation time, which is assumed to be the first inactive time stamp
8559 at the beginning of a line.
8560 d By deadline date/time.
8561 k By clocking time.
8562 n Numerically, by converting the beginning of the entry/item to a number.
8563 o By order of TODO keywords.
8564 p By priority according to the cookie.
8565 r By the value of a property.
8566 s By scheduled date/time.
8567 t By date/time, either the first active time stamp in the entry, or, if
8568 none exist, by the first inactive one.
8570 Capital letters will reverse the sort order.
8572 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8573 called with point at the beginning of the record. It must return a
8574 value that is compatible with COMPARE-FUNC, the function used to
8575 compare entries.
8577 Comparing entries ignores case by default. However, with an optional argument
8578 WITH-CASE, the sorting considers case as well.
8580 Sorting is done against the visible part of the headlines, it ignores hidden
8581 links.
8583 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8585 A non-nil value for INTERACTIVE? is used to signal that this
8586 function is being called interactively."
8587 (interactive (list current-prefix-arg nil nil nil nil t))
8588 (let ((case-func (if with-case 'identity 'downcase))
8589 start beg end stars re re2
8590 txt what tmp)
8591 ;; Find beginning and end of region to sort
8592 (cond
8593 ((org-region-active-p)
8594 ;; we will sort the region
8595 (setq end (region-end)
8596 what "region")
8597 (goto-char (region-beginning))
8598 (unless (org-at-heading-p) (outline-next-heading))
8599 (setq start (point)))
8600 ((or (org-at-heading-p)
8601 (ignore-errors (progn (org-back-to-heading) t)))
8602 ;; we will sort the children of the current headline
8603 (org-back-to-heading)
8604 (setq start (point)
8605 end (progn (org-end-of-subtree t t)
8606 (or (bolp) (insert "\n"))
8607 (when (>= (org-back-over-empty-lines) 1)
8608 (forward-line 1))
8609 (point))
8610 what "children")
8611 (goto-char start)
8612 (outline-show-subtree)
8613 (outline-next-heading))
8615 ;; we will sort the top-level entries in this file
8616 (goto-char (point-min))
8617 (or (org-at-heading-p) (outline-next-heading))
8618 (setq start (point))
8619 (goto-char (point-max))
8620 (beginning-of-line 1)
8621 (when (looking-at ".*?\\S-")
8622 ;; File ends in a non-white line
8623 (end-of-line 1)
8624 (insert "\n"))
8625 (setq end (point-max))
8626 (setq what "top-level")
8627 (goto-char start)
8628 (outline-show-all)))
8630 (setq beg (point))
8631 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8633 (looking-at "\\(\\*+\\)")
8634 (setq stars (match-string 1)
8635 re (concat "^" (regexp-quote stars) " +")
8636 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8637 txt (buffer-substring beg end))
8638 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8639 (when (and (not (equal stars "*")) (string-match re2 txt))
8640 (user-error "Region to sort contains a level above the first entry"))
8642 (unless sorting-type
8643 (message
8644 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8645 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8646 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8647 what)
8648 (setq sorting-type (read-char-exclusive)))
8650 (unless getkey-func
8651 (and (= (downcase sorting-type) ?f)
8652 (setq getkey-func
8653 (or (and interactive?
8654 (org-read-function
8655 "Function for extracting keys: "))
8656 (error "Missing key extractor")))))
8658 (and (= (downcase sorting-type) ?r)
8659 (not property)
8660 (setq property
8661 (completing-read "Property: "
8662 (mapcar #'list (org-buffer-property-keys t))
8663 nil t)))
8665 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8666 (message "Sorting entries...")
8668 (save-restriction
8669 (narrow-to-region start end)
8670 (let ((restore-clock?
8671 ;; The clock marker is lost when using `sort-subr'; mark
8672 ;; the clock with temporary `:org-clock-marker-backup'
8673 ;; text property.
8674 (when (and (eq (org-clock-is-active) (current-buffer))
8675 (<= start (marker-position org-clock-marker))
8676 (>= end (marker-position org-clock-marker)))
8677 (org-with-silent-modifications
8678 (put-text-property (1- org-clock-marker) org-clock-marker
8679 :org-clock-marker-backup t))
8681 (dcst (downcase sorting-type))
8682 (case-fold-search nil)
8683 (now (current-time)))
8684 (sort-subr
8685 (/= dcst sorting-type)
8686 ;; This function moves to the beginning character of the "record" to
8687 ;; be sorted.
8688 (lambda nil
8689 (if (re-search-forward re nil t)
8690 (goto-char (match-beginning 0))
8691 (goto-char (point-max))))
8692 ;; This function moves to the last character of the "record" being
8693 ;; sorted.
8694 (lambda nil
8695 (save-match-data
8696 (condition-case nil
8697 (outline-forward-same-level 1)
8698 (error
8699 (goto-char (point-max))))))
8700 ;; This function returns the value that gets sorted against.
8701 (lambda nil
8702 (cond
8703 ((= dcst ?n)
8704 (if (looking-at org-complex-heading-regexp)
8705 (string-to-number (org-sort-remove-invisible (match-string 4)))
8706 nil))
8707 ((= dcst ?a)
8708 (if (looking-at org-complex-heading-regexp)
8709 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8710 nil))
8711 ((= dcst ?k)
8712 (or (get-text-property (point) :org-clock-minutes) 0))
8713 ((= dcst ?t)
8714 (let ((end (save-excursion (outline-next-heading) (point))))
8715 (if (or (re-search-forward org-ts-regexp end t)
8716 (re-search-forward org-ts-regexp-both end t))
8717 (org-time-string-to-seconds (match-string 0))
8718 (float-time now))))
8719 ((= dcst ?c)
8720 (let ((end (save-excursion (outline-next-heading) (point))))
8721 (if (re-search-forward
8722 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8723 end t)
8724 (org-time-string-to-seconds (match-string 0))
8725 (float-time now))))
8726 ((= dcst ?s)
8727 (let ((end (save-excursion (outline-next-heading) (point))))
8728 (if (re-search-forward org-scheduled-time-regexp end t)
8729 (org-time-string-to-seconds (match-string 1))
8730 (float-time now))))
8731 ((= dcst ?d)
8732 (let ((end (save-excursion (outline-next-heading) (point))))
8733 (if (re-search-forward org-deadline-time-regexp end t)
8734 (org-time-string-to-seconds (match-string 1))
8735 (float-time now))))
8736 ((= dcst ?p)
8737 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8738 (string-to-char (match-string 2))
8739 org-default-priority))
8740 ((= dcst ?r)
8741 (or (org-entry-get nil property) ""))
8742 ((= dcst ?o)
8743 (when (looking-at org-complex-heading-regexp)
8744 (let* ((m (match-string 2))
8745 (s (if (member m org-done-keywords) '- '+)))
8746 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8747 ((= dcst ?f)
8748 (if getkey-func
8749 (progn
8750 (setq tmp (funcall getkey-func))
8751 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8752 tmp)
8753 (error "Invalid key function `%s'" getkey-func)))
8754 (t (error "Invalid sorting type `%c'" sorting-type))))
8756 (cond
8757 ((= dcst ?a) 'string<)
8758 ((= dcst ?f)
8759 (or compare-func
8760 (and interactive?
8761 (org-read-function
8762 (concat "Function for comparing keys "
8763 "(empty for default `sort-subr' predicate): ")
8764 'allow-empty))))
8765 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
8766 (when restore-clock?
8767 (move-marker org-clock-marker
8768 (1+ (next-single-property-change
8769 start :org-clock-marker-backup)))
8770 (remove-text-properties (1- org-clock-marker) org-clock-marker
8771 '(:org-clock-marker-backup t)))))
8772 (run-hooks 'org-after-sorting-entries-or-items-hook)
8773 (message "Sorting entries...done")))
8775 ;;; The orgstruct minor mode
8777 ;; Define a minor mode which can be used in other modes in order to
8778 ;; integrate the Org mode structure editing commands.
8780 ;; This is really a hack, because the Org mode structure commands use
8781 ;; keys which normally belong to the major mode. Here is how it
8782 ;; works: The minor mode defines all the keys necessary to operate the
8783 ;; structure commands, but wraps the commands into a function which
8784 ;; tests if the cursor is currently at a headline or a plain list
8785 ;; item. If that is the case, the structure command is used,
8786 ;; temporarily setting many Org mode variables like regular
8787 ;; expressions for filling etc. However, when any of those keys is
8788 ;; used at a different location, function uses `key-binding' to look
8789 ;; up if the key has an associated command in another currently active
8790 ;; keymap (minor modes, major mode, global), and executes that
8791 ;; command. There might be problems if any of the keys is otherwise
8792 ;; used as a prefix key.
8794 (defcustom orgstruct-heading-prefix-regexp ""
8795 "Regexp that matches the custom prefix of Org headlines in
8796 orgstruct(++)-mode."
8797 :group 'org
8798 :version "26.1"
8799 :package-version '(Org . "8.3")
8800 :type 'regexp)
8801 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8803 (defcustom orgstruct-setup-hook nil
8804 "Hook run after orgstruct-mode-map is filled."
8805 :group 'org
8806 :version "24.4"
8807 :package-version '(Org . "8.0")
8808 :type 'hook)
8810 (defvar orgstruct-initialized nil)
8812 (defvar org-local-vars nil
8813 "List of local variables, for use by `orgstruct-mode'.")
8815 ;;;###autoload
8816 (define-minor-mode orgstruct-mode
8817 "Toggle the minor mode `orgstruct-mode'.
8818 This mode is for using Org mode structure commands in other
8819 modes. The following keys behave as if Org mode were active, if
8820 the cursor is on a headline, or on a plain list item (both as
8821 defined by Org mode)."
8822 nil " OrgStruct" (make-sparse-keymap)
8823 (funcall (if orgstruct-mode
8824 'add-to-invisibility-spec
8825 'remove-from-invisibility-spec)
8826 '(outline . t))
8827 (when orgstruct-mode
8828 (org-load-modules-maybe)
8829 (unless orgstruct-initialized
8830 (orgstruct-setup)
8831 (setq orgstruct-initialized t))))
8833 ;;;###autoload
8834 (defun turn-on-orgstruct ()
8835 "Unconditionally turn on `orgstruct-mode'."
8836 (orgstruct-mode 1))
8838 (defvar-local orgstruct-is-++ nil
8839 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8840 (defvar-local org-fb-vars nil)
8841 (defun orgstruct++-mode (&optional arg)
8842 "Toggle `orgstruct-mode', the enhanced version of it.
8843 In addition to setting orgstruct-mode, this also exports all
8844 indentation and autofilling variables from Org mode into the
8845 buffer. It will also recognize item context in multiline items."
8846 (interactive "P")
8847 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8848 (if (< arg 1)
8849 (progn (orgstruct-mode -1)
8850 (dolist (v org-fb-vars)
8851 (set (make-local-variable (car v))
8852 (if (eq (car-safe (cadr v)) 'quote)
8853 (cl-cadadr v)
8854 (nth 1 v)))))
8855 (orgstruct-mode 1)
8856 (setq org-fb-vars nil)
8857 (unless org-local-vars
8858 (setq org-local-vars (org-get-local-variables)))
8859 (let (var val)
8860 (dolist (x org-local-vars)
8861 (when (string-match
8862 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8863 \\|fill-prefix\\|indent-\\)"
8864 (symbol-name (car x)))
8865 (setq var (car x) val (nth 1 x))
8866 (push (list var `(quote ,(eval var))) org-fb-vars)
8867 (set (make-local-variable var)
8868 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8869 (setq-local orgstruct-is-++ t))))
8871 ;;;###autoload
8872 (defun turn-on-orgstruct++ ()
8873 "Unconditionally turn on `orgstruct++-mode'."
8874 (orgstruct++-mode 1))
8876 (defun orgstruct-error ()
8877 "Error when there is no default binding for a structure key."
8878 (interactive)
8879 (funcall (if (fboundp 'user-error)
8880 'user-error
8881 'error)
8882 "This key has no function outside structure elements"))
8884 (defun orgstruct-setup ()
8885 "Setup orgstruct keymap."
8886 (dolist (cell '((org-demote . t)
8887 (org-metaleft . t)
8888 (org-metaright . t)
8889 (org-promote . t)
8890 (org-shiftmetaleft . t)
8891 (org-shiftmetaright . t)
8892 org-backward-element
8893 org-backward-heading-same-level
8894 org-ctrl-c-ret
8895 org-ctrl-c-minus
8896 org-ctrl-c-star
8897 org-cycle
8898 org-force-cycle-archived
8899 org-forward-heading-same-level
8900 org-insert-heading
8901 org-insert-heading-respect-content
8902 org-kill-note-or-show-branches
8903 org-mark-subtree
8904 org-meta-return
8905 org-metadown
8906 org-metaup
8907 org-narrow-to-subtree
8908 org-promote-subtree
8909 org-reveal
8910 org-shiftdown
8911 org-shiftleft
8912 org-shiftmetadown
8913 org-shiftmetaup
8914 org-shiftright
8915 org-shifttab
8916 org-shifttab
8917 org-shiftup
8918 org-show-children
8919 org-show-subtree
8920 org-sort
8921 org-up-element
8922 outline-demote
8923 outline-next-visible-heading
8924 outline-previous-visible-heading
8925 outline-promote
8926 outline-up-heading))
8927 (let ((f (or (car-safe cell) cell))
8928 (disable-when-heading-prefix (cdr-safe cell)))
8929 (when (fboundp f)
8930 (let ((new-bindings))
8931 (dolist (binding (nconc (where-is-internal f org-mode-map)
8932 (where-is-internal f outline-mode-map)))
8933 (push binding new-bindings)
8934 ;; TODO use local-function-key-map
8935 (dolist (rep '(("<tab>" . "TAB")
8936 ("<return>" . "RET")
8937 ("<escape>" . "ESC")
8938 ("<delete>" . "DEL")))
8939 (setq binding (read-kbd-macro
8940 (let ((case-fold-search))
8941 (replace-regexp-in-string
8942 (regexp-quote (cdr rep))
8943 (car rep)
8944 (key-description binding)))))
8945 (cl-pushnew binding new-bindings :test 'equal)))
8946 (dolist (binding new-bindings)
8947 (let ((key (lookup-key orgstruct-mode-map binding)))
8948 (when (or (not key) (numberp key))
8949 (ignore-errors
8950 (org-defkey orgstruct-mode-map
8951 binding
8952 (orgstruct-make-binding
8953 f binding disable-when-heading-prefix))))))))))
8954 (run-hooks 'orgstruct-setup-hook))
8956 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8957 "Create a function for binding in the structure minor mode.
8958 FUN is the command to call inside a table. KEY is the key that
8959 should be checked in for a command to execute outside of tables.
8960 Non-nil `disable-when-heading-prefix' means to disable the command
8961 if `orgstruct-heading-prefix-regexp' is not empty."
8962 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8963 (let ((nname name)
8964 (i 0))
8965 (while (fboundp (intern nname))
8966 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8967 (setq name (intern nname)))
8968 (eval
8969 (let ((bindings '((org-heading-regexp
8970 (concat "^"
8971 orgstruct-heading-prefix-regexp
8972 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8973 (org-outline-regexp
8974 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8975 (org-outline-regexp-bol
8976 (concat "^" org-outline-regexp))
8977 (outline-regexp org-outline-regexp)
8978 (outline-heading-end-regexp "\n")
8979 (outline-level 'org-outline-level)
8980 (outline-heading-alist))))
8981 `(defun ,name (arg)
8982 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8983 "Outside of structure, run the binding of `"
8984 (key-description key) "'."
8985 (when disable-when-heading-prefix
8986 (concat
8987 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
8988 "back to the default binding due to limitations of Org's implementation of\n"
8989 "`" (symbol-name fun) "'.")))
8990 (interactive "p")
8991 (let* ((disable
8992 ,(and disable-when-heading-prefix
8993 '(not (string= orgstruct-heading-prefix-regexp ""))))
8994 (fallback
8995 (or disable
8996 (not
8997 (let* ,bindings
8998 (org-context-p 'headline 'item
8999 ,(when (memq fun
9000 '(org-insert-heading
9001 org-insert-heading-respect-content
9002 org-meta-return))
9003 '(when orgstruct-is-++
9004 'item-body))))))))
9005 (if fallback
9006 (let* ((orgstruct-mode)
9007 (binding
9008 (let ((key ,key))
9009 (catch 'exit
9010 (dolist
9011 (rep
9012 '(nil
9013 ("<\\([^>]*\\)tab>" . "\\1TAB")
9014 ("<\\([^>]*\\)return>" . "\\1RET")
9015 ("<\\([^>]*\\)escape>" . "\\1ESC")
9016 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9017 nil)
9018 (when rep
9019 (setq key (read-kbd-macro
9020 (let ((case-fold-search))
9021 (replace-regexp-in-string
9022 (car rep)
9023 (cdr rep)
9024 (key-description key))))))
9025 (when (key-binding key)
9026 (throw 'exit (key-binding key))))))))
9027 (if (keymapp binding)
9028 (org-set-transient-map binding)
9029 (let ((func (or binding
9030 (unless disable
9031 'orgstruct-error))))
9032 (when func
9033 (call-interactively func)))))
9034 (org-run-like-in-org-mode
9035 (lambda ()
9036 (interactive)
9037 (let* ,bindings
9038 (call-interactively ',fun)))))))))
9039 name))
9041 (defun org-contextualize-keys (alist contexts)
9042 "Return valid elements in ALIST depending on CONTEXTS.
9044 `org-agenda-custom-commands' or `org-capture-templates' are the
9045 values used for ALIST, and `org-agenda-custom-commands-contexts'
9046 or `org-capture-templates-contexts' are the associated contexts
9047 definitions."
9048 (let ((contexts
9049 ;; normalize contexts
9050 (mapcar
9051 (lambda(c) (cond ((listp (cadr c))
9052 (list (car c) (car c) (nth 1 c)))
9053 ((string= "" (cadr c))
9054 (list (car c) (car c) (nth 2 c)))
9055 (t c)))
9056 contexts))
9057 (a alist) r s)
9058 ;; loop over all commands or templates
9059 (dolist (c a)
9060 (let (vrules repl)
9061 (cond
9062 ((not (assoc (car c) contexts))
9063 (push c r))
9064 ((and (assoc (car c) contexts)
9065 (setq vrules (org-contextualize-validate-key
9066 (car c) contexts)))
9067 (mapc (lambda (vr)
9068 (unless (equal (car vr) (cadr vr))
9069 (setq repl vr)))
9070 vrules)
9071 (if (not repl) (push c r)
9072 (push (cadr repl) s)
9073 (push
9074 (cons (car c)
9075 (cdr (or (assoc (cadr repl) alist)
9076 (error "Undefined key `%s' as contextual replacement for `%s'"
9077 (cadr repl) (car c)))))
9078 r))))))
9079 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9080 (delq
9082 (delete-dups
9083 (mapcar (lambda (x)
9084 (let ((tpl (car x)))
9085 (unless (delq
9087 (mapcar (lambda (y)
9088 (equal y tpl))
9090 x)))
9091 (reverse r))))))
9093 (defun org-contextualize-validate-key (key contexts)
9094 "Check CONTEXTS for agenda or capture KEY."
9095 (let (res)
9096 (dolist (r contexts)
9097 (dolist (rr (car (last r)))
9098 (when
9099 (and (equal key (car r))
9100 (if (functionp rr) (funcall rr)
9101 (or (and (eq (car rr) 'in-file)
9102 (buffer-file-name)
9103 (string-match (cdr rr) (buffer-file-name)))
9104 (and (eq (car rr) 'in-mode)
9105 (string-match (cdr rr) (symbol-name major-mode)))
9106 (and (eq (car rr) 'in-buffer)
9107 (string-match (cdr rr) (buffer-name)))
9108 (when (and (eq (car rr) 'not-in-file)
9109 (buffer-file-name))
9110 (not (string-match (cdr rr) (buffer-file-name))))
9111 (when (eq (car rr) 'not-in-mode)
9112 (not (string-match (cdr rr) (symbol-name major-mode))))
9113 (when (eq (car rr) 'not-in-buffer)
9114 (not (string-match (cdr rr) (buffer-name)))))))
9115 (push r res))))
9116 (delete-dups (delq nil res))))
9118 (defun org-context-p (&rest contexts)
9119 "Check if local context is any of CONTEXTS.
9120 Possible values in the list of contexts are `table', `headline', and `item'."
9121 (let ((pos (point)))
9122 (goto-char (point-at-bol))
9123 (prog1 (or (and (memq 'table contexts)
9124 (looking-at "[ \t]*|"))
9125 (and (memq 'headline contexts)
9126 (looking-at org-outline-regexp))
9127 (and (memq 'item contexts)
9128 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9129 (and (memq 'item-body contexts)
9130 (org-in-item-p)))
9131 (goto-char pos))))
9133 ;;;###autoload
9134 (defun org-run-like-in-org-mode (cmd)
9135 "Run a command, pretending that the current buffer is in Org mode.
9136 This will temporarily bind local variables that are typically bound in
9137 Org mode to the values they have in Org mode, and then interactively
9138 call CMD."
9139 (org-load-modules-maybe)
9140 (unless org-local-vars
9141 (setq org-local-vars (org-get-local-variables)))
9142 (let (binds)
9143 (dolist (var org-local-vars)
9144 (when (or (not (boundp (car var)))
9145 (eq (symbol-value (car var))
9146 (default-value (car var))))
9147 (push (list (car var) `(quote ,(cadr var))) binds)))
9148 (eval `(let ,binds
9149 (call-interactively (quote ,cmd))))))
9151 (defun org-get-category (&optional pos force-refresh)
9152 "Get the category applying to position POS."
9153 (save-match-data
9154 (when force-refresh (org-refresh-category-properties))
9155 (let ((pos (or pos (point))))
9156 (or (get-text-property pos 'org-category)
9157 (progn (org-refresh-category-properties)
9158 (get-text-property pos 'org-category))))))
9160 ;;; Refresh properties
9162 (defun org-refresh-properties (dprop tprop)
9163 "Refresh buffer text properties.
9164 DPROP is the drawer property and TPROP is either the
9165 corresponding text property to set, or an alist with each element
9166 being a text property (as a symbol) and a function to apply to
9167 the value of the drawer property."
9168 (let* ((case-fold-search t)
9169 (inhibit-read-only t)
9170 (inherit? (org-property-inherit-p dprop))
9171 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9172 (global (and inherit? (org--property-global-value dprop nil))))
9173 (org-with-silent-modifications
9174 (org-with-point-at 1
9175 ;; Set global values (e.g., values defined through
9176 ;; "#+PROPERTY:" keywords) to the whole buffer.
9177 (when global (put-text-property (point-min) (point-max) tprop global))
9178 ;; Set local values.
9179 (while (re-search-forward property-re nil t)
9180 (when (org-at-property-p)
9181 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9182 (outline-next-heading))))))
9184 (defun org-refresh-property (tprop p &optional inherit)
9185 "Refresh the buffer text property TPROP from the drawer property P.
9186 The refresh happens only for the current headline, or the whole
9187 sub-tree if optional argument INHERIT is non-nil."
9188 (unless (org-before-first-heading-p)
9189 (save-excursion
9190 (org-back-to-heading t)
9191 (let ((start (point))
9192 (end (save-excursion
9193 (if inherit (org-end-of-subtree t t)
9194 (or (outline-next-heading) (point-max))))))
9195 (if (symbolp tprop)
9196 ;; TPROP is a text property symbol.
9197 (put-text-property start end tprop p)
9198 ;; TPROP is an alist with (property . function) elements.
9199 (pcase-dolist (`(,prop . ,f) tprop)
9200 (put-text-property start end prop (funcall f p))))))))
9202 (defun org-refresh-category-properties ()
9203 "Refresh category text properties in the buffer."
9204 (let ((case-fold-search t)
9205 (inhibit-read-only t)
9206 (default-category
9207 (cond ((null org-category)
9208 (if buffer-file-name
9209 (file-name-sans-extension
9210 (file-name-nondirectory buffer-file-name))
9211 "???"))
9212 ((symbolp org-category) (symbol-name org-category))
9213 (t org-category))))
9214 (org-with-silent-modifications
9215 (org-with-wide-buffer
9216 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9217 ;; This is the default category for the buffer. If none is
9218 ;; found, fall-back to `org-category' or buffer file name.
9219 (put-text-property
9220 (point-min) (point-max)
9221 'org-category
9222 (catch 'buffer-category
9223 (goto-char (point-max))
9224 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9225 (let ((element (org-element-at-point)))
9226 (when (eq (org-element-type element) 'keyword)
9227 (throw 'buffer-category
9228 (org-element-property :value element)))))
9229 default-category))
9230 ;; Set sub-tree specific categories.
9231 (goto-char (point-min))
9232 (let ((regexp (org-re-property "CATEGORY")))
9233 (while (re-search-forward regexp nil t)
9234 (let ((value (match-string-no-properties 3)))
9235 (when (org-at-property-p)
9236 (put-text-property
9237 (save-excursion (org-back-to-heading t) (point))
9238 (save-excursion (org-end-of-subtree t t) (point))
9239 'org-category
9240 value)))))))))
9242 (defun org-refresh-stats-properties ()
9243 "Refresh stats text properties in the buffer."
9244 (org-with-silent-modifications
9245 (org-with-point-at 1
9246 (let ((regexp (concat org-outline-regexp-bol
9247 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9248 (while (re-search-forward regexp nil t)
9249 (let* ((numerator (string-to-number (match-string 1)))
9250 (denominator (and (match-end 2)
9251 (string-to-number (match-string 2))))
9252 (stats (cond ((not denominator) numerator) ;percent
9253 ((= denominator 0) 0)
9254 (t (/ (* numerator 100) denominator)))))
9255 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9256 'org-stats stats)))))))
9258 (defun org-refresh-effort-properties ()
9259 "Refresh effort properties"
9260 (org-refresh-properties
9261 org-effort-property
9262 '((effort . identity)
9263 (effort-minutes . org-duration-to-minutes))))
9265 ;;;; Link Stuff
9267 ;;; Link abbreviations
9269 (defun org-link-expand-abbrev (link)
9270 "Apply replacements as defined in `org-link-abbrev-alist'."
9271 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9272 (let* ((key (match-string 1 link))
9273 (as (or (assoc key org-link-abbrev-alist-local)
9274 (assoc key org-link-abbrev-alist)))
9275 (tag (and (match-end 2) (match-string 3 link)))
9276 rpl)
9277 (if (not as)
9278 link
9279 (setq rpl (cdr as))
9280 (cond
9281 ((symbolp rpl) (funcall rpl tag))
9282 ((string-match "%(\\([^)]+\\))" rpl)
9283 (replace-match
9284 (save-match-data
9285 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9286 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9287 ((string-match "%h" rpl)
9288 (replace-match (url-hexify-string (or tag "")) t t rpl))
9289 (t (concat rpl tag)))))
9290 link))
9292 ;;; Storing and inserting links
9294 (defvar org-insert-link-history nil
9295 "Minibuffer history for links inserted with `org-insert-link'.")
9297 (defvar org-stored-links nil
9298 "Contains the links stored with `org-store-link'.")
9300 (defvar org-store-link-plist nil
9301 "Plist with info about the most recently link created with `org-store-link'.")
9303 (defun org-store-link-functions ()
9304 "Return a list of functions that are called to create and store a link.
9305 The functions defined in the :store property of
9306 `org-link-parameters'.
9308 Each function will be called in turn until one returns a non-nil
9309 value. Each function should check if it is responsible for
9310 creating this link (for example by looking at the major mode).
9311 If not, it must exit and return nil. If yes, it should return
9312 a non-nil value after calling `org-store-link-props' with a list
9313 of properties and values. Special properties are:
9315 :type The link prefix, like \"http\". This must be given.
9316 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9317 This is obligatory as well.
9318 :description Optional default description for the second pair
9319 of brackets in an Org mode link. The user can still change
9320 this when inserting this link into an Org mode buffer.
9322 In addition to these, any additional properties can be specified
9323 and then used in capture templates."
9324 (cl-loop for link in org-link-parameters
9325 with store-func
9326 do (setq store-func (org-link-get-parameter (car link) :store))
9327 if store-func
9328 collect store-func))
9330 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9331 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9333 ;;;###autoload
9334 (defun org-store-link (arg)
9335 "Store an org-link to the current location.
9336 \\<org-mode-map>
9337 This link is added to `org-stored-links' and can later be inserted
9338 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9340 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9341 A single
9342 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9343 `org-gnus-prefer-web-links' for links to Usenet articles.
9345 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9346 skipping storing functions that are not
9347 part of Org core.
9349 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9350 prefix ARG forces storing a link for each line in the
9351 active region."
9352 (interactive "P")
9353 (org-load-modules-maybe)
9354 (if (and (equal arg '(64)) (org-region-active-p))
9355 (save-excursion
9356 (let ((end (region-end)))
9357 (goto-char (region-beginning))
9358 (set-mark (point))
9359 (while (< (point-at-eol) end)
9360 (move-end-of-line 1) (activate-mark)
9361 (let (current-prefix-arg)
9362 (call-interactively 'org-store-link))
9363 (move-beginning-of-line 2)
9364 (set-mark (point)))))
9365 (setq org-store-link-plist nil)
9366 (let (link cpltxt desc description search
9367 txt custom-id agenda-link sfuns sfunsn)
9368 (cond
9370 ;; Store a link using an external link type
9371 ((and (not (equal arg '(16)))
9372 (setq sfuns
9373 (delq
9374 nil (mapcar (lambda (f)
9375 (let (fs) (if (funcall f) (push f fs))))
9376 (org-store-link-functions)))
9377 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9378 (or (and (cdr sfuns)
9379 (funcall (intern
9380 (completing-read
9381 "Which function for creating the link? "
9382 sfunsn nil t (car sfunsn)))))
9383 (funcall (caar sfuns)))
9384 (setq link (plist-get org-store-link-plist :link)
9385 desc (or (plist-get org-store-link-plist
9386 :description)
9387 link))))
9389 ;; Store a link from a source code buffer.
9390 ((org-src-edit-buffer-p)
9391 (let ((coderef-format (org-src-coderef-format)))
9392 (cond ((save-excursion
9393 (beginning-of-line)
9394 (looking-at (org-src-coderef-regexp coderef-format)))
9395 (setq link (format "(%s)" (match-string-no-properties 3))))
9396 ((called-interactively-p 'any)
9397 (let ((label (read-string "Code line label: ")))
9398 (end-of-line)
9399 (setq link (format coderef-format label))
9400 (let ((gc (- 79 (length link))))
9401 (if (< (current-column) gc)
9402 (org-move-to-column gc t)
9403 (insert " ")))
9404 (insert link)
9405 (setq link (concat "(" label ")"))
9406 (setq desc nil)))
9407 (t (setq link nil)))))
9409 ;; We are in the agenda, link to referenced location
9410 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9411 (let ((m (or (get-text-property (point) 'org-hd-marker)
9412 (get-text-property (point) 'org-marker))))
9413 (when m
9414 (org-with-point-at m
9415 (setq agenda-link
9416 (if (called-interactively-p 'any)
9417 (call-interactively 'org-store-link)
9418 (org-store-link nil)))))))
9420 ((eq major-mode 'calendar-mode)
9421 (let ((cd (calendar-cursor-to-date)))
9422 (setq link
9423 (format-time-string
9424 (car org-time-stamp-formats)
9425 (apply 'encode-time
9426 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9427 nil nil nil))))
9428 (org-store-link-props :type "calendar" :date cd)))
9430 ((eq major-mode 'help-mode)
9431 (setq link (concat "help:" (save-excursion
9432 (goto-char (point-min))
9433 (looking-at "^[^ ]+")
9434 (match-string 0))))
9435 (org-store-link-props :type "help"))
9437 ((eq major-mode 'w3-mode)
9438 (setq cpltxt (if (and (buffer-name)
9439 (not (string-match "Untitled" (buffer-name))))
9440 (buffer-name)
9441 (url-view-url t))
9442 link (url-view-url t))
9443 (org-store-link-props :type "w3" :url (url-view-url t)))
9445 ((eq major-mode 'image-mode)
9446 (setq cpltxt (concat "file:"
9447 (abbreviate-file-name buffer-file-name))
9448 link cpltxt)
9449 (org-store-link-props :type "image" :file buffer-file-name))
9451 ;; In dired, store a link to the file of the current line
9452 ((derived-mode-p 'dired-mode)
9453 (let ((file (dired-get-filename nil t)))
9454 (setq file (if file
9455 (abbreviate-file-name
9456 (expand-file-name (dired-get-filename nil t)))
9457 ;; otherwise, no file so use current directory.
9458 default-directory))
9459 (setq cpltxt (concat "file:" file)
9460 link cpltxt)))
9462 ((setq search (run-hook-with-args-until-success
9463 'org-create-file-search-functions))
9464 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9465 "::" search))
9466 (setq cpltxt (or description link)))
9468 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9469 (org-with-limited-levels
9470 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9471 (cond
9472 ;; Store a link using the target at point
9473 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9474 (setq cpltxt
9475 (concat "file:"
9476 (abbreviate-file-name
9477 (buffer-file-name (buffer-base-buffer)))
9478 "::" (match-string 1))
9479 link cpltxt))
9480 ((and (featurep 'org-id)
9481 (or (eq org-id-link-to-org-use-id t)
9482 (and (called-interactively-p 'any)
9483 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9484 (and (eq org-id-link-to-org-use-id
9485 'create-if-interactive-and-no-custom-id)
9486 (not custom-id))))
9487 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9488 ;; Store a link using the ID at point
9489 (setq link (condition-case nil
9490 (prog1 (org-id-store-link)
9491 (setq desc (or (plist-get org-store-link-plist
9492 :description)
9493 "")))
9494 (error
9495 ;; Probably before first headline, link only to file
9496 (concat "file:"
9497 (abbreviate-file-name
9498 (buffer-file-name (buffer-base-buffer))))))))
9500 ;; Just link to current headline
9501 (setq cpltxt (concat "file:"
9502 (abbreviate-file-name
9503 (buffer-file-name (buffer-base-buffer)))))
9504 ;; Add a context search string
9505 (when (org-xor org-context-in-file-links
9506 (equal arg '(4)))
9507 (let* ((element (org-element-at-point))
9508 (name (org-element-property :name element)))
9509 (setq txt (cond
9510 ((org-at-heading-p) nil)
9511 (name)
9512 ((org-region-active-p)
9513 (buffer-substring (region-beginning) (region-end)))))
9514 (when (or (null txt) (string-match "\\S-" txt))
9515 (setq cpltxt
9516 (concat cpltxt "::"
9517 (condition-case nil
9518 (org-make-org-heading-search-string txt)
9519 (error "")))
9520 desc (or name
9521 (nth 4 (ignore-errors (org-heading-components)))
9522 "NONE")))))
9523 (when (string-match "::\\'" cpltxt)
9524 (setq cpltxt (substring cpltxt 0 -2)))
9525 (setq link cpltxt)))))
9527 ((buffer-file-name (buffer-base-buffer))
9528 ;; Just link to this file here.
9529 (setq cpltxt (concat "file:"
9530 (abbreviate-file-name
9531 (buffer-file-name (buffer-base-buffer)))))
9532 ;; Add a context string.
9533 (when (org-xor org-context-in-file-links
9534 (equal arg '(4)))
9535 (setq txt (if (org-region-active-p)
9536 (buffer-substring (region-beginning) (region-end))
9537 (buffer-substring (point-at-bol) (point-at-eol))))
9538 ;; Only use search option if there is some text.
9539 (when (string-match "\\S-" txt)
9540 (setq cpltxt
9541 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9542 desc "NONE")))
9543 (setq link cpltxt))
9545 ((called-interactively-p 'interactive)
9546 (user-error "No method for storing a link from this buffer"))
9548 (t (setq link nil)))
9550 ;; We're done setting link and desc, clean up
9551 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9552 (setq link (or link cpltxt)
9553 desc (or desc cpltxt))
9554 (cond ((not desc))
9555 ((equal desc "NONE") (setq desc nil))
9556 (t (setq desc
9557 (replace-regexp-in-string
9558 org-bracket-link-analytic-regexp
9559 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9560 desc))))
9561 ;; Return the link
9562 (if (not (and (or (called-interactively-p 'any)
9563 executing-kbd-macro)
9564 link))
9565 (or agenda-link (and link (org-make-link-string link desc)))
9566 (push (list link desc) org-stored-links)
9567 (message "Stored: %s" (or desc link))
9568 (when custom-id
9569 (setq link (concat "file:" (abbreviate-file-name
9570 (buffer-file-name)) "::#" custom-id))
9571 (push (list link desc) org-stored-links))
9572 (car org-stored-links)))))
9574 (defun org-store-link-props (&rest plist)
9575 "Store link properties.
9576 The properties are pre-processed by extracting names, addresses
9577 and dates."
9578 (let ((x (plist-get plist :from)))
9579 (when x
9580 (let ((adr (mail-extract-address-components x)))
9581 (setq plist (plist-put plist :fromname (car adr)))
9582 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9583 (let ((x (plist-get plist :to)))
9584 (when x
9585 (let ((adr (mail-extract-address-components x)))
9586 (setq plist (plist-put plist :toname (car adr)))
9587 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9588 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9589 (when x
9590 (setq plist (plist-put plist :date-timestamp
9591 (format-time-string
9592 (org-time-stamp-format t) x)))
9593 (setq plist (plist-put plist :date-timestamp-inactive
9594 (format-time-string
9595 (org-time-stamp-format t t) x)))))
9596 (let ((from (plist-get plist :from))
9597 (to (plist-get plist :to)))
9598 (when (and from to org-from-is-user-regexp)
9599 (setq plist
9600 (plist-put plist :fromto
9601 (if (string-match org-from-is-user-regexp from)
9602 (concat "to %t")
9603 (concat "from %f"))))))
9604 (setq org-store-link-plist plist))
9606 (defun org-add-link-props (&rest plist)
9607 "Add these properties to the link property list."
9608 (let (key value)
9609 (while plist
9610 (setq key (pop plist) value (pop plist))
9611 (setq org-store-link-plist
9612 (plist-put org-store-link-plist key value)))))
9614 (defun org-email-link-description (&optional fmt)
9615 "Return the description part of an email link.
9616 This takes information from `org-store-link-plist' and formats it
9617 according to FMT (default from `org-email-link-description-format')."
9618 (setq fmt (or fmt org-email-link-description-format))
9619 (let* ((p org-store-link-plist)
9620 (to (plist-get p :toaddress))
9621 (from (plist-get p :fromaddress))
9622 (table
9623 (list
9624 (cons "%c" (plist-get p :fromto))
9625 (cons "%F" (plist-get p :from))
9626 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9627 (cons "%T" (plist-get p :to))
9628 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9629 (cons "%s" (plist-get p :subject))
9630 (cons "%d" (plist-get p :date))
9631 (cons "%m" (plist-get p :message-id)))))
9632 (when (string-match "%c" fmt)
9633 ;; Check if the user wrote this message
9634 (if (and org-from-is-user-regexp from to
9635 (save-match-data (string-match org-from-is-user-regexp from)))
9636 (setq fmt (replace-match "to %t" t t fmt))
9637 (setq fmt (replace-match "from %f" t t fmt))))
9638 (org-replace-escapes fmt table)))
9640 (defun org-make-org-heading-search-string (&optional string)
9641 "Make search string for the current headline or STRING."
9642 (let ((s (or string
9643 (and (derived-mode-p 'org-mode)
9644 (save-excursion
9645 (org-back-to-heading t)
9646 (org-element-property :raw-value (org-element-at-point))))))
9647 (lines org-context-in-file-links))
9648 (unless string (setq s (concat "*" s))) ;Add * for headlines
9649 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9650 (when (and string (integerp lines) (> lines 0))
9651 (let ((slines (org-split-string s "\n")))
9652 (when (< lines (length slines))
9653 (setq s (mapconcat
9654 'identity
9655 (reverse (nthcdr (- (length slines) lines)
9656 (reverse slines))) "\n")))))
9657 (mapconcat #'identity (split-string s) " ")))
9659 (defun org-make-link-string (link &optional description)
9660 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9661 (unless (org-string-nw-p link) (error "Empty link"))
9662 (let ((uri (cond ((string-match org-link-types-re link)
9663 (concat (match-string 1 link)
9664 (org-link-escape (substring link (match-end 1)))))
9665 ;; For readability, url-encode internal links only
9666 ;; when absolutely needed (i.e, when they contain
9667 ;; square brackets). File links however, are
9668 ;; encoded since, e.g., spaces are significant.
9669 ((or (file-name-absolute-p link)
9670 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9671 (org-link-escape link))
9672 (t link)))
9673 (description
9674 (and (org-string-nw-p description)
9675 ;; Remove brackets from description, as they are fatal.
9676 (replace-regexp-in-string
9677 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9678 (org-trim description)))))
9679 (format "[[%s]%s]"
9681 (if description (format "[%s]" description) ""))))
9683 (defconst org-link-escape-chars
9684 ;;%20 %5B %5D %25
9685 '(?\s ?\[ ?\] ?%)
9686 "List of characters that should be escaped in a link when stored to Org.
9687 This is the list that is used for internal purposes.")
9689 (defun org-link-escape (text &optional table merge)
9690 "Return percent escaped representation of TEXT.
9691 TEXT is a string with the text to escape.
9692 Optional argument TABLE is a list with characters that should be
9693 escaped. When nil, `org-link-escape-chars' is used.
9694 If optional argument MERGE is set, merge TABLE into
9695 `org-link-escape-chars'."
9696 (let ((characters-to-encode
9697 (cond ((null table) org-link-escape-chars)
9698 (merge (append org-link-escape-chars table))
9699 (t table))))
9700 (mapconcat
9701 (lambda (c)
9702 (if (or (memq c characters-to-encode)
9703 (and org-url-hexify-p (or (< c 32) (> c 126))))
9704 (mapconcat (lambda (e) (format "%%%.2X" e))
9705 (or (encode-coding-char c 'utf-8)
9706 (error "Unable to percent escape character: %c" c))
9708 (char-to-string c)))
9709 text "")))
9711 (defun org-link-unescape (str)
9712 "Unhex hexified Unicode parts in string STR.
9713 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9714 reciprocal of `org-link-escape', which see."
9715 (if (org-string-nw-p str)
9716 (replace-regexp-in-string
9717 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9718 str))
9720 (defun org-link-unescape-compound (hex)
9721 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9722 Note: this function also decodes single byte encodings like
9723 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9724 (save-match-data
9725 (let* ((bytes (cdr (split-string hex "%")))
9726 (ret "")
9727 (eat 0)
9728 (sum 0))
9729 (while bytes
9730 (let* ((val (string-to-number (pop bytes) 16))
9731 (shift-xor
9732 (if (= 0 eat)
9733 (cond
9734 ((>= val 252) (cons 6 252))
9735 ((>= val 248) (cons 5 248))
9736 ((>= val 240) (cons 4 240))
9737 ((>= val 224) (cons 3 224))
9738 ((>= val 192) (cons 2 192))
9739 (t (cons 0 0)))
9740 (cons 6 128))))
9741 (when (>= val 192) (setq eat (car shift-xor)))
9742 (setq val (logxor val (cdr shift-xor)))
9743 (setq sum (+ (lsh sum (car shift-xor)) val))
9744 (when (> eat 0) (setq eat (- eat 1)))
9745 (cond
9746 ((= 0 eat) ;multi byte
9747 (setq ret (concat ret (char-to-string sum)))
9748 (setq sum 0))
9749 ((not bytes) ; single byte(s)
9750 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9751 ret)))
9753 (defun org-link-unescape-single-byte-sequence (hex)
9754 "Unhexify hex-encoded single byte character sequences."
9755 (mapconcat (lambda (byte)
9756 (char-to-string (string-to-number byte 16)))
9757 (cdr (split-string hex "%")) ""))
9759 (defun org-fixup-message-id-for-http (s)
9760 "Replace special characters in a message id, so it can be used in an http query."
9761 (when (string-match "%" s)
9762 (setq s (mapconcat (lambda (c)
9763 (if (eq c ?%)
9764 "%25"
9765 (char-to-string c)))
9766 s "")))
9767 (while (string-match "<" s)
9768 (setq s (replace-match "%3C" t t s)))
9769 (while (string-match ">" s)
9770 (setq s (replace-match "%3E" t t s)))
9771 (while (string-match "@" s)
9772 (setq s (replace-match "%40" t t s)))
9775 (defun org-link-prettify (link)
9776 "Return a human-readable representation of LINK.
9777 The car of LINK must be a raw link.
9778 The cdr of LINK must be either a link description or nil."
9779 (let ((desc (or (cadr link) "<no description>")))
9780 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9781 "<" (car link) ">")))
9783 ;;;###autoload
9784 (defun org-insert-link-global ()
9785 "Insert a link like Org mode does.
9786 This command can be called in any mode to insert a link in Org syntax."
9787 (interactive)
9788 (org-load-modules-maybe)
9789 (org-run-like-in-org-mode 'org-insert-link))
9791 (defun org-insert-all-links (arg &optional pre post)
9792 "Insert all links in `org-stored-links'.
9793 When a universal prefix, do not delete the links from `org-stored-links'.
9794 When `ARG' is a number, insert the last N link(s).
9795 `PRE' and `POST' are optional arguments to define a string to
9796 prepend or to append."
9797 (interactive "P")
9798 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9799 (links (copy-sequence org-stored-links))
9800 (pr (or pre "- "))
9801 (po (or post "\n"))
9802 (cnt 1) l)
9803 (if (null org-stored-links)
9804 (message "No link to insert")
9805 (while (and (or (listp arg) (>= arg cnt))
9806 (setq l (if (listp arg)
9807 (pop links)
9808 (pop org-stored-links))))
9809 (setq cnt (1+ cnt))
9810 (insert pr)
9811 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9812 (insert po)))))
9814 (defun org-insert-last-stored-link (arg)
9815 "Insert the last link stored in `org-stored-links'."
9816 (interactive "p")
9817 (org-insert-all-links arg "" "\n"))
9819 (defun org-link-fontify-links-to-this-file ()
9820 "Fontify links to the current file in `org-stored-links'."
9821 (let ((f (buffer-file-name)) a b)
9822 (setq a (mapcar (lambda(l)
9823 (let ((ll (car l)))
9824 (when (and (string-match "^file:\\(.+\\)::" ll)
9825 (equal f (expand-file-name (match-string 1 ll))))
9826 ll)))
9827 org-stored-links))
9828 (when (featurep 'org-id)
9829 (setq b (mapcar (lambda(l)
9830 (let ((ll (car l)))
9831 (when (and (string-match "^id:\\(.+\\)$" ll)
9832 (equal f (expand-file-name
9833 (or (org-id-find-id-file
9834 (match-string 1 ll)) ""))))
9835 ll)))
9836 org-stored-links)))
9837 (mapcar (lambda(l)
9838 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9839 (delq nil (append a b)))))
9841 (defvar org--links-history nil)
9842 (defun org-insert-link (&optional complete-file link-location default-description)
9843 "Insert a link. At the prompt, enter the link.
9845 Completion can be used to insert any of the link protocol prefixes in use.
9847 The history can be used to select a link previously stored with
9848 `org-store-link'. When the empty string is entered (i.e. if you just
9849 press `RET' at the prompt), the link defaults to the most recently
9850 stored link. As `SPC' triggers completion in the minibuffer, you need to
9851 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9853 You will also be prompted for a description, and if one is given, it will
9854 be displayed in the buffer instead of the link.
9856 If there is already a link at point, this command will allow you to edit
9857 link and description parts.
9859 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9860 file name can be
9861 selected using completion. The path to the file will be relative to the
9862 current directory if the file is in the current directory or a subdirectory.
9863 Otherwise, the link will be the absolute path as completed in the minibuffer
9864 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9865 option `org-link-file-path-type'.
9867 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9868 absolute path even if the file is in
9869 the current directory or below.
9871 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9872 prefix negates `org-keep-stored-link-after-insertion'.
9874 If the LINK-LOCATION parameter is non-nil, this value will be used as
9875 the link location instead of reading one interactively.
9877 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9878 be used as the default description. Otherwise, if
9879 `org-make-link-description-function' is non-nil, this function
9880 will be called with the link target, and the result will be the
9881 default link description."
9882 (interactive "P")
9883 (let* ((wcf (current-window-configuration))
9884 (origbuf (current-buffer))
9885 (region (when (org-region-active-p)
9886 (buffer-substring (region-beginning) (region-end))))
9887 (remove (and region (list (region-beginning) (region-end))))
9888 (desc region)
9889 (link link-location)
9890 (abbrevs org-link-abbrev-alist-local)
9891 entry all-prefixes auto-desc)
9892 (cond
9893 (link-location) ; specified by arg, just use it.
9894 ((org-in-regexp org-bracket-link-regexp 1)
9895 ;; We do have a link at point, and we are going to edit it.
9896 (setq remove (list (match-beginning 0) (match-end 0)))
9897 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9898 (setq link (read-string "Link: "
9899 (org-link-unescape
9900 (match-string-no-properties 1)))))
9901 ((or (org-in-regexp org-angle-link-re)
9902 (org-in-regexp org-plain-link-re))
9903 ;; Convert to bracket link
9904 (setq remove (list (match-beginning 0) (match-end 0))
9905 link (read-string "Link: "
9906 (org-unbracket-string "<" ">" (match-string 0)))))
9907 ((member complete-file '((4) (16)))
9908 ;; Completing read for file names.
9909 (setq link (org-file-complete-link complete-file)))
9911 ;; Read link, with completion for stored links.
9912 (org-link-fontify-links-to-this-file)
9913 (org-switch-to-buffer-other-window "*Org Links*")
9914 (with-current-buffer "*Org Links*"
9915 (erase-buffer)
9916 (insert "Insert a link.
9917 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9918 (when org-stored-links
9919 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9920 (insert (mapconcat 'org-link-prettify
9921 (reverse org-stored-links) "\n")))
9922 (goto-char (point-min)))
9923 (let ((cw (selected-window)))
9924 (select-window (get-buffer-window "*Org Links*" 'visible))
9925 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9926 (unless (pos-visible-in-window-p (point-max))
9927 (org-fit-window-to-buffer))
9928 (and (window-live-p cw) (select-window cw)))
9929 (setq all-prefixes (append (mapcar 'car abbrevs)
9930 (mapcar 'car org-link-abbrev-alist)
9931 (org-link-types)))
9932 (unwind-protect
9933 ;; Fake a link history, containing the stored links.
9934 (let ((org--links-history
9935 (append (mapcar #'car org-stored-links)
9936 org-insert-link-history)))
9937 (setq link
9938 (org-completing-read
9939 "Link: "
9940 (append
9941 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9942 (mapcar #'car org-stored-links))
9943 nil nil nil
9944 'org--links-history
9945 (caar org-stored-links)))
9946 (unless (org-string-nw-p link) (user-error "No link selected"))
9947 (dolist (l org-stored-links)
9948 (when (equal link (cadr l))
9949 (setq link (car l))
9950 (setq auto-desc t)))
9951 (when (or (member link all-prefixes)
9952 (and (equal ":" (substring link -1))
9953 (member (substring link 0 -1) all-prefixes)
9954 (setq link (substring link 0 -1))))
9955 (setq link (with-current-buffer origbuf
9956 (org-link-try-special-completion link)))))
9957 (set-window-configuration wcf)
9958 (kill-buffer "*Org Links*"))
9959 (setq entry (assoc link org-stored-links))
9960 (or entry (push link org-insert-link-history))
9961 (setq desc (or desc (nth 1 entry)))))
9963 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9964 (not org-keep-stored-link-after-insertion))
9965 (setq org-stored-links (delq (assoc link org-stored-links)
9966 org-stored-links)))
9968 (when (and (string-match org-plain-link-re link)
9969 (not (string-match org-ts-regexp link)))
9970 ;; URL-like link, normalize the use of angular brackets.
9971 (setq link (org-unbracket-string "<" ">" link)))
9973 ;; Check if we are linking to the current file with a search
9974 ;; option If yes, simplify the link by using only the search
9975 ;; option.
9976 (when (and buffer-file-name
9977 (let ((case-fold-search nil))
9978 (string-match "\\`file:\\(.+?\\)::" link)))
9979 (let ((path (match-string-no-properties 1 link))
9980 (search (substring-no-properties link (match-end 0))))
9981 (save-match-data
9982 (when (equal (file-truename buffer-file-name) (file-truename path))
9983 ;; We are linking to this same file, with a search option
9984 (setq link search)))))
9986 ;; Check if we can/should use a relative path. If yes, simplify the link
9987 (let ((case-fold-search nil))
9988 (when (string-match "\\`\\(file\\|docview\\):" link)
9989 (let* ((type (match-string-no-properties 0 link))
9990 (path (substring-no-properties link (match-end 0)))
9991 (origpath path))
9992 (cond
9993 ((or (eq org-link-file-path-type 'absolute)
9994 (equal complete-file '(16)))
9995 (setq path (abbreviate-file-name (expand-file-name path))))
9996 ((eq org-link-file-path-type 'noabbrev)
9997 (setq path (expand-file-name path)))
9998 ((eq org-link-file-path-type 'relative)
9999 (setq path (file-relative-name path)))
10001 (save-match-data
10002 (if (string-match (concat "^" (regexp-quote
10003 (expand-file-name
10004 (file-name-as-directory
10005 default-directory))))
10006 (expand-file-name path))
10007 ;; We are linking a file with relative path name.
10008 (setq path (substring (expand-file-name path)
10009 (match-end 0)))
10010 (setq path (abbreviate-file-name (expand-file-name path)))))))
10011 (setq link (concat type path))
10012 (when (equal desc origpath)
10013 (setq desc path)))))
10015 (unless auto-desc
10016 (let ((initial-input
10017 (cond
10018 (default-description)
10019 ((not org-make-link-description-function) desc)
10020 (t (condition-case nil
10021 (funcall org-make-link-description-function link desc)
10022 (error
10023 (message "Can't get link description from `%s'"
10024 (symbol-name org-make-link-description-function))
10025 (sit-for 2)
10026 nil))))))
10027 (setq desc (read-string "Description: " initial-input))))
10029 (unless (string-match "\\S-" desc) (setq desc nil))
10030 (when remove (apply 'delete-region remove))
10031 (insert (org-make-link-string link desc))
10032 ;; Redisplay so as the new link has proper invisible characters.
10033 (sit-for 0)))
10035 (defun org-link-try-special-completion (type)
10036 "If there is completion support for link type TYPE, offer it."
10037 (let ((fun (org-link-get-parameter type :complete)))
10038 (if (functionp fun)
10039 (funcall fun)
10040 (read-string "Link (no completion support): " (concat type ":")))))
10042 (defun org-file-complete-link (&optional arg)
10043 "Create a file link using completion."
10044 (let ((file (read-file-name "File: "))
10045 (pwd (file-name-as-directory (expand-file-name ".")))
10046 (pwd1 (file-name-as-directory (abbreviate-file-name
10047 (expand-file-name ".")))))
10048 (cond ((equal arg '(16))
10049 (concat "file:"
10050 (abbreviate-file-name (expand-file-name file))))
10051 ((string-match
10052 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10053 (concat "file:" (match-string 1 file)))
10054 ((string-match
10055 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10056 (expand-file-name file))
10057 (concat "file:"
10058 (match-string 1 (expand-file-name file))))
10059 (t (concat "file:" file)))))
10062 ;;; Opening/following a link
10064 (defvar org-link-search-failed nil)
10066 (defvar org-open-link-functions nil
10067 "Hook for functions finding a plain text link.
10068 These functions must take a single argument, the link content.
10069 They will be called for links that look like [[link text][description]]
10070 when LINK TEXT does not have a protocol like \"http:\" and does not look
10071 like a filename (e.g. \"./blue.png\").
10073 These functions will be called *before* Org attempts to resolve the
10074 link by doing text searches in the current buffer - so if you want a
10075 link \"[[target]]\" to still find \"<<target>>\", your function should
10076 handle this as a special case.
10078 When the function does handle the link, it must return a non-nil value.
10079 If it decides that it is not responsible for this link, it must return
10080 nil to indicate that that Org can continue with other options like
10081 exact and fuzzy text search.")
10083 (defun org-next-link (&optional search-backward)
10084 "Move forward to the next link.
10085 If the link is in hidden text, expose it."
10086 (interactive "P")
10087 (when (and org-link-search-failed (eq this-command last-command))
10088 (goto-char (point-min))
10089 (message "Link search wrapped back to beginning of buffer"))
10090 (setq org-link-search-failed nil)
10091 (let* ((pos (point))
10092 (ct (org-context))
10093 (a (assq :link ct))
10094 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10095 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10096 ((looking-at org-any-link-re)
10097 ;; Don't stay stuck at link without an org-link face
10098 (forward-char (if search-backward -1 1))))
10099 (if (funcall srch-fun org-any-link-re nil t)
10100 (progn
10101 (goto-char (match-beginning 0))
10102 (when (org-invisible-p) (org-show-context)))
10103 (goto-char pos)
10104 (setq org-link-search-failed t)
10105 (message "No further link found"))))
10107 (defun org-previous-link ()
10108 "Move backward to the previous link.
10109 If the link is in hidden text, expose it."
10110 (interactive)
10111 (funcall 'org-next-link t))
10113 (defun org-translate-link (s)
10114 "Translate a link string if a translation function has been defined."
10115 (with-temp-buffer
10116 (insert (org-trim s))
10117 (org-trim (org-element-interpret-data (org-element-context)))))
10119 (defun org-translate-link-from-planner (type path)
10120 "Translate a link from Emacs Planner syntax so that Org can follow it.
10121 This is still an experimental function, your mileage may vary."
10122 (cond
10123 ((member type '("http" "https" "news" "ftp"))
10124 ;; standard Internet links are the same.
10125 nil)
10126 ((and (equal type "irc") (string-match "^//" path))
10127 ;; Planner has two / at the beginning of an irc link, we have 1.
10128 ;; We should have zero, actually....
10129 (setq path (substring path 1)))
10130 ((and (equal type "lisp") (string-match "^/" path))
10131 ;; Planner has a slash, we do not.
10132 (setq type "elisp" path (substring path 1)))
10133 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10134 ;; A typical message link. Planner has the id after the final slash,
10135 ;; we separate it with a hash mark
10136 (setq path (concat (match-string 1 path) "#"
10137 (org-unbracket-string "<" ">" (match-string 2 path))))))
10138 (cons type path))
10140 (defun org-find-file-at-mouse (ev)
10141 "Open file link or URL at mouse."
10142 (interactive "e")
10143 (mouse-set-point ev)
10144 (org-open-at-point 'in-emacs))
10146 (defun org-open-at-mouse (ev)
10147 "Open file link or URL at mouse.
10148 See the docstring of `org-open-file' for details."
10149 (interactive "e")
10150 (mouse-set-point ev)
10151 (when (eq major-mode 'org-agenda-mode)
10152 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10153 (org-open-at-point))
10155 (defvar org-window-config-before-follow-link nil
10156 "The window configuration before following a link.
10157 This is saved in case the need arises to restore it.")
10159 ;;;###autoload
10160 (defun org-open-at-point-global ()
10161 "Follow a link or time-stamp like Org mode does.
10162 This command can be called in any mode to follow an external link
10163 or a time-stamp that has Org mode syntax. Its behavior is
10164 undefined when called on internal links (e.g., fuzzy links).
10165 Raise an error when there is nothing to follow. "
10166 (interactive)
10167 (cond ((org-in-regexp org-any-link-re)
10168 (org-open-link-from-string (match-string-no-properties 0)))
10169 ((or (org-in-regexp org-ts-regexp-both nil t)
10170 (org-in-regexp org-tsr-regexp-both nil t))
10171 (org-follow-timestamp-link))
10172 (t (user-error "No link found"))))
10174 ;;;###autoload
10175 (defun org-open-link-from-string (s &optional arg reference-buffer)
10176 "Open a link in the string S, as if it was in Org mode."
10177 (interactive "sLink: \nP")
10178 (let ((reference-buffer (or reference-buffer (current-buffer))))
10179 (with-temp-buffer
10180 (let ((org-inhibit-startup (not reference-buffer)))
10181 (org-mode)
10182 (insert s)
10183 (goto-char (point-min))
10184 (when reference-buffer
10185 (setq org-link-abbrev-alist-local
10186 (with-current-buffer reference-buffer
10187 org-link-abbrev-alist-local)))
10188 (org-open-at-point arg reference-buffer)))))
10190 (defvar org-open-at-point-functions nil
10191 "Hook that is run when following a link at point.
10193 Functions in this hook must return t if they identify and follow
10194 a link at point. If they don't find anything interesting at point,
10195 they must return nil.")
10197 (defvar org-link-search-inhibit-query nil)
10198 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10199 (defun org--open-doi-link (path)
10200 "Open a \"doi\" type link.
10201 PATH is a the path to search for, as a string."
10202 (browse-url (url-encode-url (concat org-doi-server-url path))))
10204 (defun org--open-elisp-link (path)
10205 "Open a \"elisp\" type link.
10206 PATH is the sexp to evaluate, as a string."
10207 (let ((cmd path))
10208 (if (or (and (org-string-nw-p
10209 org-confirm-elisp-link-not-regexp)
10210 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10211 (not org-confirm-elisp-link-function)
10212 (funcall org-confirm-elisp-link-function
10213 (format "Execute \"%s\" as elisp? "
10214 (org-add-props cmd nil 'face 'org-warning))))
10215 (message "%s => %s" cmd
10216 (if (eq (string-to-char cmd) ?\()
10217 (eval (read cmd))
10218 (call-interactively (read cmd))))
10219 (user-error "Abort"))))
10221 (defun org--open-help-link (path)
10222 "Open a \"help\" type link.
10223 PATH is a symbol name, as a string."
10224 (pcase (intern path)
10225 ((and (pred fboundp) variable) (describe-function variable))
10226 ((and (pred boundp) function) (describe-variable function))
10227 (name (user-error "Unknown function or variable: %s" name))))
10229 (defun org--open-shell-link (path)
10230 "Open a \"shell\" type link.
10231 PATH is the command to execute, as a string."
10232 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10233 (cmd path))
10234 (if (or (and (org-string-nw-p
10235 org-confirm-shell-link-not-regexp)
10236 (string-match
10237 org-confirm-shell-link-not-regexp cmd))
10238 (not org-confirm-shell-link-function)
10239 (funcall org-confirm-shell-link-function
10240 (format "Execute \"%s\" in shell? "
10241 (org-add-props cmd nil
10242 'face 'org-warning))))
10243 (progn
10244 (message "Executing %s" cmd)
10245 (shell-command cmd buf)
10246 (when (featurep 'midnight)
10247 (setq clean-buffer-list-kill-buffer-names
10248 (cons (buffer-name buf)
10249 clean-buffer-list-kill-buffer-names))))
10250 (user-error "Abort"))))
10252 (defun org-open-at-point (&optional arg reference-buffer)
10253 "Open link, timestamp, footnote or tags at point.
10255 When point is on a link, follow it. Normally, files will be
10256 opened by an appropriate application. If the optional prefix
10257 argument ARG is non-nil, Emacs will visit the file. With
10258 a double prefix argument, try to open outside of Emacs, in the
10259 application the system uses for this file type.
10261 When point is on a timestamp, open the agenda at the day
10262 specified.
10264 When point is a footnote definition, move to the first reference
10265 found. If it is on a reference, move to the associated
10266 definition.
10268 When point is on a headline, display a list of every link in the
10269 entry, so it is possible to pick one, or all, of them. If point
10270 is on a tag, call `org-tags-view' instead.
10272 When optional argument REFERENCE-BUFFER is non-nil, it should
10273 specify a buffer from where the link search should happen. This
10274 is used internally by `org-open-link-from-string'.
10276 On top of syntactically correct links, this function will also
10277 try to open links and time-stamps in comments, example
10278 blocks... i.e., whenever point is on something looking like
10279 a timestamp or a link."
10280 (interactive "P")
10281 ;; On a code block, open block's results.
10282 (unless (call-interactively 'org-babel-open-src-block-result)
10283 (org-load-modules-maybe)
10284 (setq org-window-config-before-follow-link (current-window-configuration))
10285 (org-remove-occur-highlights nil nil t)
10286 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10287 (let* ((context
10288 ;; Only consider supported types, even if they are not
10289 ;; the closest one.
10290 (org-element-lineage
10291 (org-element-context)
10292 '(clock footnote-definition footnote-reference headline
10293 inlinetask link timestamp)
10295 (type (org-element-type context))
10296 (value (org-element-property :value context)))
10297 (cond
10298 ;; On a headline or an inlinetask, but not on a timestamp,
10299 ;; a link, a footnote reference.
10300 ((memq type '(headline inlinetask))
10301 (org-match-line org-complex-heading-regexp)
10302 (if (and (match-beginning 5)
10303 (>= (point) (match-beginning 5))
10304 (< (point) (match-end 5)))
10305 ;; On tags.
10306 (org-tags-view arg (substring (match-string 5) 0 -1))
10307 ;; Not on tags.
10308 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10309 (`(nil . ,_)
10310 (require 'org-attach)
10311 (org-attach-reveal 'if-exists))
10312 (`(,links . ,links-end)
10313 (dolist (link (if (stringp links) (list links) links))
10314 (search-forward link nil links-end)
10315 (goto-char (match-beginning 0))
10316 (org-open-at-point))))))
10317 ;; On a footnote reference or at definition's label.
10318 ((or (eq type 'footnote-reference)
10319 (and (eq type 'footnote-definition)
10320 (save-excursion
10321 ;; Do not validate action when point is on the
10322 ;; spaces right after the footnote label, in
10323 ;; order to be on par with behaviour on links.
10324 (skip-chars-forward " \t")
10325 (let ((begin
10326 (org-element-property :contents-begin context)))
10327 (if begin (< (point) begin)
10328 (= (org-element-property :post-affiliated context)
10329 (line-beginning-position)))))))
10330 (org-footnote-action))
10331 ;; No valid context. Ignore catch-all types like `headline'.
10332 ;; If point is on something looking like a link or
10333 ;; a time-stamp, try opening it. It may be useful in
10334 ;; comments, example blocks...
10335 ((memq type '(footnote-definition headline inlinetask nil))
10336 (call-interactively #'org-open-at-point-global))
10337 ;; On a clock line, make sure point is on the timestamp
10338 ;; before opening it.
10339 ((and (eq type 'clock)
10340 value
10341 (>= (point) (org-element-property :begin value))
10342 (<= (point) (org-element-property :end value)))
10343 (org-follow-timestamp-link))
10344 ;; Do nothing on white spaces after an object.
10345 ((>= (point)
10346 (save-excursion
10347 (goto-char (org-element-property :end context))
10348 (skip-chars-backward " \t")
10349 (point)))
10350 (user-error "No link found"))
10351 ((eq type 'timestamp) (org-follow-timestamp-link))
10352 ((eq type 'link)
10353 (let ((type (org-element-property :type context))
10354 (path (org-link-unescape (org-element-property :path context))))
10355 ;; Switch back to REFERENCE-BUFFER needed when called in
10356 ;; a temporary buffer through `org-open-link-from-string'.
10357 (with-current-buffer (or reference-buffer (current-buffer))
10358 (cond
10359 ((equal type "file")
10360 (if (string-match "[*?{]" (file-name-nondirectory path))
10361 (dired path)
10362 ;; Look into `org-link-parameters' in order to find
10363 ;; a DEDICATED-FUNCTION to open file. The function
10364 ;; will be applied on raw link instead of parsed
10365 ;; link due to the limitation in `org-add-link-type'
10366 ;; ("open" function called with a single argument).
10367 ;; If no such function is found, fallback to
10368 ;; `org-open-file'.
10369 (let* ((option (org-element-property :search-option context))
10370 (app (org-element-property :application context))
10371 (dedicated-function
10372 (org-link-get-parameter
10373 (if app (concat type "+" app) type)
10374 :follow)))
10375 (if dedicated-function
10376 (funcall dedicated-function
10377 (concat path
10378 (and option (concat "::" option))))
10379 (apply #'org-open-file
10380 path
10381 (cond (arg)
10382 ((equal app "emacs") 'emacs)
10383 ((equal app "sys") 'system))
10384 (cond ((not option) nil)
10385 ((string-match-p "\\`[0-9]+\\'" option)
10386 (list (string-to-number option)))
10387 (t (list nil
10388 (org-link-unescape option)))))))))
10389 ((functionp (org-link-get-parameter type :follow))
10390 (funcall (org-link-get-parameter type :follow) path))
10391 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10392 (unless (run-hook-with-args-until-success
10393 'org-open-link-functions path)
10394 (if (not arg) (org-mark-ring-push)
10395 (switch-to-buffer-other-window
10396 (org-get-buffer-for-internal-link (current-buffer))))
10397 (let ((destination
10398 (org-with-wide-buffer
10399 (if (equal type "radio")
10400 (org-search-radio-target
10401 (org-element-property :path context))
10402 (org-link-search
10403 (if (member type '("custom-id" "coderef"))
10404 (org-element-property :raw-link context)
10405 path)
10406 ;; Prevent fuzzy links from matching
10407 ;; themselves.
10408 (and (equal type "fuzzy")
10409 (+ 2 (org-element-property :begin context)))))
10410 (point))))
10411 (unless (and (<= (point-min) destination)
10412 (>= (point-max) destination))
10413 (widen))
10414 (goto-char destination))))
10415 (t (browse-url-at-point))))))
10416 (t (user-error "No link found")))))
10417 (run-hook-with-args 'org-follow-link-hook)))
10419 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10420 "Offer links in the current entry and return the selected link.
10421 If there is only one link, return it.
10422 If NTH is an integer, return the NTH link found.
10423 If ZERO is a string, check also this string for a link, and if
10424 there is one, return it."
10425 (with-current-buffer buffer
10426 (org-with-wide-buffer
10427 (goto-char marker)
10428 (let ((cnt ?0)
10429 have-zero end links link c)
10430 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10431 (push (match-string 0 zero) links)
10432 (setq cnt (1- cnt) have-zero t))
10433 (save-excursion
10434 (org-back-to-heading t)
10435 (setq end (save-excursion (outline-next-heading) (point)))
10436 (while (re-search-forward org-any-link-re end t)
10437 (push (match-string 0) links))
10438 (setq links (org-uniquify (reverse links))))
10439 (cond
10440 ((null links)
10441 (message "No links"))
10442 ((equal (length links) 1)
10443 (setq link (car links)))
10444 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10445 (setq link (nth (if have-zero nth (1- nth)) links)))
10446 (t ; we have to select a link
10447 (save-excursion
10448 (save-window-excursion
10449 (delete-other-windows)
10450 (with-output-to-temp-buffer "*Select Link*"
10451 (dolist (l links)
10452 (cond
10453 ((not (string-match org-bracket-link-regexp l))
10454 (princ (format "[%c] %s\n" (cl-incf cnt)
10455 (org-unbracket-string "<" ">" l))))
10456 ((match-end 3)
10457 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10458 (match-string 3 l) (match-string 1 l))))
10459 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10460 (match-string 1 l)))))))
10461 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10462 (message "Select link to open, RET to open all:")
10463 (setq c (read-char-exclusive))
10464 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10465 (when (equal c ?q) (user-error "Abort"))
10466 (if (equal c ?\C-m)
10467 (setq link links)
10468 (setq nth (- c ?0))
10469 (when have-zero (setq nth (1+ nth)))
10470 (unless (and (integerp nth) (>= (length links) nth))
10471 (user-error "Invalid link selection"))
10472 (setq link (nth (1- nth) links)))))
10473 (cons link end)))))
10475 ;; TODO: These functions are deprecated since `org-open-at-point'
10476 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10477 (defun org-open-file-with-system (path)
10478 "Open file at PATH using the system way of opening it."
10479 (org-open-file path 'system))
10480 (defun org-open-file-with-emacs (path)
10481 "Open file at PATH in Emacs."
10482 (org-open-file path 'emacs))
10485 ;;; File search
10487 (defvar org-create-file-search-functions nil
10488 "List of functions to construct the right search string for a file link.
10489 These functions are called in turn with point at the location to
10490 which the link should point.
10492 A function in the hook should first test if it would like to
10493 handle this file type, for example by checking the `major-mode'
10494 or the file extension. If it decides not to handle this file, it
10495 should just return nil to give other functions a chance. If it
10496 does handle the file, it must return the search string to be used
10497 when following the link. The search string will be part of the
10498 file link, given after a double colon, and `org-open-at-point'
10499 will automatically search for it. If special measures must be
10500 taken to make the search successful, another function should be
10501 added to the companion hook `org-execute-file-search-functions',
10502 which see.
10504 A function in this hook may also use `setq' to set the variable
10505 `description' to provide a suggestion for the descriptive text to
10506 be used for this link when it gets inserted into an Org buffer
10507 with \\[org-insert-link].")
10509 (defvar org-execute-file-search-functions nil
10510 "List of functions to execute a file search triggered by a link.
10512 Functions added to this hook must accept a single argument, the
10513 search string that was part of the file link, the part after the
10514 double colon. The function must first check if it would like to
10515 handle this search, for example by checking the `major-mode' or
10516 the file extension. If it decides not to handle this search, it
10517 should just return nil to give other functions a chance. If it
10518 does handle the search, it must return a non-nil value to keep
10519 other functions from trying.
10521 Each function can access the current prefix argument through the
10522 variable `current-prefix-arg'. Note that a single prefix is used
10523 to force opening a link in Emacs, so it may be good to only use a
10524 numeric or double prefix to guide the search function.
10526 In case this is needed, a function in this hook can also restore
10527 the window configuration before `org-open-at-point' was called using:
10529 (set-window-configuration org-window-config-before-follow-link)")
10531 (defun org-search-radio-target (target)
10532 "Search a radio target matching TARGET in current buffer.
10533 White spaces are not significant."
10534 (let ((re (format "<<<%s>>>"
10535 (mapconcat #'regexp-quote
10536 (split-string target)
10537 "[ \t]+\\(?:\n[ \t]*\\)?")))
10538 (origin (point)))
10539 (goto-char (point-min))
10540 (catch :radio-match
10541 (while (re-search-forward re nil t)
10542 (backward-char)
10543 (let ((object (org-element-context)))
10544 (when (eq (org-element-type object) 'radio-target)
10545 (goto-char (org-element-property :begin object))
10546 (org-show-context 'link-search)
10547 (throw :radio-match nil))))
10548 (goto-char origin)
10549 (user-error "No match for radio target: %s" target))))
10551 (defun org-link-search (s &optional avoid-pos stealth)
10552 "Search for a search string S.
10554 If S starts with \"#\", it triggers a custom ID search.
10556 If S is enclosed within parenthesis, it initiates a coderef
10557 search.
10559 If S is surrounded by forward slashes, it is interpreted as
10560 a regular expression. In Org mode files, this will create an
10561 `org-occur' sparse tree. In ordinary files, `occur' will be used
10562 to list matches. If the current buffer is in `dired-mode', grep
10563 will be used to search in all files.
10565 When AVOID-POS is given, ignore matches near that position.
10567 When optional argument STEALTH is non-nil, do not modify
10568 visibility around point, thus ignoring `org-show-context-detail'
10569 variable.
10571 Search is case-insensitive and ignores white spaces. Return type
10572 of matched result, which is either `dedicated' or `fuzzy'."
10573 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10574 (let* ((case-fold-search t)
10575 (origin (point))
10576 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10577 (starred (eq (string-to-char normalized) ?*))
10578 (words (split-string (if starred (substring s 1) s)))
10579 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10580 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10581 type)
10582 (cond
10583 ;; Check if there are any special search functions.
10584 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10585 ((eq (string-to-char s) ?#)
10586 ;; Look for a custom ID S if S starts with "#".
10587 (let* ((id (substring normalized 1))
10588 (match (org-find-property "CUSTOM_ID" id)))
10589 (if match (progn (goto-char match) (setf type 'dedicated))
10590 (error "No match for custom ID: %s" id))))
10591 ((string-match "\\`(\\(.*\\))\\'" normalized)
10592 ;; Look for coderef targets if S is enclosed within parenthesis.
10593 (let ((coderef (match-string-no-properties 1 normalized))
10594 (re (substring s-single-re 1 -1)))
10595 (goto-char (point-min))
10596 (catch :coderef-match
10597 (while (re-search-forward re nil t)
10598 (let ((element (org-element-at-point)))
10599 (when (and (memq (org-element-type element)
10600 '(example-block src-block))
10601 ;; Build proper regexp according to current
10602 ;; block's label format.
10603 (let ((label-fmt
10604 (regexp-quote
10605 (or (org-element-property :label-fmt element)
10606 org-coderef-label-format))))
10607 (save-excursion
10608 (beginning-of-line)
10609 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10610 (format label-fmt coderef))))))
10611 (setq type 'dedicated)
10612 (goto-char (match-beginning 1))
10613 (throw :coderef-match nil))))
10614 (goto-char origin)
10615 (error "No match for coderef: %s" coderef))))
10616 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10617 ;; Look for a regular expression.
10618 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10619 (match-string 1 s)))
10620 ;; From here, we handle fuzzy links.
10622 ;; Look for targets, only if not in a headline search.
10623 ((and (not starred)
10624 (let ((target (format "<<%s>>" s-multi-re)))
10625 (catch :target-match
10626 (goto-char (point-min))
10627 (while (re-search-forward target nil t)
10628 (backward-char)
10629 (let ((context (org-element-context)))
10630 (when (eq (org-element-type context) 'target)
10631 (setq type 'dedicated)
10632 (goto-char (org-element-property :begin context))
10633 (throw :target-match t))))
10634 nil))))
10635 ;; Look for elements named after S, only if not in a headline
10636 ;; search.
10637 ((and (not starred)
10638 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10639 (catch :name-match
10640 (goto-char (point-min))
10641 (while (re-search-forward name nil t)
10642 (let ((element (org-element-at-point)))
10643 (when (equal words
10644 (split-string
10645 (org-element-property :name element)))
10646 (setq type 'dedicated)
10647 (beginning-of-line)
10648 (throw :name-match t))))
10649 nil))))
10650 ;; Regular text search. Prefer headlines in Org mode buffers.
10651 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10652 ;; statistics cookies and tags.
10653 ((and (derived-mode-p 'org-mode)
10654 (let ((title-re
10655 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10656 org-outline-regexp-bol
10657 org-comment-string
10658 (mapconcat #'regexp-quote words ".+")))
10659 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10660 (comment-re (eval-when-compile
10661 (format "\\`%s[ \t]+" org-comment-string))))
10662 (goto-char (point-min))
10663 (catch :found
10664 (while (re-search-forward title-re nil t)
10665 (when (equal words
10666 (split-string
10667 (replace-regexp-in-string
10668 cookie-re ""
10669 (replace-regexp-in-string
10670 comment-re "" (org-get-heading t t t)))))
10671 (throw :found t)))
10672 nil)))
10673 (beginning-of-line)
10674 (setq type 'dedicated))
10675 ;; Offer to create non-existent headline depending on
10676 ;; `org-link-search-must-match-exact-headline'.
10677 ((and (derived-mode-p 'org-mode)
10678 (not org-link-search-inhibit-query)
10679 (eq org-link-search-must-match-exact-headline 'query-to-create)
10680 (yes-or-no-p "No match - create this as a new heading? "))
10681 (goto-char (point-max))
10682 (unless (bolp) (newline))
10683 (org-insert-heading nil t t)
10684 (insert s "\n")
10685 (beginning-of-line 0))
10686 ;; Only headlines are looked after. No need to process
10687 ;; further: throw an error.
10688 ((and (derived-mode-p 'org-mode)
10689 (or starred org-link-search-must-match-exact-headline))
10690 (goto-char origin)
10691 (error "No match for fuzzy expression: %s" normalized))
10692 ;; Regular text search.
10693 ((catch :fuzzy-match
10694 (goto-char (point-min))
10695 (while (re-search-forward s-multi-re nil t)
10696 ;; Skip match if it contains AVOID-POS or it is included in
10697 ;; a link with a description but outside the description.
10698 (unless (or (and avoid-pos
10699 (<= (match-beginning 0) avoid-pos)
10700 (> (match-end 0) avoid-pos))
10701 (and (save-match-data
10702 (org-in-regexp org-bracket-link-regexp))
10703 (match-beginning 3)
10704 (or (> (match-beginning 3) (point))
10705 (<= (match-end 3) (point)))
10706 (org-element-lineage
10707 (save-match-data (org-element-context))
10708 '(link) t)))
10709 (goto-char (match-beginning 0))
10710 (setq type 'fuzzy)
10711 (throw :fuzzy-match t)))
10712 nil))
10713 ;; All failed. Throw an error.
10714 (t (goto-char origin)
10715 (error "No match for fuzzy expression: %s" normalized)))
10716 ;; Disclose surroundings of match, if appropriate.
10717 (when (and (derived-mode-p 'org-mode) (not stealth))
10718 (org-show-context 'link-search))
10719 type))
10721 (defun org-get-buffer-for-internal-link (buffer)
10722 "Return a buffer to be used for displaying the link target of internal links."
10723 (cond
10724 ((not org-display-internal-link-with-indirect-buffer)
10725 buffer)
10726 ((string-suffix-p "(Clone)" (buffer-name buffer))
10727 (message "Buffer is already a clone, not making another one")
10728 ;; we also do not modify visibility in this case
10729 buffer)
10730 (t ; make a new indirect buffer for displaying the link
10731 (let* ((bn (buffer-name buffer))
10732 (ibn (concat bn "(Clone)"))
10733 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10734 (with-current-buffer ib (org-overview))
10735 ib))))
10737 (defun org-do-occur (regexp &optional cleanup)
10738 "Call the Emacs command `occur'.
10739 If CLEANUP is non-nil, remove the printout of the regular expression
10740 in the *Occur* buffer. This is useful if the regex is long and not useful
10741 to read."
10742 (occur regexp)
10743 (when cleanup
10744 (let ((cwin (selected-window)) win beg end)
10745 (when (setq win (get-buffer-window "*Occur*"))
10746 (select-window win))
10747 (goto-char (point-min))
10748 (when (re-search-forward "match[a-z]+" nil t)
10749 (setq beg (match-end 0))
10750 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10751 (setq end (1- (match-beginning 0)))))
10752 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10753 (goto-char (point-min))
10754 (select-window cwin))))
10756 ;;; The mark ring for links jumps
10758 (defvar org-mark-ring nil
10759 "Mark ring for positions before jumps in Org mode.")
10760 (defvar org-mark-ring-last-goto nil
10761 "Last position in the mark ring used to go back.")
10762 ;; Fill and close the ring
10763 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10764 (dotimes (_ org-mark-ring-length)
10765 (push (make-marker) org-mark-ring))
10766 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10767 org-mark-ring)
10769 (defun org-mark-ring-push (&optional pos buffer)
10770 "Put the current position or POS into the mark ring and rotate it."
10771 (interactive)
10772 (setq pos (or pos (point)))
10773 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10774 (move-marker (car org-mark-ring)
10775 (or pos (point))
10776 (or buffer (current-buffer)))
10777 (message "%s"
10778 (substitute-command-keys
10779 "Position saved to mark ring, go back with \
10780 `\\[org-mark-ring-goto]'.")))
10782 (defun org-mark-ring-goto (&optional n)
10783 "Jump to the previous position in the mark ring.
10784 With prefix arg N, jump back that many stored positions. When
10785 called several times in succession, walk through the entire ring.
10786 Org mode commands jumping to a different position in the current file,
10787 or to another Org file, automatically push the old position onto the ring."
10788 (interactive "p")
10789 (let (p m)
10790 (if (eq last-command this-command)
10791 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10792 (setq p org-mark-ring))
10793 (setq org-mark-ring-last-goto p)
10794 (setq m (car p))
10795 (pop-to-buffer-same-window (marker-buffer m))
10796 (goto-char m)
10797 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10799 (defun org-add-angle-brackets (s)
10800 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10801 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10804 ;;; Following specific links
10806 (defvar org-agenda-buffer-tmp-name)
10807 (defvar org-agenda-start-on-weekday)
10808 (defun org-follow-timestamp-link ()
10809 "Open an agenda view for the time-stamp date/range at point."
10810 (cond
10811 ((org-at-date-range-p t)
10812 (let ((org-agenda-start-on-weekday)
10813 (t1 (match-string 1))
10814 (t2 (match-string 2)) tt1 tt2)
10815 (setq tt1 (time-to-days (org-time-string-to-time t1))
10816 tt2 (time-to-days (org-time-string-to-time t2)))
10817 (let ((org-agenda-buffer-tmp-name
10818 (format "*Org Agenda(a:%s)"
10819 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10820 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10821 ((org-at-timestamp-p 'lax)
10822 (let ((org-agenda-buffer-tmp-name
10823 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10824 (org-agenda-list nil (time-to-days (org-time-string-to-time
10825 (substring (match-string 1) 0 10)))
10826 1)))
10827 (t (error "This should not happen"))))
10830 ;;; Following file links
10831 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10832 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10833 (declare-function mailcap-mime-info
10834 "mailcap" (string &optional request no-decode))
10835 (defvar org-wait nil)
10836 (defun org-open-file (path &optional in-emacs line search)
10837 "Open the file at PATH.
10838 First, this expands any special file name abbreviations. Then the
10839 configuration variable `org-file-apps' is checked if it contains an
10840 entry for this file type, and if yes, the corresponding command is launched.
10842 If no application is found, Emacs simply visits the file.
10844 With optional prefix argument IN-EMACS, Emacs will visit the file.
10845 With a double \\[universal-argument] \\[universal-argument] \
10846 prefix arg, Org tries to avoid opening in Emacs
10847 and to use an external application to visit the file.
10849 Optional LINE specifies a line to go to, optional SEARCH a string
10850 to search for. If LINE or SEARCH is given, the file will be
10851 opened in Emacs, unless an entry from org-file-apps that makes
10852 use of groups in a regexp matches.
10854 If you want to change the way frames are used when following a
10855 link, please customize `org-link-frame-setup'.
10857 If the file does not exist, an error is thrown."
10858 (let* ((file (if (equal path "")
10859 buffer-file-name
10860 (substitute-in-file-name (expand-file-name path))))
10861 (file-apps (append org-file-apps (org-default-apps)))
10862 (apps (cl-remove-if
10863 'org-file-apps-entry-match-against-dlink-p file-apps))
10864 (apps-dlink (cl-remove-if-not
10865 'org-file-apps-entry-match-against-dlink-p file-apps))
10866 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10867 (dirp (unless remp (file-directory-p file)))
10868 (file (if (and dirp org-open-directory-means-index-dot-org)
10869 (concat (file-name-as-directory file) "index.org")
10870 file))
10871 (a-m-a-p (assq 'auto-mode apps))
10872 (dfile (downcase file))
10873 ;; Reconstruct the original link from the PATH, LINE and
10874 ;; SEARCH args.
10875 (link (cond (line (concat file "::" (number-to-string line)))
10876 (search (concat file "::" search))
10877 (t file)))
10878 (dlink (downcase link))
10879 (ext
10880 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10881 (match-string 1 dfile)))
10882 (save-position-maybe
10883 (let ((old-buffer (current-buffer))
10884 (old-pos (point))
10885 (old-mode major-mode))
10886 (lambda ()
10887 (and (derived-mode-p 'org-mode)
10888 (eq old-mode 'org-mode)
10889 (or (not (eq old-buffer (current-buffer)))
10890 (not (eq old-pos (point))))
10891 (org-mark-ring-push old-pos old-buffer)))))
10892 cmd link-match-data)
10893 (cond
10894 ((member in-emacs '((16) system))
10895 (setq cmd (cdr (assq 'system apps))))
10896 (in-emacs (setq cmd 'emacs))
10898 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10899 (and dirp (cdr (assq 'directory apps)))
10900 ;; First, try matching against apps-dlink if we
10901 ;; get a match here, store the match data for
10902 ;; later.
10903 (let ((match (assoc-default dlink apps-dlink
10904 'string-match)))
10905 (if match
10906 (progn (setq link-match-data (match-data))
10907 match)
10908 (progn (setq in-emacs (or in-emacs line search))
10909 nil))) ; if we have no match in apps-dlink,
10910 ; always open the file in emacs if line or search
10911 ; is given (for backwards compatibility)
10912 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10913 'string-match)
10914 (cdr (assoc ext apps))
10915 (cdr (assq t apps))))))
10916 (when (eq cmd 'system)
10917 (setq cmd (cdr (assq 'system apps))))
10918 (when (eq cmd 'default)
10919 (setq cmd (cdr (assoc t apps))))
10920 (when (eq cmd 'mailcap)
10921 (require 'mailcap)
10922 (mailcap-parse-mailcaps)
10923 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10924 (command (mailcap-mime-info mime-type)))
10925 (if (stringp command)
10926 (setq cmd command)
10927 (setq cmd 'emacs))))
10928 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10929 (not (file-exists-p file))
10930 (not org-open-non-existing-files))
10931 (user-error "No such file: %s" file))
10932 (cond
10933 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10934 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10935 (while (string-match "['\"]%s['\"]" cmd)
10936 (setq cmd (replace-match "%s" t t cmd)))
10937 (setq cmd (replace-regexp-in-string
10938 "%s"
10939 (shell-quote-argument (convert-standard-filename file))
10941 nil t))
10943 ;; Replace "%1", "%2" etc. in command with group matches from regex
10944 (save-match-data
10945 (let ((match-index 1)
10946 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10947 (set-match-data link-match-data)
10948 (while (<= match-index number-of-groups)
10949 (let ((regex (concat "%" (number-to-string match-index)))
10950 (replace-with (match-string match-index dlink)))
10951 (while (string-match regex cmd)
10952 (setq cmd (replace-match replace-with t t cmd))))
10953 (setq match-index (+ match-index 1)))))
10955 (save-window-excursion
10956 (message "Running %s...done" cmd)
10957 (start-process-shell-command cmd nil cmd)
10958 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10959 ((or (stringp cmd)
10960 (eq cmd 'emacs))
10961 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10962 (widen)
10963 (cond (line (org-goto-line line)
10964 (when (derived-mode-p 'org-mode) (org-reveal)))
10965 (search (condition-case err
10966 (org-link-search search)
10967 ;; Save position before error-ing out so user
10968 ;; can easily move back to the original buffer.
10969 (error (funcall save-position-maybe)
10970 (error (nth 1 err)))))))
10971 ((functionp cmd)
10972 (save-match-data
10973 (set-match-data link-match-data)
10974 (condition-case nil
10975 (funcall cmd file link)
10976 ;; FIXME: Remove this check when most default installations
10977 ;; of Emacs have at least Org 9.0.
10978 ((debug wrong-number-of-arguments wrong-type-argument
10979 invalid-function)
10980 (user-error "Please see Org News for version 9.0 about \
10981 `org-file-apps'--Lisp error: %S" cmd)))))
10982 ((consp cmd)
10983 ;; FIXME: Remove this check when most default installations of
10984 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10985 ;; fall back to `org-link-frame-setup' for an old usage of
10986 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10987 (user-error "Please see Org News for version 9.0 about \
10988 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10989 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10990 (funcall save-position-maybe)))
10992 (defun org-file-apps-entry-match-against-dlink-p (entry)
10993 "This function returns non-nil if `entry' uses a regular
10994 expression which should be matched against the whole link by
10995 org-open-file.
10997 It assumes that is the case when the entry uses a regular
10998 expression which has at least one grouping construct and the
10999 action is either a lisp form or a command string containing
11000 `%1', i.e. using at least one subexpression match as a
11001 parameter."
11002 (let ((selector (car entry))
11003 (action (cdr entry)))
11004 (if (stringp selector)
11005 (and (> (regexp-opt-depth selector) 0)
11006 (or (and (stringp action)
11007 (string-match "%[0-9]" action))
11008 (consp action)))
11009 nil)))
11011 (defun org-default-apps ()
11012 "Return the default applications for this operating system."
11013 (cond
11014 ((eq system-type 'darwin)
11015 org-file-apps-defaults-macosx)
11016 ((eq system-type 'windows-nt)
11017 org-file-apps-defaults-windowsnt)
11018 (t org-file-apps-defaults-gnu)))
11020 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11021 "Convert extensions to regular expressions in the cars of LIST.
11022 Also, weed out any non-string entries, because the return value is used
11023 only for regexp matching.
11024 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11025 point to the symbol `emacs', indicating that the file should
11026 be opened in Emacs."
11027 (append
11028 (delq nil
11029 (mapcar (lambda (x)
11030 (unless (not (stringp (car x)))
11031 (if (string-match "\\W" (car x))
11033 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11034 list))
11035 (when add-auto-mode
11036 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11038 (defvar ange-ftp-name-format)
11039 (defun org-file-remote-p (file)
11040 "Test whether FILE specifies a location on a remote system.
11041 Return non-nil if the location is indeed remote.
11043 For example, the filename \"/user@host:/foo\" specifies a location
11044 on the system \"/user@host:\"."
11045 (cond ((fboundp 'file-remote-p)
11046 (file-remote-p file))
11047 ((fboundp 'tramp-handle-file-remote-p)
11048 (tramp-handle-file-remote-p file))
11049 ((and (boundp 'ange-ftp-name-format)
11050 (string-match (car ange-ftp-name-format) file))
11051 t)))
11054 ;;;; Refiling
11056 (defun org-get-org-file ()
11057 "Read a filename, with default directory `org-directory'."
11058 (let ((default (or org-default-notes-file remember-data-file)))
11059 (read-file-name (format "File name [%s]: " default)
11060 (file-name-as-directory org-directory)
11061 default)))
11063 (defun org-notes-order-reversed-p ()
11064 "Check if the current file should receive notes in reversed order."
11065 (cond
11066 ((not org-reverse-note-order) nil)
11067 ((eq t org-reverse-note-order) t)
11068 ((not (listp org-reverse-note-order)) nil)
11069 (t (catch 'exit
11070 (dolist (entry org-reverse-note-order)
11071 (when (string-match (car entry) buffer-file-name)
11072 (throw 'exit (cdr entry))))))))
11074 (defvar org-refile-target-table nil
11075 "The list of refile targets, created by `org-refile'.")
11077 (defvar org-agenda-new-buffers nil
11078 "Buffers created to visit agenda files.")
11080 (defvar org-refile-cache nil
11081 "Cache for refile targets.")
11083 (defvar org-refile-markers nil
11084 "All the markers used for caching refile locations.")
11086 (defun org-refile-marker (pos)
11087 "Get a new refile marker, but only if caching is in use."
11088 (if (not org-refile-use-cache)
11090 (let ((m (make-marker)))
11091 (move-marker m pos)
11092 (push m org-refile-markers)
11093 m)))
11095 (defun org-refile-cache-clear ()
11096 "Clear the refile cache and disable all the markers."
11097 (dolist (m org-refile-markers) (move-marker m nil))
11098 (setq org-refile-markers nil)
11099 (setq org-refile-cache nil)
11100 (message "Refile cache has been cleared"))
11102 (defun org-refile-cache-check-set (set)
11103 "Check if all the markers in the cache still have live buffers."
11104 (let (marker)
11105 (catch 'exit
11106 (while (and set (setq marker (nth 3 (pop set))))
11107 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11108 (when (and marker (null (marker-buffer marker)))
11109 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11110 (sit-for 3)
11111 (throw 'exit nil)))
11112 t)))
11114 (defun org-refile-cache-put (set &rest identifiers)
11115 "Push the refile targets SET into the cache, under IDENTIFIERS."
11116 (let* ((key (sha1 (prin1-to-string identifiers)))
11117 (entry (assoc key org-refile-cache)))
11118 (if entry
11119 (setcdr entry set)
11120 (push (cons key set) org-refile-cache))))
11122 (defun org-refile-cache-get (&rest identifiers)
11123 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11124 (cond
11125 ((not org-refile-cache) nil)
11126 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11128 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11129 org-refile-cache))))
11130 (and set (org-refile-cache-check-set set) set)))))
11132 (defvar org-outline-path-cache nil
11133 "Alist between buffer positions and outline paths.
11134 It value is an alist (POSITION . PATH) where POSITION is the
11135 buffer position at the beginning of an entry and PATH is a list
11136 of strings describing the outline path for that entry, in reverse
11137 order.")
11139 (defun org-refile-get-targets (&optional default-buffer)
11140 "Produce a table with refile targets."
11141 (let ((case-fold-search nil)
11142 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11143 (entries (or org-refile-targets '((nil . (:level . 1)))))
11144 targets tgs files desc descre)
11145 (message "Getting targets...")
11146 (with-current-buffer (or default-buffer (current-buffer))
11147 (dolist (entry entries)
11148 (setq files (car entry) desc (cdr entry))
11149 (cond
11150 ((null files) (setq files (list (current-buffer))))
11151 ((eq files 'org-agenda-files)
11152 (setq files (org-agenda-files 'unrestricted)))
11153 ((and (symbolp files) (fboundp files))
11154 (setq files (funcall files)))
11155 ((and (symbolp files) (boundp files))
11156 (setq files (symbol-value files))))
11157 (when (stringp files) (setq files (list files)))
11158 (cond
11159 ((eq (car desc) :tag)
11160 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11161 ((eq (car desc) :todo)
11162 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11163 ((eq (car desc) :regexp)
11164 (setq descre (cdr desc)))
11165 ((eq (car desc) :level)
11166 (setq descre (concat "^\\*\\{" (number-to-string
11167 (if org-odd-levels-only
11168 (1- (* 2 (cdr desc)))
11169 (cdr desc)))
11170 "\\}[ \t]")))
11171 ((eq (car desc) :maxlevel)
11172 (setq descre (concat "^\\*\\{1," (number-to-string
11173 (if org-odd-levels-only
11174 (1- (* 2 (cdr desc)))
11175 (cdr desc)))
11176 "\\}[ \t]")))
11177 (t (error "Bad refiling target description %s" desc)))
11178 (dolist (f files)
11179 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11181 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11182 (progn
11183 (when (bufferp f)
11184 (setq f (buffer-file-name (buffer-base-buffer f))))
11185 (setq f (and f (expand-file-name f)))
11186 (when (eq org-refile-use-outline-path 'file)
11187 (push (list (file-name-nondirectory f) f nil nil) tgs))
11188 (when (eq org-refile-use-outline-path 'buffer-name)
11189 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11190 (when (eq org-refile-use-outline-path 'full-file-path)
11191 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11192 (org-with-wide-buffer
11193 (goto-char (point-min))
11194 (setq org-outline-path-cache nil)
11195 (while (re-search-forward descre nil t)
11196 (beginning-of-line)
11197 (let ((case-fold-search nil))
11198 (looking-at org-complex-heading-regexp))
11199 (let ((begin (point))
11200 (heading (match-string-no-properties 4)))
11201 (unless (or (and
11202 org-refile-target-verify-function
11203 (not
11204 (funcall org-refile-target-verify-function)))
11205 (not heading))
11206 (let ((re (format org-complex-heading-regexp-format
11207 (regexp-quote heading)))
11208 (target
11209 (if (not org-refile-use-outline-path) heading
11210 (mapconcat
11211 #'identity
11212 (append
11213 (pcase org-refile-use-outline-path
11214 (`file (list (file-name-nondirectory
11215 (buffer-file-name
11216 (buffer-base-buffer)))))
11217 (`full-file-path
11218 (list (buffer-file-name
11219 (buffer-base-buffer))))
11220 (`buffer-name
11221 (list (buffer-name
11222 (buffer-base-buffer))))
11223 (_ nil))
11224 (mapcar (lambda (s) (replace-regexp-in-string
11225 "/" "\\/" s nil t))
11226 (org-get-outline-path t t)))
11227 "/"))))
11228 (push (list target f re (org-refile-marker (point)))
11229 tgs)))
11230 (when (= (point) begin)
11231 ;; Verification function has not moved point.
11232 (end-of-line)))))))
11233 (when org-refile-use-cache
11234 (org-refile-cache-put tgs (buffer-file-name) descre))
11235 (setq targets (append tgs targets))))))
11236 (message "Getting targets...done")
11237 (delete-dups (nreverse targets))))
11239 (defun org--get-outline-path-1 (&optional use-cache)
11240 "Return outline path to current headline.
11242 Outline path is a list of strings, in reverse order. When
11243 optional argument USE-CACHE is non-nil, make use of a cache. See
11244 `org-get-outline-path' for details.
11246 Assume buffer is widened and point is on a headline."
11247 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11248 (let ((p (point))
11249 (heading (let ((case-fold-search nil))
11250 (looking-at org-complex-heading-regexp)
11251 (if (not (match-end 4)) ""
11252 ;; Remove statistics cookies.
11253 (org-trim
11254 (org-link-display-format
11255 (replace-regexp-in-string
11256 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11257 (match-string-no-properties 4))))))))
11258 (if (org-up-heading-safe)
11259 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11260 (when use-cache
11261 (push (cons p path) org-outline-path-cache))
11262 path)
11263 ;; This is a new root node. Since we assume we are moving
11264 ;; forward, we can drop previous cache so as to limit number
11265 ;; of associations there.
11266 (let ((path (list heading)))
11267 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11268 path)))))
11270 (defun org-get-outline-path (&optional with-self use-cache)
11271 "Return the outline path to the current entry.
11273 An outline path is a list of ancestors for current headline, as
11274 a list of strings. Statistics cookies are removed and links are
11275 replaced with their description, if any, or their path otherwise.
11277 When optional argument WITH-SELF is non-nil, the path also
11278 includes the current headline.
11280 When optional argument USE-CACHE is non-nil, cache outline paths
11281 between calls to this function so as to avoid backtracking. This
11282 argument is useful when planning to find more than one outline
11283 path in the same document. In that case, there are two
11284 conditions to satisfy:
11285 - `org-outline-path-cache' is set to nil before starting the
11286 process;
11287 - outline paths are computed by increasing buffer positions."
11288 (org-with-wide-buffer
11289 (and (or (and with-self (org-back-to-heading t))
11290 (org-up-heading-safe))
11291 (reverse (org--get-outline-path-1 use-cache)))))
11293 (defun org-format-outline-path (path &optional width prefix separator)
11294 "Format the outline path PATH for display.
11295 WIDTH is the maximum number of characters that is available.
11296 PREFIX is a prefix to be included in the returned string,
11297 such as the file name.
11298 SEPARATOR is inserted between the different parts of the path,
11299 the default is \"/\"."
11300 (setq width (or width 79))
11301 (setq path (delq nil path))
11302 (unless (> width 0)
11303 (user-error "Argument `width' must be positive"))
11304 (setq separator (or separator "/"))
11305 (let* ((org-odd-levels-only nil)
11306 (fpath (concat
11307 prefix (and prefix path separator)
11308 (mapconcat
11309 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11310 (cl-loop for head in path
11311 for n from 0
11312 collect (org-add-props
11313 head nil 'face
11314 (nth (% n org-n-level-faces) org-level-faces)))
11315 separator))))
11316 (when (> (length fpath) width)
11317 (if (< width 7)
11318 ;; It's unlikely that `width' will be this small, but don't
11319 ;; waste characters by adding ".." if it is.
11320 (setq fpath (substring fpath 0 width))
11321 (setf (substring fpath (- width 2)) "..")))
11322 fpath))
11324 (defun org-display-outline-path (&optional file current separator just-return-string)
11325 "Display the current outline path in the echo area.
11327 If FILE is non-nil, prepend the output with the file name.
11328 If CURRENT is non-nil, append the current heading to the output.
11329 SEPARATOR is passed through to `org-format-outline-path'. It separates
11330 the different parts of the path and defaults to \"/\".
11331 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11332 (interactive "P")
11333 (let* (case-fold-search
11334 (bfn (buffer-file-name (buffer-base-buffer)))
11335 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11336 res)
11337 (when current (setq path (append path
11338 (save-excursion
11339 (org-back-to-heading t)
11340 (when (looking-at org-complex-heading-regexp)
11341 (list (match-string 4)))))))
11342 (setq res
11343 (org-format-outline-path
11344 path
11345 (1- (frame-width))
11346 (and file bfn (concat (file-name-nondirectory bfn) separator))
11347 separator))
11348 (if just-return-string
11349 (org-no-properties res)
11350 (org-unlogged-message "%s" res))))
11352 (defvar org-refile-history nil
11353 "History for refiling operations.")
11355 (defvar org-after-refile-insert-hook nil
11356 "Hook run after `org-refile' has inserted its stuff at the new location.
11357 Note that this is still *before* the stuff will be removed from
11358 the *old* location.")
11360 (defvar org-capture-last-stored-marker)
11361 (defvar org-refile-keep nil
11362 "Non-nil means `org-refile' will copy instead of refile.")
11364 (defun org-copy ()
11365 "Like `org-refile', but copy."
11366 (interactive)
11367 (let ((org-refile-keep t))
11368 (funcall 'org-refile nil nil nil "Copy")))
11370 (defun org-refile (&optional arg default-buffer rfloc msg)
11371 "Move the entry or entries at point to another heading.
11373 The list of target headings is compiled using the information in
11374 `org-refile-targets', which see.
11376 At the target location, the entry is filed as a subitem of the
11377 target heading. Depending on `org-reverse-note-order', the new
11378 subitem will either be the first or the last subitem.
11380 If there is an active region, all entries in that region will be
11381 refiled. However, the region must fulfill the requirement that
11382 the first heading sets the top-level of the moved text.
11384 With a `\\[universal-argument]' ARG, the command will only visit the target \
11385 location
11386 and not actually move anything.
11388 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11389 location where the last
11390 refiling operation has put the subtree.
11392 With a numeric prefix argument of `2', refile to the running clock.
11394 With a numeric prefix argument of `3', emulate `org-refile-keep'
11395 being set to t and copy to the target location, don't move it.
11396 Beware that keeping refiled entries may result in duplicated ID
11397 properties.
11399 RFLOC can be a refile location obtained in a different way.
11401 MSG is a string to replace \"Refile\" in the default prompt with
11402 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11404 See also `org-refile-use-outline-path'.
11406 If you are using target caching (see `org-refile-use-cache'), you
11407 have to clear the target cache in order to find new targets.
11408 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11409 prefix argument (`C-u C-u C-u C-c C-w')."
11410 (interactive "P")
11411 (if (member arg '(0 (64)))
11412 (org-refile-cache-clear)
11413 (let* ((actionmsg (cond (msg msg)
11414 ((equal arg 3) "Refile (and keep)")
11415 (t "Refile")))
11416 (regionp (org-region-active-p))
11417 (region-start (and regionp (region-beginning)))
11418 (region-end (and regionp (region-end)))
11419 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11420 pos it nbuf file level reversed)
11421 (setq last-command nil)
11422 (when regionp
11423 (goto-char region-start)
11424 (or (bolp) (goto-char (point-at-bol)))
11425 (setq region-start (point))
11426 (unless (or (org-kill-is-subtree-p
11427 (buffer-substring region-start region-end))
11428 (prog1 org-refile-active-region-within-subtree
11429 (let ((s (point-at-eol)))
11430 (org-toggle-heading)
11431 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11432 (user-error "The region is not a (sequence of) subtree(s)")))
11433 (if (equal arg '(16))
11434 (org-refile-goto-last-stored)
11435 (when (or
11436 (and (equal arg 2)
11437 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11438 (prog1
11439 (setq it (list (or org-clock-heading "running clock")
11440 (buffer-file-name
11441 (marker-buffer org-clock-hd-marker))
11443 (marker-position org-clock-hd-marker)))
11444 (setq arg nil)))
11445 (setq it
11446 (or rfloc
11447 (let (heading-text)
11448 (save-excursion
11449 (unless (and arg (listp arg))
11450 (org-back-to-heading t)
11451 (setq heading-text
11452 (replace-regexp-in-string
11453 org-bracket-link-regexp
11454 "\\3"
11455 (or (nth 4 (org-heading-components))
11456 ""))))
11457 (org-refile-get-location
11458 (cond ((and arg (listp arg)) "Goto")
11459 (regionp (concat actionmsg " region to"))
11460 (t (concat actionmsg " subtree \""
11461 heading-text "\" to")))
11462 default-buffer
11463 (and (not (equal '(4) arg))
11464 org-refile-allow-creating-parent-nodes)))))))
11465 (setq file (nth 1 it)
11466 pos (nth 3 it))
11467 (when (and (not arg)
11469 (equal (buffer-file-name) file)
11470 (if regionp
11471 (and (>= pos region-start)
11472 (<= pos region-end))
11473 (and (>= pos (point))
11474 (< pos (save-excursion
11475 (org-end-of-subtree t t))))))
11476 (error "Cannot refile to position inside the tree or region"))
11477 (setq nbuf (or (find-buffer-visiting file)
11478 (find-file-noselect file)))
11479 (if (and arg (not (equal arg 3)))
11480 (progn
11481 (pop-to-buffer-same-window nbuf)
11482 (goto-char (cond (pos)
11483 ((org-notes-order-reversed-p) (point-min))
11484 (t (point-max))))
11485 (org-show-context 'org-goto))
11486 (if regionp
11487 (progn
11488 (org-kill-new (buffer-substring region-start region-end))
11489 (org-save-markers-in-region region-start region-end))
11490 (org-copy-subtree 1 nil t))
11491 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11492 (find-file-noselect file)))
11493 (setq reversed (org-notes-order-reversed-p))
11494 (org-with-wide-buffer
11495 (if pos
11496 (progn
11497 (goto-char pos)
11498 (setq level (org-get-valid-level (funcall outline-level) 1))
11499 (goto-char
11500 (if reversed
11501 (or (outline-next-heading) (point-max))
11502 (or (save-excursion (org-get-next-sibling))
11503 (org-end-of-subtree t t)
11504 (point-max)))))
11505 (setq level 1)
11506 (if (not reversed)
11507 (goto-char (point-max))
11508 (goto-char (point-min))
11509 (or (outline-next-heading) (goto-char (point-max)))))
11510 (unless (bolp) (newline))
11511 (org-paste-subtree level nil nil t)
11512 (when org-log-refile
11513 (org-add-log-setup 'refile nil nil org-log-refile)
11514 (unless (eq org-log-refile 'note)
11515 (save-excursion (org-add-log-note))))
11516 (and org-auto-align-tags
11517 (let ((org-loop-over-headlines-in-active-region nil))
11518 (org-set-tags nil t)))
11519 (let ((bookmark-name (plist-get org-bookmark-names-plist
11520 :last-refile)))
11521 (when bookmark-name
11522 (with-demoted-errors
11523 (bookmark-set bookmark-name))))
11524 ;; If we are refiling for capture, make sure that the
11525 ;; last-capture pointers point here
11526 (when (bound-and-true-p org-capture-is-refiling)
11527 (let ((bookmark-name (plist-get org-bookmark-names-plist
11528 :last-capture-marker)))
11529 (when bookmark-name
11530 (with-demoted-errors
11531 (bookmark-set bookmark-name))))
11532 (move-marker org-capture-last-stored-marker (point)))
11533 (when (fboundp 'deactivate-mark) (deactivate-mark))
11534 (run-hooks 'org-after-refile-insert-hook)))
11535 (unless org-refile-keep
11536 (if regionp
11537 (delete-region (point) (+ (point) (- region-end region-start)))
11538 (delete-region
11539 (and (org-back-to-heading t) (point))
11540 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11541 (when (featurep 'org-inlinetask)
11542 (org-inlinetask-remove-END-maybe))
11543 (setq org-markers-to-move nil)
11544 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11546 (defun org-refile-goto-last-stored ()
11547 "Go to the location where the last refile was stored."
11548 (interactive)
11549 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11550 (message "This is the location of the last refile"))
11552 (defun org-refile--get-location (refloc tbl)
11553 "When user refile to REFLOC, find the associated target in TBL.
11554 Also check `org-refile-target-table'."
11555 (car (delq
11557 (mapcar
11558 (lambda (r) (or (assoc r tbl)
11559 (assoc r org-refile-target-table)))
11560 (list (replace-regexp-in-string "/$" "" refloc)
11561 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11563 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11564 "Prompt the user for a refile location, using PROMPT.
11565 PROMPT should not be suffixed with a colon and a space, because
11566 this function appends the default value from
11567 `org-refile-history' automatically, if that is not empty."
11568 (let ((org-refile-targets org-refile-targets)
11569 (org-refile-use-outline-path org-refile-use-outline-path))
11570 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11571 (unless org-refile-target-table
11572 (user-error "No refile targets"))
11573 (let* ((cbuf (current-buffer))
11574 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11575 (cfunc (if (and org-refile-use-outline-path
11576 org-outline-path-complete-in-steps)
11577 #'org-olpath-completing-read
11578 #'completing-read))
11579 (extra (if org-refile-use-outline-path "/" ""))
11580 (cbnex (concat (buffer-name) extra))
11581 (filename (and cfn (expand-file-name cfn)))
11582 (tbl (mapcar
11583 (lambda (x)
11584 (if (and (not (member org-refile-use-outline-path
11585 '(file full-file-path)))
11586 (not (equal filename (nth 1 x))))
11587 (cons (concat (car x) extra " ("
11588 (file-name-nondirectory (nth 1 x)) ")")
11589 (cdr x))
11590 (cons (concat (car x) extra) (cdr x))))
11591 org-refile-target-table))
11592 (completion-ignore-case t)
11593 cdef
11594 (prompt (concat prompt
11595 (or (and (car org-refile-history)
11596 (concat " (default " (car org-refile-history) ")"))
11597 (and (assoc cbnex tbl) (setq cdef cbnex)
11598 (concat " (default " cbnex ")"))) ": "))
11599 pa answ parent-target child parent old-hist)
11600 (setq old-hist org-refile-history)
11601 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11602 nil 'org-refile-history (or cdef (car org-refile-history))))
11603 (if (setq pa (org-refile--get-location answ tbl))
11604 (progn
11605 (org-refile-check-position pa)
11606 (when (or (not org-refile-history)
11607 (not (eq old-hist org-refile-history))
11608 (not (equal (car pa) (car org-refile-history))))
11609 (setq org-refile-history
11610 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11611 org-refile-history
11612 (cdr org-refile-history))))
11613 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11614 (pop org-refile-history)))
11616 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11617 (progn
11618 (setq parent (match-string 1 answ)
11619 child (match-string 2 answ))
11620 (setq parent-target (org-refile--get-location parent tbl))
11621 (when (and parent-target
11622 (or (eq new-nodes t)
11623 (and (eq new-nodes 'confirm)
11624 (y-or-n-p (format "Create new node \"%s\"? "
11625 child)))))
11626 (org-refile-new-child parent-target child)))
11627 (user-error "Invalid target location")))))
11629 (declare-function org-string-nw-p "org-macs" (s))
11630 (defun org-refile-check-position (refile-pointer)
11631 "Check if the refile pointer matches the headline to which it points."
11632 (let* ((file (nth 1 refile-pointer))
11633 (re (nth 2 refile-pointer))
11634 (pos (nth 3 refile-pointer))
11635 buffer)
11636 (if (and (not (markerp pos)) (not file))
11637 (user-error "Please indicate a target file in the refile path")
11638 (when (org-string-nw-p re)
11639 (setq buffer (if (markerp pos)
11640 (marker-buffer pos)
11641 (or (find-buffer-visiting file)
11642 (find-file-noselect file))))
11643 (with-current-buffer buffer
11644 (org-with-wide-buffer
11645 (goto-char pos)
11646 (beginning-of-line 1)
11647 (unless (looking-at-p re)
11648 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11650 (defun org-refile-new-child (parent-target child)
11651 "Use refile target PARENT-TARGET to add new CHILD below it."
11652 (unless parent-target
11653 (error "Cannot find parent for new node"))
11654 (let ((file (nth 1 parent-target))
11655 (pos (nth 3 parent-target))
11656 level)
11657 (with-current-buffer (or (find-buffer-visiting file)
11658 (find-file-noselect file))
11659 (org-with-wide-buffer
11660 (if pos
11661 (goto-char pos)
11662 (goto-char (point-max))
11663 (unless (bolp) (newline)))
11664 (when (looking-at org-outline-regexp)
11665 (setq level (funcall outline-level))
11666 (org-end-of-subtree t t))
11667 (org-back-over-empty-lines)
11668 (insert "\n" (make-string
11669 (if pos (org-get-valid-level level 1) 1) ?*)
11670 " " child "\n")
11671 (beginning-of-line 0)
11672 (list (concat (car parent-target) "/" child) file "" (point))))))
11674 (defun org-olpath-completing-read (prompt collection &rest args)
11675 "Read an outline path like a file name."
11676 (let ((thetable collection))
11677 (apply #'completing-read
11678 prompt
11679 (lambda (string predicate &optional flag)
11680 (cond
11681 ((eq flag nil) (try-completion string thetable))
11682 ((eq flag t)
11683 (let ((l (length string)))
11684 (mapcar (lambda (x)
11685 (let ((r (substring x l))
11686 (f (if (string-match " ([^)]*)$" x)
11687 (match-string 0 x)
11688 "")))
11689 (if (string-match "/" r)
11690 (concat string (substring r 0 (match-end 0)) f)
11691 x)))
11692 (all-completions string thetable predicate))))
11693 ;; Exact match?
11694 ((eq flag 'lambda) (assoc string thetable))))
11695 args)))
11697 ;;;; Dynamic blocks
11699 (defun org-find-dblock (name)
11700 "Find the first dynamic block with name NAME in the buffer.
11701 If not found, stay at current position and return nil."
11702 (let ((case-fold-search t) pos)
11703 (save-excursion
11704 (goto-char (point-min))
11705 (setq pos (and (re-search-forward
11706 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11707 (match-beginning 0))))
11708 (when pos (goto-char pos))
11709 pos))
11711 (defun org-create-dblock (plist)
11712 "Create a dynamic block section, with parameters taken from PLIST.
11713 PLIST must contain a :name entry which is used as the name of the block."
11714 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11715 (end-of-line 1)
11716 (newline))
11717 (let ((col (current-column))
11718 (name (plist-get plist :name)))
11719 (insert "#+BEGIN: " name)
11720 (while plist
11721 (if (eq (car plist) :name)
11722 (setq plist (cddr plist))
11723 (insert " " (prin1-to-string (pop plist)))))
11724 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11725 (beginning-of-line -2)))
11727 (defun org-prepare-dblock ()
11728 "Prepare dynamic block for refresh.
11729 This empties the block, puts the cursor at the insert position and returns
11730 the property list including an extra property :name with the block name."
11731 (unless (looking-at org-dblock-start-re)
11732 (user-error "Not at a dynamic block"))
11733 (let* ((begdel (1+ (match-end 0)))
11734 (name (org-no-properties (match-string 1)))
11735 (params (append (list :name name)
11736 (read (concat "(" (match-string 3) ")")))))
11737 (save-excursion
11738 (beginning-of-line 1)
11739 (skip-chars-forward " \t")
11740 (setq params (plist-put params :indentation-column (current-column))))
11741 (unless (re-search-forward org-dblock-end-re nil t)
11742 (error "Dynamic block not terminated"))
11743 (setq params
11744 (append params
11745 (list :content (buffer-substring
11746 begdel (match-beginning 0)))))
11747 (delete-region begdel (match-beginning 0))
11748 (goto-char begdel)
11749 (open-line 1)
11750 params))
11752 (defun org-map-dblocks (&optional command)
11753 "Apply COMMAND to all dynamic blocks in the current buffer.
11754 If COMMAND is not given, use `org-update-dblock'."
11755 (let ((cmd (or command 'org-update-dblock)))
11756 (save-excursion
11757 (goto-char (point-min))
11758 (while (re-search-forward org-dblock-start-re nil t)
11759 (goto-char (match-beginning 0))
11760 (save-excursion
11761 (condition-case nil
11762 (funcall cmd)
11763 (error (message "Error during update of dynamic block"))))
11764 (unless (re-search-forward org-dblock-end-re nil t)
11765 (error "Dynamic block not terminated"))))))
11767 (defun org-dblock-update (&optional arg)
11768 "User command for updating dynamic blocks.
11769 Update the dynamic block at point. With prefix ARG, update all dynamic
11770 blocks in the buffer."
11771 (interactive "P")
11772 (if arg
11773 (org-update-all-dblocks)
11774 (or (looking-at org-dblock-start-re)
11775 (org-beginning-of-dblock))
11776 (org-update-dblock)))
11778 (defun org-update-dblock ()
11779 "Update the dynamic block at point.
11780 This means to empty the block, parse for parameters and then call
11781 the correct writing function."
11782 (interactive)
11783 (save-excursion
11784 (let* ((win (selected-window))
11785 (pos (point))
11786 (line (org-current-line))
11787 (params (org-prepare-dblock))
11788 (name (plist-get params :name))
11789 (indent (plist-get params :indentation-column))
11790 (cmd (intern (concat "org-dblock-write:" name))))
11791 (message "Updating dynamic block `%s' at line %d..." name line)
11792 (funcall cmd params)
11793 (message "Updating dynamic block `%s' at line %d...done" name line)
11794 (goto-char pos)
11795 (when (and indent (> indent 0))
11796 (setq indent (make-string indent ?\ ))
11797 (save-excursion
11798 (select-window win)
11799 (org-beginning-of-dblock)
11800 (forward-line 1)
11801 (while (not (looking-at org-dblock-end-re))
11802 (insert indent)
11803 (beginning-of-line 2))
11804 (when (looking-at org-dblock-end-re)
11805 (and (looking-at "[ \t]+")
11806 (replace-match ""))
11807 (insert indent)))))))
11809 (defun org-beginning-of-dblock ()
11810 "Find the beginning of the dynamic block at point.
11811 Error if there is no such block at point."
11812 (let ((pos (point))
11813 beg)
11814 (end-of-line 1)
11815 (if (and (re-search-backward org-dblock-start-re nil t)
11816 (setq beg (match-beginning 0))
11817 (re-search-forward org-dblock-end-re nil t)
11818 (> (match-end 0) pos))
11819 (goto-char beg)
11820 (goto-char pos)
11821 (error "Not in a dynamic block"))))
11823 (defun org-update-all-dblocks ()
11824 "Update all dynamic blocks in the buffer.
11825 This function can be used in a hook."
11826 (interactive)
11827 (when (derived-mode-p 'org-mode)
11828 (org-map-dblocks 'org-update-dblock)))
11831 ;;;; Completion
11833 (declare-function org-export-backend-options "ox" (cl-x) t)
11834 (defun org-get-export-keywords ()
11835 "Return a list of all currently understood export keywords.
11836 Export keywords include options, block names, attributes and
11837 keywords relative to each registered export back-end."
11838 (let (keywords)
11839 (dolist (backend
11840 (bound-and-true-p org-export-registered-backends)
11841 (delq nil keywords))
11842 ;; Back-end name (for keywords, like #+LATEX:)
11843 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11844 (dolist (option-entry (org-export-backend-options backend))
11845 ;; Back-end options.
11846 (push (nth 1 option-entry) keywords)))))
11848 (defconst org-options-keywords
11849 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11850 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11851 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11852 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11853 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11855 (defcustom org-structure-template-alist
11856 '((?a . "export ascii")
11857 (?c . "center")
11858 (?C . "comment")
11859 (?e . "example")
11860 (?E . "export")
11861 (?h . "export html")
11862 (?l . "export latex")
11863 (?q . "quote")
11864 (?s . "src")
11865 (?v . "verse"))
11866 "Structure completion elements.
11867 This is an alist of characters and values. When
11868 `org-insert-structure-template' is called, an additional key is
11869 read. The key is first looked up in this alist, and the
11870 corresponding structure is inserted, with \"#+BEGIN_\" and
11871 \"#+END_\" added automatically."
11872 :group 'org-completion
11873 :type '(repeat
11874 (cons (character :tag "Key")
11875 (string :tag "Template")))
11876 :package-version '(Org . "9.2"))
11878 (defun org-insert-structure-template (type)
11879 "Insert a block structure of the type #+begin_foo/#+end_foo.
11880 First read a character, which can be one of the keys in
11881 `org-structure-template-alist'. When it is <TAB>, prompt the
11882 user for a string to use. With an active region, wrap the region
11883 in the block. Otherwise, insert an empty block."
11884 (interactive
11885 (list
11886 (let* ((key (read-key "Key: "))
11887 (struct-string
11888 (or (cdr (assq key org-structure-template-alist))
11889 (and (= key ?\t)
11890 (read-string "Structure type: "))
11891 (user-error "`%c' has no structure definition" key))))
11892 struct-string)))
11893 (let* ((region? (use-region-p))
11894 (s (if region? (region-beginning) (point)))
11895 (e (copy-marker (if region? (region-end) (point)) t))
11896 column)
11897 (when (string-match-p
11898 (concat "\\`" (regexp-opt '("example" "export" "src")))
11899 type)
11900 (org-escape-code-in-region s e))
11901 (goto-char s)
11902 (setq column (current-indentation))
11903 (beginning-of-line)
11904 (indent-to column)
11905 (insert (format "#+begin_%s\n" type))
11906 (goto-char e)
11907 (if (bolp)
11908 (progn
11909 (skip-chars-backward " \n\t")
11910 (forward-line))
11911 (end-of-line)
11912 (insert "\n"))
11913 (indent-to column)
11914 (insert (format "#+end_%s\n"
11915 (car (split-string type))))
11916 (when (or (not region?)
11917 (string-match-p "src\\|\\`export\\'" type))
11918 (goto-char s)
11919 (end-of-line))
11920 (set-marker e nil)))
11922 ;;;; TODO, DEADLINE, Comments
11924 (defun org-toggle-comment ()
11925 "Change the COMMENT state of an entry."
11926 (interactive)
11927 (save-excursion
11928 (org-back-to-heading)
11929 (let ((case-fold-search nil))
11930 (looking-at org-complex-heading-regexp))
11931 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11932 (skip-chars-forward " \t")
11933 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11934 (if (org-in-commented-heading-p t)
11935 (delete-region (point)
11936 (progn (search-forward " " (line-end-position) 'move)
11937 (skip-chars-forward " \t")
11938 (point)))
11939 (insert org-comment-string)
11940 (unless (eolp) (insert " ")))))
11942 (defvar org-last-todo-state-is-todo nil
11943 "This is non-nil when the last TODO state change led to a TODO state.
11944 If the last change removed the TODO tag or switched to DONE, then
11945 this is nil.")
11947 (defvar org-setting-tags nil) ; dynamically skipped
11949 (defvar org-todo-setup-filter-hook nil
11950 "Hook for functions that pre-filter todo specs.
11951 Each function takes a todo spec and returns either nil or the spec
11952 transformed into canonical form." )
11954 (defvar org-todo-get-default-hook nil
11955 "Hook for functions that get a default item for todo.
11956 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11957 nil or a string to be used for the todo mark." )
11959 (defvar org-agenda-headline-snapshot-before-repeat)
11961 (defun org-current-effective-time ()
11962 "Return current time adjusted for `org-extend-today-until' variable."
11963 (let* ((ct (org-current-time))
11964 (dct (decode-time ct))
11965 (ct1
11966 (cond
11967 (org-use-last-clock-out-time-as-effective-time
11968 (or (org-clock-get-last-clock-out-time) ct))
11969 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11970 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11971 (t ct))))
11972 ct1))
11974 (defun org-todo-yesterday (&optional arg)
11975 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11976 (interactive "P")
11977 (if (eq major-mode 'org-agenda-mode)
11978 (apply 'org-agenda-todo-yesterday arg)
11979 (let* ((org-use-effective-time t)
11980 (hour (nth 2 (decode-time (org-current-time))))
11981 (org-extend-today-until (1+ hour)))
11982 (org-todo arg))))
11984 (defvar org-block-entry-blocking ""
11985 "First entry preventing the TODO state change.")
11987 (defun org-cancel-repeater ()
11988 "Cancel a repeater by setting its numeric value to zero."
11989 (interactive)
11990 (save-excursion
11991 (org-back-to-heading t)
11992 (let ((bound1 (point))
11993 (bound0 (save-excursion (outline-next-heading) (point))))
11994 (when (and (re-search-forward
11995 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11996 org-deadline-time-regexp "\\)\\|\\("
11997 org-ts-regexp "\\)")
11998 bound0 t)
11999 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12000 bound1 t))
12001 (replace-match "0" t nil nil 1)))))
12003 (defvar org-state)
12004 (defvar org-blocked-by-checkboxes)
12005 (defun org-todo (&optional arg)
12006 "Change the TODO state of an item.
12008 The state of an item is given by a keyword at the start of the heading,
12009 like
12010 *** TODO Write paper
12011 *** DONE Call mom
12013 The different keywords are specified in the variable `org-todo-keywords'.
12014 By default the available states are \"TODO\" and \"DONE\". So, for this
12015 example: when the item starts with TODO, it is changed to DONE.
12016 When it starts with DONE, the DONE is removed. And when neither TODO nor
12017 DONE are present, add TODO at the beginning of the heading.
12019 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12020 state.
12021 With numeric prefix ARG, switch to that state.
12022 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12023 next set of TODO \
12024 keywords (nextset).
12025 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12026 prefix, circumvent any state blocking.
12027 With a numeric prefix arg of 0, inhibit note taking for the change.
12028 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12030 When called through ELisp, arg is also interpreted in the following way:
12031 `none' -> empty state
12032 \"\" -> switch to empty state
12033 `done' -> switch to DONE
12034 `nextset' -> switch to the next set of keywords
12035 `previousset' -> switch to the previous set of keywords
12036 \"WAITING\" -> switch to the specified keyword, but only if it
12037 really is a member of `org-todo-keywords'."
12038 (interactive "P")
12039 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12040 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12041 'region-start-level 'region))
12042 org-loop-over-headlines-in-active-region)
12043 (org-map-entries
12044 `(org-todo ,arg)
12045 org-loop-over-headlines-in-active-region
12046 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12047 (when (equal arg '(16)) (setq arg 'nextset))
12048 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12049 (let ((org-blocker-hook org-blocker-hook)
12050 commentp
12051 case-fold-search)
12052 (when (equal arg '(64))
12053 (setq arg nil org-blocker-hook nil))
12054 (when (and org-blocker-hook
12055 (or org-inhibit-blocking
12056 (org-entry-get nil "NOBLOCKING")))
12057 (setq org-blocker-hook nil))
12058 (save-excursion
12059 (catch 'exit
12060 (org-back-to-heading t)
12061 (when (org-in-commented-heading-p t)
12062 (org-toggle-comment)
12063 (setq commentp t))
12064 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12065 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12066 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12067 (let* ((match-data (match-data))
12068 (startpos (point-at-bol))
12069 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12070 (org-log-done org-log-done)
12071 (org-log-repeat org-log-repeat)
12072 (org-todo-log-states org-todo-log-states)
12073 (org-inhibit-logging
12074 (if (equal arg 0)
12075 (progn (setq arg nil) 'note) org-inhibit-logging))
12076 (this (match-string 1))
12077 (hl-pos (match-beginning 0))
12078 (head (org-get-todo-sequence-head this))
12079 (ass (assoc head org-todo-kwd-alist))
12080 (interpret (nth 1 ass))
12081 (done-word (nth 3 ass))
12082 (final-done-word (nth 4 ass))
12083 (org-last-state (or this ""))
12084 (completion-ignore-case t)
12085 (member (member this org-todo-keywords-1))
12086 (tail (cdr member))
12087 (org-state (cond
12088 ((and org-todo-key-trigger
12089 (or (and (equal arg '(4))
12090 (eq org-use-fast-todo-selection 'prefix))
12091 (and (not arg) org-use-fast-todo-selection
12092 (not (eq org-use-fast-todo-selection
12093 'prefix)))))
12094 ;; Use fast selection.
12095 (org-fast-todo-selection))
12096 ((and (equal arg '(4))
12097 (or (not org-use-fast-todo-selection)
12098 (not org-todo-key-trigger)))
12099 ;; Read a state with completion.
12100 (completing-read
12101 "State: " (mapcar #'list org-todo-keywords-1)
12102 nil t))
12103 ((eq arg 'right)
12104 (if this
12105 (if tail (car tail) nil)
12106 (car org-todo-keywords-1)))
12107 ((eq arg 'left)
12108 (unless (equal member org-todo-keywords-1)
12109 (if this
12110 (nth (- (length org-todo-keywords-1)
12111 (length tail) 2)
12112 org-todo-keywords-1)
12113 (org-last org-todo-keywords-1))))
12114 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12115 (setq arg nil))) ;hack to fall back to cycling
12116 (arg
12117 ;; User or caller requests a specific state.
12118 (cond
12119 ((equal arg "") nil)
12120 ((eq arg 'none) nil)
12121 ((eq arg 'done) (or done-word (car org-done-keywords)))
12122 ((eq arg 'nextset)
12123 (or (car (cdr (member head org-todo-heads)))
12124 (car org-todo-heads)))
12125 ((eq arg 'previousset)
12126 (let ((org-todo-heads (reverse org-todo-heads)))
12127 (or (car (cdr (member head org-todo-heads)))
12128 (car org-todo-heads))))
12129 ((car (member arg org-todo-keywords-1)))
12130 ((stringp arg)
12131 (user-error "State `%s' not valid in this file" arg))
12132 ((nth (1- (prefix-numeric-value arg))
12133 org-todo-keywords-1))))
12134 ((null member) (or head (car org-todo-keywords-1)))
12135 ((equal this final-done-word) nil) ;-> make empty
12136 ((null tail) nil) ;-> first entry
12137 ((memq interpret '(type priority))
12138 (if (eq this-command last-command)
12139 (car tail)
12140 (if (> (length tail) 0)
12141 (or done-word (car org-done-keywords))
12142 nil)))
12144 (car tail))))
12145 (org-state (or
12146 (run-hook-with-args-until-success
12147 'org-todo-get-default-hook org-state org-last-state)
12148 org-state))
12149 (next (if org-state (concat " " org-state " ") " "))
12150 (change-plist (list :type 'todo-state-change :from this :to org-state
12151 :position startpos))
12152 dolog now-done-p)
12153 (when org-blocker-hook
12154 (let (org-blocked-by-checkboxes block-reason)
12155 (setq org-last-todo-state-is-todo
12156 (not (member this org-done-keywords)))
12157 (unless (save-excursion
12158 (save-match-data
12159 (org-with-wide-buffer
12160 (run-hook-with-args-until-failure
12161 'org-blocker-hook change-plist))))
12162 (setq block-reason (if org-blocked-by-checkboxes
12163 "contained checkboxes"
12164 (format "\"%s\"" org-block-entry-blocking)))
12165 (if (called-interactively-p 'interactive)
12166 (user-error "TODO state change from %s to %s blocked (by %s)"
12167 this org-state block-reason)
12168 ;; Fail silently.
12169 (message "TODO state change from %s to %s blocked (by %s)"
12170 this org-state block-reason)
12171 (throw 'exit nil)))))
12172 (store-match-data match-data)
12173 (replace-match next t t)
12174 (cond ((equal this org-state)
12175 (message "TODO state was already %s" (org-trim next)))
12176 ((not (pos-visible-in-window-p hl-pos))
12177 (message "TODO state changed to %s" (org-trim next))))
12178 (unless head
12179 (setq head (org-get-todo-sequence-head org-state)
12180 ass (assoc head org-todo-kwd-alist)
12181 interpret (nth 1 ass)
12182 done-word (nth 3 ass)
12183 final-done-word (nth 4 ass)))
12184 (when (memq arg '(nextset previousset))
12185 (message "Keyword-Set %d/%d: %s"
12186 (- (length org-todo-sets) -1
12187 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12188 (length org-todo-sets)
12189 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12190 (setq org-last-todo-state-is-todo
12191 (not (member org-state org-done-keywords)))
12192 (setq now-done-p (and (member org-state org-done-keywords)
12193 (not (member this org-done-keywords))))
12194 (and logging (org-local-logging logging))
12195 (when (and (or org-todo-log-states org-log-done)
12196 (not (eq org-inhibit-logging t))
12197 (not (memq arg '(nextset previousset))))
12198 ;; We need to look at recording a time and note.
12199 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12200 (nth 2 (assoc this org-todo-log-states))))
12201 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12202 (setq dolog 'time))
12203 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12204 (and org-state
12205 (member org-state org-not-done-keywords)
12206 (not (member this org-not-done-keywords))))
12207 ;; This is now a todo state and was not one before
12208 ;; If there was a CLOSED time stamp, get rid of it.
12209 (org-add-planning-info nil nil 'closed))
12210 (when (and now-done-p org-log-done)
12211 ;; It is now done, and it was not done before.
12212 (org-add-planning-info 'closed (org-current-effective-time))
12213 (when (and (not dolog) (eq 'note org-log-done))
12214 (org-add-log-setup 'done org-state this 'note)))
12215 (when (and org-state dolog)
12216 ;; This is a non-nil state, and we need to log it.
12217 (org-add-log-setup 'state org-state this dolog)))
12218 ;; Fixup tag positioning.
12219 (org-todo-trigger-tag-changes org-state)
12220 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12221 (when org-provide-todo-statistics
12222 (org-update-parent-todo-statistics))
12223 (run-hooks 'org-after-todo-state-change-hook)
12224 (when (and arg (not (member org-state org-done-keywords)))
12225 (setq head (org-get-todo-sequence-head org-state)))
12226 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12227 ;; Do we need to trigger a repeat?
12228 (when now-done-p
12229 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12230 ;; This is for the agenda, take a snapshot of the headline.
12231 (save-match-data
12232 (setq org-agenda-headline-snapshot-before-repeat
12233 (org-get-heading))))
12234 (org-auto-repeat-maybe org-state))
12235 ;; Fixup cursor location if close to the keyword.
12236 (when (and (outline-on-heading-p)
12237 (not (bolp))
12238 (save-excursion (beginning-of-line 1)
12239 (looking-at org-todo-line-regexp))
12240 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12241 (goto-char (or (match-end 2) (match-end 1)))
12242 (and (looking-at " ") (just-one-space)))
12243 (when org-trigger-hook
12244 (save-excursion
12245 (run-hook-with-args 'org-trigger-hook change-plist)))
12246 (when commentp (org-toggle-comment))))))))
12248 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12249 "Block turning an entry into a TODO, using the hierarchy.
12250 This checks whether the current task should be blocked from state
12251 changes. Such blocking occurs when:
12253 1. The task has children which are not all in a completed state.
12255 2. A task has a parent with the property :ORDERED:, and there
12256 are siblings prior to the current task with incomplete
12257 status.
12259 3. The parent of the task is blocked because it has siblings that should
12260 be done first, or is child of a block grandparent TODO entry."
12262 (if (not org-enforce-todo-dependencies)
12263 t ; if locally turned off don't block
12264 (catch 'dont-block
12265 ;; If this is not a todo state change, or if this entry is already DONE,
12266 ;; do not block
12267 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12268 (member (plist-get change-plist :from)
12269 (cons 'done org-done-keywords))
12270 (member (plist-get change-plist :to)
12271 (cons 'todo org-not-done-keywords))
12272 (not (plist-get change-plist :to)))
12273 (throw 'dont-block t))
12274 ;; If this task has children, and any are undone, it's blocked
12275 (save-excursion
12276 (org-back-to-heading t)
12277 (let ((this-level (funcall outline-level)))
12278 (outline-next-heading)
12279 (let ((child-level (funcall outline-level)))
12280 (while (and (not (eobp))
12281 (> child-level this-level))
12282 ;; this todo has children, check whether they are all
12283 ;; completed
12284 (when (and (not (org-entry-is-done-p))
12285 (org-entry-is-todo-p))
12286 (setq org-block-entry-blocking (org-get-heading))
12287 (throw 'dont-block nil))
12288 (outline-next-heading)
12289 (setq child-level (funcall outline-level))))))
12290 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12291 ;; any previous siblings are undone, it's blocked
12292 (save-excursion
12293 (org-back-to-heading t)
12294 (let* ((pos (point))
12295 (parent-pos (and (org-up-heading-safe) (point)))
12296 (case-fold-search nil))
12297 (unless parent-pos (throw 'dont-block t)) ; no parent
12298 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12299 (forward-line 1)
12300 (re-search-forward org-not-done-heading-regexp pos t))
12301 (setq org-block-entry-blocking (match-string 0))
12302 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12303 ;; Search further up the hierarchy, to see if an ancestor is blocked
12304 (while t
12305 (goto-char parent-pos)
12306 (unless (looking-at org-not-done-heading-regexp)
12307 (throw 'dont-block t)) ; do not block, parent is not a TODO
12308 (setq pos (point))
12309 (setq parent-pos (and (org-up-heading-safe) (point)))
12310 (unless parent-pos (throw 'dont-block t)) ; no parent
12311 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12312 (forward-line 1)
12313 (re-search-forward org-not-done-heading-regexp pos t)
12314 (setq org-block-entry-blocking (org-get-heading)))
12315 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12317 (defcustom org-track-ordered-property-with-tag nil
12318 "Should the ORDERED property also be shown as a tag?
12319 The ORDERED property decides if an entry should require subtasks to be
12320 completed in sequence. Since a property is not very visible, setting
12321 this option means that toggling the ORDERED property with the command
12322 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12323 not relevant for the behavior, but it makes things more visible.
12325 Note that toggling the tag with tags commands will not change the property
12326 and therefore not influence behavior!
12328 This can be t, meaning the tag ORDERED should be used, It can also be a
12329 string to select a different tag for this task."
12330 :group 'org-todo
12331 :type '(choice
12332 (const :tag "No tracking" nil)
12333 (const :tag "Track with ORDERED tag" t)
12334 (string :tag "Use other tag")))
12336 (defun org-toggle-ordered-property ()
12337 "Toggle the ORDERED property of the current entry.
12338 For better visibility, you can track the value of this property with a tag.
12339 See variable `org-track-ordered-property-with-tag'."
12340 (interactive)
12341 (let* ((t1 org-track-ordered-property-with-tag)
12342 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12343 (save-excursion
12344 (org-back-to-heading)
12345 (if (org-entry-get nil "ORDERED")
12346 (progn
12347 (org-delete-property "ORDERED")
12348 (and tag (org-toggle-tag tag 'off))
12349 (message "Subtasks can be completed in arbitrary order"))
12350 (org-entry-put nil "ORDERED" "t")
12351 (and tag (org-toggle-tag tag 'on))
12352 (message "Subtasks must be completed in sequence")))))
12354 (defun org-block-todo-from-checkboxes (change-plist)
12355 "Block turning an entry into a TODO, using checkboxes.
12356 This checks whether the current task should be blocked from state
12357 changes because there are unchecked boxes in this entry."
12358 (if (not org-enforce-todo-checkbox-dependencies)
12359 t ; if locally turned off don't block
12360 (catch 'dont-block
12361 ;; If this is not a todo state change, or if this entry is already DONE,
12362 ;; do not block
12363 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12364 (member (plist-get change-plist :from)
12365 (cons 'done org-done-keywords))
12366 (member (plist-get change-plist :to)
12367 (cons 'todo org-not-done-keywords))
12368 (not (plist-get change-plist :to)))
12369 (throw 'dont-block t))
12370 ;; If this task has checkboxes that are not checked, it's blocked
12371 (save-excursion
12372 (org-back-to-heading t)
12373 (let ((beg (point)) end)
12374 (outline-next-heading)
12375 (setq end (point))
12376 (goto-char beg)
12377 (when (org-list-search-forward
12378 (concat (org-item-beginning-re)
12379 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12380 "\\[[- ]\\]")
12381 end t)
12382 (when (boundp 'org-blocked-by-checkboxes)
12383 (setq org-blocked-by-checkboxes t))
12384 (throw 'dont-block nil))))
12385 t))) ; do not block
12387 (defun org-entry-blocked-p ()
12388 "Non-nil if entry at point is blocked."
12389 (and (not (org-entry-get nil "NOBLOCKING"))
12390 (member (org-entry-get nil "TODO") org-not-done-keywords)
12391 (not (run-hook-with-args-until-failure
12392 'org-blocker-hook
12393 (list :type 'todo-state-change
12394 :position (point)
12395 :from 'todo
12396 :to 'done)))))
12398 (defun org-update-statistics-cookies (all)
12399 "Update the statistics cookie, either from TODO or from checkboxes.
12400 This should be called with the cursor in a line with a statistics
12401 cookie. When called with a \\[universal-argument] prefix, update
12402 all statistics cookies in the buffer."
12403 (interactive "P")
12404 (if all
12405 (progn
12406 (org-update-checkbox-count 'all)
12407 (org-map-entries 'org-update-parent-todo-statistics))
12408 (if (not (org-at-heading-p))
12409 (org-update-checkbox-count)
12410 (let ((pos (point-marker))
12411 end l1 l2)
12412 (ignore-errors (org-back-to-heading t))
12413 (if (not (org-at-heading-p))
12414 (org-update-checkbox-count)
12415 (setq l1 (org-outline-level))
12416 (setq end (save-excursion
12417 (outline-next-heading)
12418 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12419 (point)))
12420 (if (and (save-excursion
12421 (re-search-forward
12422 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12423 (not (save-excursion (re-search-forward
12424 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12425 (org-update-checkbox-count)
12426 (if (and l2 (> l2 l1))
12427 (progn
12428 (goto-char end)
12429 (org-update-parent-todo-statistics))
12430 (goto-char pos)
12431 (beginning-of-line 1)
12432 (while (re-search-forward
12433 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12434 (point-at-eol) t)
12435 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12436 (goto-char pos)
12437 (move-marker pos nil)))))
12439 (defvar org-entry-property-inherited-from) ;; defined below
12440 (defun org-update-parent-todo-statistics ()
12441 "Update any statistics cookie in the parent of the current headline.
12442 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12443 the entire subtree and this will travel up the hierarchy and update
12444 statistics everywhere."
12445 (let* ((prop (save-excursion (org-up-heading-safe)
12446 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12447 (recursive (or (not org-hierarchical-todo-statistics)
12448 (and prop (string-match "\\<recursive\\>" prop))))
12449 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12451 (first t)
12452 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12453 level ltoggle l1 new ndel
12454 (cnt-all 0) (cnt-done 0) is-percent kwd
12455 checkbox-beg cookie-present)
12456 (catch 'exit
12457 (save-excursion
12458 (beginning-of-line 1)
12459 (setq ltoggle (funcall outline-level))
12460 ;; Three situations are to consider:
12462 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12463 ;; to the top-level ancestor on the headline;
12465 ;; 2. If parent has "recursive" property, repeat up to the
12466 ;; headline setting that property, taking inheritance into
12467 ;; account;
12469 ;; 3. Else, move up to direct parent and proceed only once.
12470 (while (and (setq level (org-up-heading-safe))
12471 (or recursive first)
12472 (>= (point) lim))
12473 (setq first nil cookie-present nil)
12474 (unless (and level
12475 (not (string-match
12476 "\\<checkbox\\>"
12477 (downcase (or (org-entry-get nil "COOKIE_DATA")
12478 "")))))
12479 (throw 'exit nil))
12480 (while (re-search-forward box-re (point-at-eol) t)
12481 (setq cnt-all 0 cnt-done 0 cookie-present t)
12482 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12483 (save-match-data
12484 (unless (outline-next-heading) (throw 'exit nil))
12485 (while (and (looking-at org-complex-heading-regexp)
12486 (> (setq l1 (length (match-string 1))) level))
12487 (setq kwd (and (or recursive (= l1 ltoggle))
12488 (match-string 2)))
12489 (if (or (eq org-provide-todo-statistics 'all-headlines)
12490 (and (eq org-provide-todo-statistics t)
12491 (or (member kwd org-done-keywords)))
12492 (and (listp org-provide-todo-statistics)
12493 (stringp (car org-provide-todo-statistics))
12494 (or (member kwd org-provide-todo-statistics)
12495 (member kwd org-done-keywords)))
12496 (and (listp org-provide-todo-statistics)
12497 (listp (car org-provide-todo-statistics))
12498 (or (member kwd (car org-provide-todo-statistics))
12499 (and (member kwd org-done-keywords)
12500 (member kwd (cadr org-provide-todo-statistics))))))
12501 (setq cnt-all (1+ cnt-all))
12502 (and (eq org-provide-todo-statistics t)
12504 (setq cnt-all (1+ cnt-all))))
12505 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12506 (member kwd org-done-keywords))
12507 (and (listp org-provide-todo-statistics)
12508 (listp (car org-provide-todo-statistics))
12509 (member kwd org-done-keywords)
12510 (member kwd (cadr org-provide-todo-statistics)))
12511 (and (listp org-provide-todo-statistics)
12512 (stringp (car org-provide-todo-statistics))
12513 (member kwd org-done-keywords)))
12514 (setq cnt-done (1+ cnt-done)))
12515 (outline-next-heading)))
12516 (setq new
12517 (if is-percent
12518 (format "[%d%%]" (floor (* 100.0 cnt-done)
12519 (max 1 cnt-all)))
12520 (format "[%d/%d]" cnt-done cnt-all))
12521 ndel (- (match-end 0) checkbox-beg))
12522 (goto-char checkbox-beg)
12523 (insert new)
12524 (delete-region (point) (+ (point) ndel))
12525 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12526 (when cookie-present
12527 (run-hook-with-args 'org-after-todo-statistics-hook
12528 cnt-done (- cnt-all cnt-done))))))
12529 (run-hooks 'org-todo-statistics-hook)))
12531 (defvar org-after-todo-statistics-hook nil
12532 "Hook that is called after a TODO statistics cookie has been updated.
12533 Each function is called with two arguments: the number of not-done entries
12534 and the number of done entries.
12536 For example, the following function, when added to this hook, will switch
12537 an entry to DONE when all children are done, and back to TODO when new
12538 entries are set to a TODO status. Note that this hook is only called
12539 when there is a statistics cookie in the headline!
12541 (defun org-summary-todo (n-done n-not-done)
12542 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12543 (let (org-log-done org-log-states) ; turn off logging
12544 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12547 (defvar org-todo-statistics-hook nil
12548 "Hook that is run whenever Org thinks TODO statistics should be updated.
12549 This hook runs even if there is no statistics cookie present, in which case
12550 `org-after-todo-statistics-hook' would not run.")
12552 (defun org-todo-trigger-tag-changes (state)
12553 "Apply the changes defined in `org-todo-state-tags-triggers'."
12554 (let ((l org-todo-state-tags-triggers)
12555 changes)
12556 (when (or (not state) (equal state ""))
12557 (setq changes (append changes (cdr (assoc "" l)))))
12558 (when (and (stringp state) (> (length state) 0))
12559 (setq changes (append changes (cdr (assoc state l)))))
12560 (when (member state org-not-done-keywords)
12561 (setq changes (append changes (cdr (assq 'todo l)))))
12562 (when (member state org-done-keywords)
12563 (setq changes (append changes (cdr (assq 'done l)))))
12564 (dolist (c changes)
12565 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12567 (defun org-local-logging (value)
12568 "Get logging settings from a property VALUE."
12569 ;; Directly set the variables, they are already local.
12570 (setq org-log-done nil
12571 org-log-repeat nil
12572 org-todo-log-states nil)
12573 (dolist (w (split-string value))
12574 (let (a)
12575 (cond
12576 ((setq a (assoc w org-startup-options))
12577 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12578 (set (nth 1 a) (nth 2 a))))
12579 ((setq a (org-extract-log-state-settings w))
12580 (and (member (car a) org-todo-keywords-1)
12581 (push a org-todo-log-states)))))))
12583 (defun org-get-todo-sequence-head (kwd)
12584 "Return the head of the TODO sequence to which KWD belongs.
12585 If KWD is not set, check if there is a text property remembering the
12586 right sequence."
12587 (let (p)
12588 (cond
12589 ((not kwd)
12590 (or (get-text-property (point-at-bol) 'org-todo-head)
12591 (progn
12592 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12593 nil (point-at-eol)))
12594 (get-text-property p 'org-todo-head))))
12595 ((not (member kwd org-todo-keywords-1))
12596 (car org-todo-keywords-1))
12597 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12599 (defun org-fast-todo-selection ()
12600 "Fast TODO keyword selection with single keys.
12601 Returns the new TODO keyword, or nil if no state change should occur."
12602 (let* ((fulltable org-todo-key-alist)
12603 (done-keywords org-done-keywords) ;; needed for the faces.
12604 (maxlen (apply 'max (mapcar
12605 (lambda (x)
12606 (if (stringp (car x)) (string-width (car x)) 0))
12607 fulltable)))
12608 (expert nil)
12609 (fwidth (+ maxlen 3 1 3))
12610 (ncol (/ (- (window-width) 4) fwidth))
12611 tg cnt e c tbl
12612 groups ingroup)
12613 (save-excursion
12614 (save-window-excursion
12615 (if expert
12616 (set-buffer (get-buffer-create " *Org todo*"))
12617 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12618 (erase-buffer)
12619 (setq-local org-done-keywords done-keywords)
12620 (setq tbl fulltable cnt 0)
12621 (while (setq e (pop tbl))
12622 (cond
12623 ((equal e '(:startgroup))
12624 (push '() groups) (setq ingroup t)
12625 (unless (= cnt 0)
12626 (setq cnt 0)
12627 (insert "\n"))
12628 (insert "{ "))
12629 ((equal e '(:endgroup))
12630 (setq ingroup nil cnt 0)
12631 (insert "}\n"))
12632 ((equal e '(:newline))
12633 (unless (= cnt 0)
12634 (setq cnt 0)
12635 (insert "\n")
12636 (setq e (car tbl))
12637 (while (equal (car tbl) '(:newline))
12638 (insert "\n")
12639 (setq tbl (cdr tbl)))))
12641 (setq tg (car e) c (cdr e))
12642 (when ingroup (push tg (car groups)))
12643 (setq tg (org-add-props tg nil 'face
12644 (org-get-todo-face tg)))
12645 (when (and (= cnt 0) (not ingroup)) (insert " "))
12646 (insert "[" c "] " tg (make-string
12647 (- fwidth 4 (length tg)) ?\ ))
12648 (when (= (setq cnt (1+ cnt)) ncol)
12649 (insert "\n")
12650 (when ingroup (insert " "))
12651 (setq cnt 0)))))
12652 (insert "\n")
12653 (goto-char (point-min))
12654 (unless expert (org-fit-window-to-buffer))
12655 (message "[a-z..]:Set [SPC]:clear")
12656 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12657 (cond
12658 ((or (= c ?\C-g)
12659 (and (= c ?q) (not (rassoc c fulltable))))
12660 (setq quit-flag t))
12661 ((= c ?\ ) nil)
12662 ((setq e (rassoc c fulltable) tg (car e))
12664 (t (setq quit-flag t)))))))
12666 (defun org-entry-is-todo-p ()
12667 (member (org-get-todo-state) org-not-done-keywords))
12669 (defun org-entry-is-done-p ()
12670 (member (org-get-todo-state) org-done-keywords))
12672 (defun org-get-todo-state ()
12673 "Return the TODO keyword of the current subtree."
12674 (save-excursion
12675 (org-back-to-heading t)
12676 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12677 (match-end 2)
12678 (match-string 2))))
12680 (defun org-at-date-range-p (&optional inactive-ok)
12681 "Non-nil if point is inside a date range.
12683 When optional argument INACTIVE-OK is non-nil, also consider
12684 inactive time ranges.
12686 When this function returns a non-nil value, match data is set
12687 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12688 on INACTIVE-OK."
12689 (interactive)
12690 (save-excursion
12691 (catch 'exit
12692 (let ((pos (point)))
12693 (skip-chars-backward "^[<\r\n")
12694 (skip-chars-backward "<[")
12695 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12696 (>= (match-end 0) pos)
12697 (throw 'exit t))
12698 (skip-chars-backward "^<[\r\n")
12699 (skip-chars-backward "<[")
12700 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12701 (>= (match-end 0) pos)
12702 (throw 'exit t)))
12703 nil)))
12705 (defun org-get-repeat (&optional timestamp)
12706 "Check if there is a time-stamp with repeater in this entry.
12708 Return the repeater, as a string, or nil. Also return nil when
12709 this function is called before first heading.
12711 When optional argument TIMESTAMP is a string, extract the
12712 repeater from there instead."
12713 (save-match-data
12714 (cond (timestamp
12715 (and (string-match org-repeat-re timestamp)
12716 (match-string-no-properties 1 timestamp)))
12717 ((org-before-first-heading-p) nil)
12719 (save-excursion
12720 (org-back-to-heading t)
12721 (let ((end (org-entry-end-position)))
12722 (catch :repeat
12723 (while (re-search-forward org-repeat-re end t)
12724 (when (save-match-data (org-at-timestamp-p 'agenda))
12725 (throw :repeat (match-string-no-properties 1)))))))))))
12727 (defvar org-last-changed-timestamp)
12728 (defvar org-last-inserted-timestamp)
12729 (defvar org-log-post-message)
12730 (defvar org-log-note-purpose)
12731 (defvar org-log-note-how nil)
12732 (defvar org-log-note-extra)
12733 (defun org-auto-repeat-maybe (done-word)
12734 "Check if the current headline contains a repeated time-stamp.
12736 If yes, set TODO state back to what it was and change the base date
12737 of repeating deadline/scheduled time stamps to new date.
12739 This function is run automatically after each state change to a DONE state."
12740 (let* ((repeat (org-get-repeat))
12741 (aa (assoc org-last-state org-todo-kwd-alist))
12742 (interpret (nth 1 aa))
12743 (head (nth 2 aa))
12744 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12745 (msg "Entry repeats: ")
12746 (org-log-done nil)
12747 (org-todo-log-states nil)
12748 (end (copy-marker (org-entry-end-position))))
12749 (unwind-protect
12750 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12751 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12752 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12753 org-todo-repeat-to-state)))
12754 (org-todo (cond
12755 ((and to-state (member to-state org-todo-keywords-1))
12756 to-state)
12757 ((eq interpret 'type) org-last-state)
12758 (head)
12759 (t 'none))))
12760 (org-back-to-heading t)
12761 (org-add-planning-info nil nil 'closed)
12762 ;; When `org-log-repeat' is non-nil or entry contains
12763 ;; a clock, set LAST_REPEAT property.
12764 (when (or org-log-repeat
12765 (catch :clock
12766 (save-excursion
12767 (while (re-search-forward org-clock-line-re end t)
12768 (when (org-at-clock-log-p) (throw :clock t))))))
12769 (org-entry-put nil "LAST_REPEAT" (format-time-string
12770 (org-time-stamp-format t t)
12771 (current-time))))
12772 (when org-log-repeat
12773 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12774 (memq 'org-add-log-note post-command-hook))
12775 ;; We are already setup for some record.
12776 (when (eq org-log-repeat 'note)
12777 ;; Make sure we take a note, not only a time stamp.
12778 (setq org-log-note-how 'note))
12779 ;; Set up for taking a record.
12780 (org-add-log-setup 'state
12781 (or done-word (car org-done-keywords))
12782 org-last-state
12783 org-log-repeat)))
12784 (let ((planning-re (regexp-opt
12785 (list org-scheduled-string org-deadline-string))))
12786 (while (re-search-forward org-ts-regexp end t)
12787 (let* ((ts (match-string 0))
12788 (planning? (org-at-planning-p))
12789 (type (if (not planning?) "Plain:"
12790 (save-excursion
12791 (re-search-backward
12792 planning-re (line-beginning-position) t)
12793 (match-string 0)))))
12794 (cond
12795 ;; Ignore fake time-stamps (e.g., within comments).
12796 ((not (org-at-timestamp-p 'agenda)))
12797 ;; Time-stamps without a repeater are usually
12798 ;; skipped. However, a SCHEDULED time-stamp without
12799 ;; one is removed, as they are no longer relevant.
12800 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12801 ts))
12802 (when (equal type org-scheduled-string)
12803 (org-remove-timestamp-with-keyword type)))
12805 (let ((n (string-to-number (match-string 2 ts)))
12806 (what (match-string 3 ts)))
12807 (when (equal what "w") (setq n (* n 7) what "d"))
12808 (when (and (equal what "h")
12809 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12810 ts)))
12811 (user-error
12812 "Cannot repeat in Repeat in %d hour(s) because no hour \
12813 has been set"
12815 ;; Preparation, see if we need to modify the start
12816 ;; date for the change.
12817 (when (match-end 1)
12818 (let ((time (save-match-data
12819 (org-time-string-to-time ts))))
12820 (cond
12821 ((equal (match-string 1 ts) ".")
12822 ;; Shift starting date to today
12823 (org-timestamp-change
12824 (- (org-today) (time-to-days time))
12825 'day))
12826 ((equal (match-string 1 ts) "+")
12827 (let ((nshiftmax 10)
12828 (nshift 0))
12829 (while (or (= nshift 0)
12830 (not (time-less-p (current-time) time)))
12831 (when (= (cl-incf nshift) nshiftmax)
12832 (or (y-or-n-p
12833 (format "%d repeater intervals were not \
12834 enough to shift date past today. Continue? "
12835 nshift))
12836 (user-error "Abort")))
12837 (org-timestamp-change n (cdr (assoc what whata)))
12838 (org-in-regexp org-ts-regexp3)
12839 (setq ts (match-string 1))
12840 (setq time
12841 (save-match-data
12842 (org-time-string-to-time ts)))))
12843 (org-timestamp-change (- n) (cdr (assoc what whata)))
12844 ;; Rematch, so that we have everything in place
12845 ;; for the real shift.
12846 (org-in-regexp org-ts-regexp3)
12847 (setq ts (match-string 1))
12848 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12849 ts)))))
12850 (save-excursion
12851 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12852 (setq msg
12853 (concat
12854 msg type " " org-last-changed-timestamp " "))))))))
12855 (setq org-log-post-message msg)
12856 (message "%s" msg))
12857 (set-marker end nil))))
12859 (defun org-show-todo-tree (arg)
12860 "Make a compact tree which shows all headlines marked with TODO.
12861 The tree will show the lines where the regexp matches, and all higher
12862 headlines above the match.
12863 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12864 With a numeric prefix N, construct a sparse tree for the Nth element
12865 of `org-todo-keywords-1'."
12866 (interactive "P")
12867 (let ((case-fold-search nil)
12868 (kwd-re
12869 (cond ((null arg) org-not-done-regexp)
12870 ((equal arg '(4))
12871 (let ((kwd
12872 (completing-read "Keyword (or KWD1|KWD2|...): "
12873 (mapcar #'list org-todo-keywords-1))))
12874 (concat "\\("
12875 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12876 "\\)\\>")))
12877 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12878 (regexp-quote (nth (1- (prefix-numeric-value arg))
12879 org-todo-keywords-1)))
12880 (t (user-error "Invalid prefix argument: %s" arg)))))
12881 (message "%d TODO entries found"
12882 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12884 (defun org--deadline-or-schedule (arg type time)
12885 "Insert DEADLINE or SCHEDULE information in current entry.
12886 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12887 `org-schedule' for information about ARG and TIME arguments."
12888 (let* ((deadline? (eq type 'deadline))
12889 (keyword (if deadline? org-deadline-string org-scheduled-string))
12890 (log (if deadline? org-log-redeadline org-log-reschedule))
12891 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12892 (old-date-time (and old-date (org-time-string-to-time old-date)))
12893 ;; Save repeater cookie from either TIME or current scheduled
12894 ;; time stamp. We are going to insert it back at the end of
12895 ;; the process.
12896 (repeater (or (and (org-string-nw-p time)
12897 ;; We use `org-repeat-re' because we need
12898 ;; to tell the difference between a real
12899 ;; repeater and a time delta, e.g. "+2d".
12900 (string-match org-repeat-re time)
12901 (match-string 1 time))
12902 (and (org-string-nw-p old-date)
12903 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12904 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12905 old-date)
12906 (match-string 1 old-date)))))
12907 (pcase arg
12908 (`(4)
12909 (when (and old-date log)
12910 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12911 nil old-date log))
12912 (org-remove-timestamp-with-keyword keyword)
12913 (message (if deadline? "Item no longer has a deadline."
12914 "Item is no longer scheduled.")))
12915 (`(16)
12916 (save-excursion
12917 (org-back-to-heading t)
12918 (let ((regexp (if deadline? org-deadline-time-regexp
12919 org-scheduled-time-regexp)))
12920 (if (not (re-search-forward regexp (line-end-position 2) t))
12921 (user-error (if deadline? "No deadline information to update"
12922 "No scheduled information to update"))
12923 (let* ((rpl0 (match-string 1))
12924 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12925 (msg (if deadline? "Warn starting from" "Delay until")))
12926 (replace-match
12927 (concat keyword
12928 " <" rpl
12929 (format " -%dd"
12930 (abs (- (time-to-days
12931 (save-match-data
12932 (org-read-date
12933 nil t nil msg old-date-time)))
12934 (time-to-days old-date-time))))
12935 ">") t t))))))
12937 (org-add-planning-info type time 'closed)
12938 (when (and old-date
12940 (not (equal old-date org-last-inserted-timestamp)))
12941 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12942 org-last-inserted-timestamp
12943 old-date
12944 log))
12945 (when repeater
12946 (save-excursion
12947 (org-back-to-heading t)
12948 (when (re-search-forward
12949 (concat keyword " " org-last-inserted-timestamp)
12950 (line-end-position 2)
12952 (goto-char (1- (match-end 0)))
12953 (insert " " repeater)
12954 (setq org-last-inserted-timestamp
12955 (concat (substring org-last-inserted-timestamp 0 -1)
12956 " " repeater
12957 (substring org-last-inserted-timestamp -1))))))
12958 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12959 org-last-inserted-timestamp)))))
12961 (defun org-deadline (arg &optional time)
12962 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12963 With one universal prefix argument, remove any deadline from the item.
12964 With two universal prefix arguments, prompt for a warning delay.
12965 With argument TIME, set the deadline at the corresponding date. TIME
12966 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12967 (interactive "P")
12968 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12969 (org-map-entries
12970 (lambda () (org--deadline-or-schedule arg 'deadline time))
12972 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12973 'region-start-level
12974 'region)
12975 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12976 (org--deadline-or-schedule arg 'deadline time)))
12978 (defun org-schedule (arg &optional time)
12979 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12980 With one universal prefix argument, remove any scheduling date from the item.
12981 With two universal prefix arguments, prompt for a delay cookie.
12982 With argument TIME, scheduled at the corresponding date. TIME can
12983 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12984 (interactive "P")
12985 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12986 (org-map-entries
12987 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12989 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12990 'region-start-level
12991 'region)
12992 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12993 (org--deadline-or-schedule arg 'scheduled time)))
12995 (defun org-get-scheduled-time (pom &optional inherit)
12996 "Get the scheduled time as a time tuple, of a format suitable
12997 for calling org-schedule with, or if there is no scheduling,
12998 returns nil."
12999 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13000 (when time
13001 (apply 'encode-time (org-parse-time-string time)))))
13003 (defun org-get-deadline-time (pom &optional inherit)
13004 "Get the deadline as a time tuple, of a format suitable for
13005 calling org-deadline with, or if there is no scheduling, returns
13006 nil."
13007 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13008 (when time
13009 (apply 'encode-time (org-parse-time-string time)))))
13011 (defun org-remove-timestamp-with-keyword (keyword)
13012 "Remove all time stamps with KEYWORD in the current entry."
13013 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13014 beg)
13015 (save-excursion
13016 (org-back-to-heading t)
13017 (setq beg (point))
13018 (outline-next-heading)
13019 (while (re-search-backward re beg t)
13020 (replace-match "")
13021 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13022 (equal (char-before) ?\ ))
13023 (backward-delete-char 1)
13024 (when (string-match "^[ \t]*$" (buffer-substring
13025 (point-at-bol) (point-at-eol)))
13026 (delete-region (point-at-bol)
13027 (min (point-max) (1+ (point-at-eol))))))))))
13029 (defvar org-time-was-given) ; dynamically scoped parameter
13030 (defvar org-end-time-was-given) ; dynamically scoped parameter
13032 (defun org-at-planning-p ()
13033 "Non-nil when point is on a planning info line."
13034 ;; This is as accurate and faster than `org-element-at-point' since
13035 ;; planning info location is fixed in the section.
13036 (org-with-wide-buffer
13037 (beginning-of-line)
13038 (and (looking-at-p org-planning-line-re)
13039 (eq (point)
13040 (ignore-errors
13041 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13042 (org-back-to-heading t)
13043 (org-with-limited-levels (org-back-to-heading t)))
13044 (line-beginning-position 2))))))
13046 (defun org-add-planning-info (what &optional time &rest remove)
13047 "Insert new timestamp with keyword in the planning line.
13048 WHAT indicates what kind of time stamp to add. It is a symbol
13049 among `closed', `deadline', `scheduled' and nil. TIME indicates
13050 the time to use. If none is given, the user is prompted for
13051 a date. REMOVE indicates what kind of entries to remove. An old
13052 WHAT entry will also be removed."
13053 (let (org-time-was-given org-end-time-was-given default-time default-input)
13054 (catch 'exit
13055 (when (and (memq what '(scheduled deadline))
13056 (or (not time)
13057 (and (stringp time)
13058 (string-match "^[-+]+[0-9]" time))))
13059 ;; Try to get a default date/time from existing timestamp
13060 (save-excursion
13061 (org-back-to-heading t)
13062 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13063 (when (re-search-forward (if (eq what 'scheduled)
13064 org-scheduled-time-regexp
13065 org-deadline-time-regexp)
13066 end t)
13067 (setq ts (match-string 1)
13068 default-time (apply 'encode-time (org-parse-time-string ts))
13069 default-input (and ts (org-get-compact-tod ts)))))))
13070 (when what
13071 (setq time
13072 (if (stringp time)
13073 ;; This is a string (relative or absolute), set
13074 ;; proper date.
13075 (apply #'encode-time
13076 (org-read-date-analyze
13077 time default-time (decode-time default-time)))
13078 ;; If necessary, get the time from the user
13079 (or time (org-read-date nil 'to-time nil nil
13080 default-time default-input)))))
13082 (org-with-wide-buffer
13083 (org-back-to-heading t)
13084 (forward-line)
13085 (unless (bolp) (insert "\n"))
13086 (cond ((looking-at-p org-planning-line-re)
13087 ;; Move to current indentation.
13088 (skip-chars-forward " \t")
13089 ;; Check if we have to remove something.
13090 (dolist (type (if what (cons what remove) remove))
13091 (save-excursion
13092 (when (re-search-forward
13093 (cl-case type
13094 (closed org-closed-time-regexp)
13095 (deadline org-deadline-time-regexp)
13096 (scheduled org-scheduled-time-regexp)
13097 (otherwise
13098 (error "Invalid planning type: %s" type)))
13099 (line-end-position) t)
13100 ;; Delete until next keyword or end of line.
13101 (delete-region
13102 (match-beginning 0)
13103 (if (re-search-forward org-keyword-time-not-clock-regexp
13104 (line-end-position)
13106 (match-beginning 0)
13107 (line-end-position))))))
13108 ;; If there is nothing more to add and no more keyword
13109 ;; is left, remove the line completely.
13110 (if (and (looking-at-p "[ \t]*$") (not what))
13111 (delete-region (line-beginning-position)
13112 (line-beginning-position 2))
13113 ;; If we removed last keyword, do not leave trailing
13114 ;; white space at the end of line.
13115 (let ((p (point)))
13116 (save-excursion
13117 (end-of-line)
13118 (unless (= (skip-chars-backward " \t" p) 0)
13119 (delete-region (point) (line-end-position)))))))
13120 ((not what) (throw 'exit nil)) ; Nothing to do.
13121 (t (insert-before-markers "\n")
13122 (backward-char 1)
13123 (when org-adapt-indentation
13124 (indent-to-column (1+ (org-outline-level))))))
13125 (when what
13126 ;; Insert planning keyword.
13127 (insert (cl-case what
13128 (closed org-closed-string)
13129 (deadline org-deadline-string)
13130 (scheduled org-scheduled-string)
13131 (otherwise (error "Invalid planning type: %s" what)))
13132 " ")
13133 ;; Insert associated timestamp.
13134 (let ((ts (org-insert-time-stamp
13135 time
13136 (or org-time-was-given
13137 (and (eq what 'closed) org-log-done-with-time))
13138 (eq what 'closed)
13139 nil nil (list org-end-time-was-given))))
13140 (unless (eolp) (insert " "))
13141 ts))))))
13143 (defvar org-log-note-marker (make-marker)
13144 "Marker pointing at the entry where the note is to be inserted.")
13145 (defvar org-log-note-purpose nil)
13146 (defvar org-log-note-state nil)
13147 (defvar org-log-note-previous-state nil)
13148 (defvar org-log-note-extra nil)
13149 (defvar org-log-note-window-configuration nil)
13150 (defvar org-log-note-return-to (make-marker))
13151 (defvar org-log-note-effective-time nil
13152 "Remembered current time so that dynamically scoped
13153 `org-extend-today-until' affects timestamps in state change log")
13155 (defvar org-log-post-message nil
13156 "Message to be displayed after a log note has been stored.
13157 The auto-repeater uses this.")
13159 (defun org-add-note ()
13160 "Add a note to the current entry.
13161 This is done in the same way as adding a state change note."
13162 (interactive)
13163 (org-add-log-setup 'note))
13165 (defun org-log-beginning (&optional create)
13166 "Return expected start of log notes in current entry.
13167 When optional argument CREATE is non-nil, the function creates
13168 a drawer to store notes, if necessary. Returned position ignores
13169 narrowing."
13170 (org-with-wide-buffer
13171 (let ((drawer (org-log-into-drawer)))
13172 (cond
13173 (drawer
13174 (org-end-of-meta-data)
13175 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13176 (end (if (org-at-heading-p) (point)
13177 (save-excursion (outline-next-heading) (point))))
13178 (case-fold-search t))
13179 (catch 'exit
13180 ;; Try to find existing drawer.
13181 (while (re-search-forward regexp end t)
13182 (let ((element (org-element-at-point)))
13183 (when (eq (org-element-type element) 'drawer)
13184 (let ((cend (org-element-property :contents-end element)))
13185 (when (and (not org-log-states-order-reversed) cend)
13186 (goto-char cend)))
13187 (throw 'exit nil))))
13188 ;; No drawer found. Create one, if permitted.
13189 (when create
13190 (unless (bolp) (insert "\n"))
13191 (let ((beg (point)))
13192 (insert ":" drawer ":\n:END:\n")
13193 (org-indent-region beg (point)))
13194 (end-of-line -1)))))
13196 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13197 (skip-chars-forward " \t\n")
13198 (beginning-of-line)
13199 (unless org-log-states-order-reversed
13200 (org-skip-over-state-notes)
13201 (skip-chars-backward " \t\n")
13202 (forward-line)))))
13203 (if (bolp) (point) (line-beginning-position 2))))
13205 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13206 "Set up the post command hook to take a note.
13207 If this is about to TODO state change, the new state is expected in STATE.
13208 HOW is an indicator what kind of note should be created.
13209 EXTRA is additional text that will be inserted into the notes buffer."
13210 (move-marker org-log-note-marker (point))
13211 (setq org-log-note-purpose purpose
13212 org-log-note-state state
13213 org-log-note-previous-state prev-state
13214 org-log-note-how how
13215 org-log-note-extra extra
13216 org-log-note-effective-time (org-current-effective-time))
13217 (add-hook 'post-command-hook 'org-add-log-note 'append))
13219 (defun org-skip-over-state-notes ()
13220 "Skip past the list of State notes in an entry."
13221 (when (ignore-errors (goto-char (org-in-item-p)))
13222 (let* ((struct (org-list-struct))
13223 (prevs (org-list-prevs-alist struct))
13224 (regexp
13225 (concat "[ \t]*- +"
13226 (replace-regexp-in-string
13227 " +" " +"
13228 (org-replace-escapes
13229 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13230 `(("%d" . ,org-ts-regexp-inactive)
13231 ("%D" . ,org-ts-regexp)
13232 ("%s" . "\"\\S-+\"")
13233 ("%S" . "\"\\S-+\"")
13234 ("%t" . ,org-ts-regexp-inactive)
13235 ("%T" . ,org-ts-regexp)
13236 ("%u" . ".*?")
13237 ("%U" . ".*?")))))))
13238 (while (looking-at-p regexp)
13239 (goto-char (or (org-list-get-next-item (point) struct prevs)
13240 (org-list-get-item-end (point) struct)))))))
13242 (defun org-add-log-note (&optional _purpose)
13243 "Pop up a window for taking a note, and add this note later."
13244 (remove-hook 'post-command-hook 'org-add-log-note)
13245 (setq org-log-note-window-configuration (current-window-configuration))
13246 (delete-other-windows)
13247 (move-marker org-log-note-return-to (point))
13248 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13249 (goto-char org-log-note-marker)
13250 (org-switch-to-buffer-other-window "*Org Note*")
13251 (erase-buffer)
13252 (if (memq org-log-note-how '(time state))
13253 (org-store-log-note)
13254 (let ((org-inhibit-startup t)) (org-mode))
13255 (insert (format "# Insert note for %s.
13256 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13257 (cond
13258 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13259 ((eq org-log-note-purpose 'done) "closed todo item")
13260 ((eq org-log-note-purpose 'state)
13261 (format "state change from \"%s\" to \"%s\""
13262 (or org-log-note-previous-state "")
13263 (or org-log-note-state "")))
13264 ((eq org-log-note-purpose 'reschedule)
13265 "rescheduling")
13266 ((eq org-log-note-purpose 'delschedule)
13267 "no longer scheduled")
13268 ((eq org-log-note-purpose 'redeadline)
13269 "changing deadline")
13270 ((eq org-log-note-purpose 'deldeadline)
13271 "removing deadline")
13272 ((eq org-log-note-purpose 'refile)
13273 "refiling")
13274 ((eq org-log-note-purpose 'note)
13275 "this entry")
13276 (t (error "This should not happen")))))
13277 (when org-log-note-extra (insert org-log-note-extra))
13278 (setq-local org-finish-function 'org-store-log-note)
13279 (run-hooks 'org-log-buffer-setup-hook)))
13281 (defvar org-note-abort nil) ; dynamically scoped
13282 (defun org-store-log-note ()
13283 "Finish taking a log note, and insert it to where it belongs."
13284 (let ((txt (prog1 (buffer-string)
13285 (kill-buffer)))
13286 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13287 lines)
13288 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13289 (setq txt (replace-match "" t t txt)))
13290 (when (string-match "\\s-+\\'" txt)
13291 (setq txt (replace-match "" t t txt)))
13292 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13293 (when (org-string-nw-p note)
13294 (setq note
13295 (org-replace-escapes
13296 note
13297 (list (cons "%u" (user-login-name))
13298 (cons "%U" user-full-name)
13299 (cons "%t" (format-time-string
13300 (org-time-stamp-format 'long 'inactive)
13301 org-log-note-effective-time))
13302 (cons "%T" (format-time-string
13303 (org-time-stamp-format 'long nil)
13304 org-log-note-effective-time))
13305 (cons "%d" (format-time-string
13306 (org-time-stamp-format nil 'inactive)
13307 org-log-note-effective-time))
13308 (cons "%D" (format-time-string
13309 (org-time-stamp-format nil nil)
13310 org-log-note-effective-time))
13311 (cons "%s" (cond
13312 ((not org-log-note-state) "")
13313 ((string-match-p org-ts-regexp
13314 org-log-note-state)
13315 (format "\"[%s]\""
13316 (substring org-log-note-state 1 -1)))
13317 (t (format "\"%s\"" org-log-note-state))))
13318 (cons "%S"
13319 (cond
13320 ((not org-log-note-previous-state) "")
13321 ((string-match-p org-ts-regexp
13322 org-log-note-previous-state)
13323 (format "\"[%s]\""
13324 (substring
13325 org-log-note-previous-state 1 -1)))
13326 (t (format "\"%s\""
13327 org-log-note-previous-state)))))))
13328 (when lines (setq note (concat note " \\\\")))
13329 (push note lines))
13330 (when (and lines (not org-note-abort))
13331 (with-current-buffer (marker-buffer org-log-note-marker)
13332 (org-with-wide-buffer
13333 ;; Find location for the new note.
13334 (goto-char org-log-note-marker)
13335 (set-marker org-log-note-marker nil)
13336 ;; Note associated to a clock is to be located right after
13337 ;; the clock. Do not move point.
13338 (unless (eq org-log-note-purpose 'clock-out)
13339 (goto-char (org-log-beginning t)))
13340 ;; Make sure point is at the beginning of an empty line.
13341 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13342 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13343 ;; In an existing list, add a new item at the top level.
13344 ;; Otherwise, indent line like a regular one.
13345 (let ((itemp (org-in-item-p)))
13346 (if itemp
13347 (indent-line-to
13348 (let ((struct (save-excursion
13349 (goto-char itemp) (org-list-struct))))
13350 (org-list-get-ind (org-list-get-top-point struct) struct)))
13351 (org-indent-line)))
13352 (insert (org-list-bullet-string "-") (pop lines))
13353 (let ((ind (org-list-item-body-column (line-beginning-position))))
13354 (dolist (line lines)
13355 (insert "\n")
13356 (indent-line-to ind)
13357 (insert line)))
13358 (message "Note stored")
13359 (org-back-to-heading t)
13360 (org-cycle-hide-drawers 'children))
13361 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13362 ;; from within `org-add-log-note' because `buffer-undo-list'
13363 ;; is then modified outside of `org-with-remote-undo'.
13364 (when (eq this-command 'org-agenda-todo)
13365 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13366 ;; Don't add undo information when called from `org-agenda-todo'.
13367 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13368 (set-window-configuration org-log-note-window-configuration)
13369 (with-current-buffer (marker-buffer org-log-note-return-to)
13370 (goto-char org-log-note-return-to))
13371 (move-marker org-log-note-return-to nil)
13372 (when org-log-post-message (message "%s" org-log-post-message))))
13374 (defun org-remove-empty-drawer-at (pos)
13375 "Remove an empty drawer at position POS.
13376 POS may also be a marker."
13377 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13378 (org-with-wide-buffer
13379 (goto-char pos)
13380 (let ((drawer (org-element-at-point)))
13381 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13382 (not (org-element-property :contents-begin drawer)))
13383 (delete-region (org-element-property :begin drawer)
13384 (progn (goto-char (org-element-property :end drawer))
13385 (skip-chars-backward " \r\t\n")
13386 (forward-line)
13387 (point))))))))
13389 (defvar org-ts-type nil)
13390 (defun org-sparse-tree (&optional arg type)
13391 "Create a sparse tree, prompt for the details.
13392 This command can create sparse trees. You first need to select the type
13393 of match used to create the tree:
13395 t Show all TODO entries.
13396 T Show entries with a specific TODO keyword.
13397 m Show entries selected by a tags/property match.
13398 p Enter a property name and its value (both with completion on existing
13399 names/values) and show entries with that property.
13400 r Show entries matching a regular expression (`/' can be used as well).
13401 b Show deadlines and scheduled items before a date.
13402 a Show deadlines and scheduled items after a date.
13403 d Show deadlines due within `org-deadline-warning-days'.
13404 D Show deadlines and scheduled items between a date range."
13405 (interactive "P")
13406 (setq type (or type org-sparse-tree-default-date-type))
13407 (setq org-ts-type type)
13408 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13409 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13410 \[c]ycle through date types: %s"
13411 (cl-case type
13412 (all "all timestamps")
13413 (scheduled "only scheduled")
13414 (deadline "only deadline")
13415 (active "only active timestamps")
13416 (inactive "only inactive timestamps")
13417 (closed "with a closed time-stamp")
13418 (otherwise "scheduled/deadline")))
13419 (let ((answer (read-char-exclusive)))
13420 (cl-case answer
13422 (org-sparse-tree
13424 (cadr
13425 (memq type '(nil all scheduled deadline active inactive closed)))))
13426 (?d (call-interactively 'org-check-deadlines))
13427 (?b (call-interactively 'org-check-before-date))
13428 (?a (call-interactively 'org-check-after-date))
13429 (?D (call-interactively 'org-check-dates-range))
13430 (?t (call-interactively 'org-show-todo-tree))
13431 (?T (org-show-todo-tree '(4)))
13432 (?m (call-interactively 'org-match-sparse-tree))
13433 ((?p ?P)
13434 (let* ((kwd (completing-read
13435 "Property: " (mapcar #'list (org-buffer-property-keys))))
13436 (value (completing-read
13437 "Value: " (mapcar #'list (org-property-values kwd)))))
13438 (unless (string-match "\\`{.*}\\'" value)
13439 (setq value (concat "\"" value "\"")))
13440 (org-match-sparse-tree arg (concat kwd "=" value))))
13441 ((?r ?R ?/) (call-interactively 'org-occur))
13442 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13444 (defvar-local org-occur-highlights nil
13445 "List of overlays used for occur matches.")
13446 (defvar-local org-occur-parameters nil
13447 "Parameters of the active org-occur calls.
13448 This is a list, each call to org-occur pushes as cons cell,
13449 containing the regular expression and the callback, onto the list.
13450 The list can contain several entries if `org-occur' has been called
13451 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13452 will only contain one set of parameters. When the highlights are
13453 removed (for example with `C-c C-c', or with the next edit (depending
13454 on `org-remove-highlights-with-change'), this variable is emptied
13455 as well.")
13457 (defun org-occur (regexp &optional keep-previous callback)
13458 "Make a compact tree which shows all matches of REGEXP.
13460 The tree will show the lines where the regexp matches, and any other context
13461 defined in `org-show-context-detail', which see.
13463 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13464 done by a previous call to `org-occur' will be kept, to allow stacking of
13465 calls to this command.
13467 Optional argument CALLBACK can be a function of no argument. In this case,
13468 it is called with point at the end of the match, match data being set
13469 accordingly. Current match is shown only if the return value is non-nil.
13470 The function must neither move point nor alter narrowing."
13471 (interactive "sRegexp: \nP")
13472 (when (equal regexp "")
13473 (user-error "Regexp cannot be empty"))
13474 (unless keep-previous
13475 (org-remove-occur-highlights nil nil t))
13476 (push (cons regexp callback) org-occur-parameters)
13477 (let ((cnt 0))
13478 (save-excursion
13479 (goto-char (point-min))
13480 (when (or (not keep-previous) ; do not want to keep
13481 (not org-occur-highlights)) ; no previous matches
13482 ;; hide everything
13483 (org-overview))
13484 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13485 (isearch-no-upper-case-p regexp t)
13486 org-occur-case-fold-search)))
13487 (while (re-search-forward regexp nil t)
13488 (when (or (not callback)
13489 (save-match-data (funcall callback)))
13490 (setq cnt (1+ cnt))
13491 (when org-highlight-sparse-tree-matches
13492 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13493 (org-show-context 'occur-tree)))))
13494 (when org-remove-highlights-with-change
13495 (add-hook 'before-change-functions 'org-remove-occur-highlights
13496 nil 'local))
13497 (unless org-sparse-tree-open-archived-trees
13498 (org-hide-archived-subtrees (point-min) (point-max)))
13499 (run-hooks 'org-occur-hook)
13500 (when (called-interactively-p 'interactive)
13501 (message "%d match(es) for regexp %s" cnt regexp))
13502 cnt))
13504 (defun org-occur-next-match (&optional n _reset)
13505 "Function for `next-error-function' to find sparse tree matches.
13506 N is the number of matches to move, when negative move backwards.
13507 This function always goes back to the starting point when no
13508 match is found."
13509 (let* ((limit (if (< n 0) (point-min) (point-max)))
13510 (search-func (if (< n 0)
13511 'previous-single-char-property-change
13512 'next-single-char-property-change))
13513 (n (abs n))
13514 (pos (point))
13516 (catch 'exit
13517 (while (setq p1 (funcall search-func (point) 'org-type))
13518 (when (equal p1 limit)
13519 (goto-char pos)
13520 (user-error "No more matches"))
13521 (when (equal (get-char-property p1 'org-type) 'org-occur)
13522 (setq n (1- n))
13523 (when (= n 0)
13524 (goto-char p1)
13525 (throw 'exit (point))))
13526 (goto-char p1))
13527 (goto-char p1)
13528 (user-error "No more matches"))))
13530 (defun org-show-context (&optional key)
13531 "Make sure point and context are visible.
13532 Optional argument KEY, when non-nil, is a symbol. See
13533 `org-show-context-detail' for allowed values and how much is to
13534 be shown."
13535 (org-show-set-visibility
13536 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13537 ((cdr (assq key org-show-context-detail)))
13538 (t (cdr (assq 'default org-show-context-detail))))))
13540 (defun org-show-set-visibility (detail)
13541 "Set visibility around point according to DETAIL.
13542 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13543 `tree', `canonical' or t. See `org-show-context-detail' for more
13544 information."
13545 ;; Show current heading and possibly its entry, following headline
13546 ;; or all children.
13547 (if (and (org-at-heading-p) (not (eq detail 'local)))
13548 (org-flag-heading nil)
13549 (org-show-entry)
13550 ;; If point is hidden within a drawer or a block, make sure to
13551 ;; expose it.
13552 (dolist (o (overlays-at (point)))
13553 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13554 (delete-overlay o)))
13555 (unless (org-before-first-heading-p)
13556 (org-with-limited-levels
13557 (cl-case detail
13558 ((tree canonical t) (org-show-children))
13559 ((nil minimal ancestors))
13560 (t (save-excursion
13561 (outline-next-heading)
13562 (org-flag-heading nil)))))))
13563 ;; Show all siblings.
13564 (when (eq detail 'lineage) (org-show-siblings))
13565 ;; Show ancestors, possibly with their children.
13566 (when (memq detail '(ancestors lineage tree canonical t))
13567 (save-excursion
13568 (while (org-up-heading-safe)
13569 (org-flag-heading nil)
13570 (when (memq detail '(canonical t)) (org-show-entry))
13571 (when (memq detail '(tree canonical t)) (org-show-children))))))
13573 (defvar org-reveal-start-hook nil
13574 "Hook run before revealing a location.")
13576 (defun org-reveal (&optional siblings)
13577 "Show current entry, hierarchy above it, and the following headline.
13579 This can be used to show a consistent set of context around
13580 locations exposed with `org-show-context'.
13582 With optional argument SIBLINGS, on each level of the hierarchy all
13583 siblings are shown. This repairs the tree structure to what it would
13584 look like when opened with hierarchical calls to `org-cycle'.
13586 With a \\[universal-argument] \\[universal-argument] prefix, \
13587 go to the parent and show the entire tree."
13588 (interactive "P")
13589 (run-hooks 'org-reveal-start-hook)
13590 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13591 ((equal siblings '(16))
13592 (save-excursion
13593 (when (org-up-heading-safe)
13594 (org-show-subtree)
13595 (run-hook-with-args 'org-cycle-hook 'subtree))))
13596 (t (org-show-set-visibility 'lineage))))
13598 (defun org-highlight-new-match (beg end)
13599 "Highlight from BEG to END and mark the highlight is an occur headline."
13600 (let ((ov (make-overlay beg end)))
13601 (overlay-put ov 'face 'secondary-selection)
13602 (overlay-put ov 'org-type 'org-occur)
13603 (push ov org-occur-highlights)))
13605 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13606 "Remove the occur highlights from the buffer.
13607 BEG and END are ignored. If NOREMOVE is nil, remove this function
13608 from the `before-change-functions' in the current buffer."
13609 (interactive)
13610 (unless org-inhibit-highlight-removal
13611 (mapc #'delete-overlay org-occur-highlights)
13612 (setq org-occur-highlights nil)
13613 (setq org-occur-parameters nil)
13614 (unless noremove
13615 (remove-hook 'before-change-functions
13616 'org-remove-occur-highlights 'local))))
13618 ;;;; Priorities
13620 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13621 "Regular expression matching the priority indicator.")
13623 (defvar org-remove-priority-next-time nil)
13625 (defun org-priority-up ()
13626 "Increase the priority of the current item."
13627 (interactive)
13628 (org-priority 'up))
13630 (defun org-priority-down ()
13631 "Decrease the priority of the current item."
13632 (interactive)
13633 (org-priority 'down))
13635 (defun org-priority (&optional action _show)
13636 "Change the priority of an item.
13637 ACTION can be `set', `up', `down', or a character."
13638 (interactive "P")
13639 (if (equal action '(4))
13640 (org-show-priority)
13641 (unless org-enable-priority-commands
13642 (user-error "Priority commands are disabled"))
13643 (setq action (or action 'set))
13644 (let (current new news have remove)
13645 (save-excursion
13646 (org-back-to-heading t)
13647 (when (looking-at org-priority-regexp)
13648 (setq current (string-to-char (match-string 2))
13649 have t))
13650 (cond
13651 ((eq action 'remove)
13652 (setq remove t new ?\ ))
13653 ((or (eq action 'set)
13654 (integerp action))
13655 (if (not (eq action 'set))
13656 (setq new action)
13657 (message "Priority %c-%c, SPC to remove: "
13658 org-highest-priority org-lowest-priority)
13659 (save-match-data
13660 (setq new (read-char-exclusive))))
13661 (when (and (= (upcase org-highest-priority) org-highest-priority)
13662 (= (upcase org-lowest-priority) org-lowest-priority))
13663 (setq new (upcase new)))
13664 (cond ((equal new ?\ ) (setq remove t))
13665 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13666 (user-error "Priority must be between `%c' and `%c'"
13667 org-highest-priority org-lowest-priority))))
13668 ((eq action 'up)
13669 (setq new (if have
13670 (1- current) ; normal cycling
13671 ;; last priority was empty
13672 (if (eq last-command this-command)
13673 org-lowest-priority ; wrap around empty to lowest
13674 ;; default
13675 (if org-priority-start-cycle-with-default
13676 org-default-priority
13677 (1- org-default-priority))))))
13678 ((eq action 'down)
13679 (setq new (if have
13680 (1+ current) ; normal cycling
13681 ;; last priority was empty
13682 (if (eq last-command this-command)
13683 org-highest-priority ; wrap around empty to highest
13684 ;; default
13685 (if org-priority-start-cycle-with-default
13686 org-default-priority
13687 (1+ org-default-priority))))))
13688 (t (user-error "Invalid action")))
13689 (when (or (< (upcase new) org-highest-priority)
13690 (> (upcase new) org-lowest-priority))
13691 (if (and (memq action '(up down))
13692 (not have) (not (eq last-command this-command)))
13693 ;; `new' is from default priority
13694 (error
13695 "The default can not be set, see `org-default-priority' why")
13696 ;; normal cycling: `new' is beyond highest/lowest priority
13697 ;; and is wrapped around to the empty priority
13698 (setq remove t)))
13699 (setq news (format "%c" new))
13700 (if have
13701 (if remove
13702 (replace-match "" t t nil 1)
13703 (replace-match news t t nil 2))
13704 (if remove
13705 (user-error "No priority cookie found in line")
13706 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13707 (if (match-end 2)
13708 (progn
13709 (goto-char (match-end 2))
13710 (insert " [#" news "]"))
13711 (goto-char (match-beginning 3))
13712 (insert "[#" news "] "))))
13713 (org-set-tags nil 'align))
13714 (if remove
13715 (message "Priority removed")
13716 (message "Priority of current item set to %s" news)))))
13718 (defun org-show-priority ()
13719 "Show the priority of the current item.
13720 This priority is composed of the main priority given with the [#A] cookies,
13721 and by additional input from the age of a schedules or deadline entry."
13722 (interactive)
13723 (let ((pri (if (eq major-mode 'org-agenda-mode)
13724 (org-get-at-bol 'priority)
13725 (save-excursion
13726 (save-match-data
13727 (beginning-of-line)
13728 (and (looking-at org-heading-regexp)
13729 (org-get-priority (match-string 0))))))))
13730 (message "Priority is %d" (if pri pri -1000))))
13732 (defun org-get-priority (s)
13733 "Find priority cookie and return priority."
13734 (save-match-data
13735 (if (functionp org-get-priority-function)
13736 (funcall org-get-priority-function)
13737 (if (not (string-match org-priority-regexp s))
13738 (* 1000 (- org-lowest-priority org-default-priority))
13739 (* 1000 (- org-lowest-priority
13740 (string-to-char (match-string 2 s))))))))
13742 ;;;; Tags
13744 (defvar org-agenda-archives-mode)
13745 (defvar org-map-continue-from nil
13746 "Position from where mapping should continue.
13747 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13749 (defvar org-scanner-tags nil
13750 "The current tag list while the tags scanner is running.")
13752 (defvar org-trust-scanner-tags nil
13753 "Should `org-get-tags-at' use the tags for the scanner.
13754 This is for internal dynamical scoping only.
13755 When this is non-nil, the function `org-get-tags-at' will return the value
13756 of `org-scanner-tags' instead of building the list by itself. This
13757 can lead to large speed-ups when the tags scanner is used in a file with
13758 many entries, and when the list of tags is retrieved, for example to
13759 obtain a list of properties. Building the tags list for each entry in such
13760 a file becomes an N^2 operation - but with this variable set, it scales
13761 as N.")
13763 (defvar org--matcher-tags-todo-only nil)
13765 (defun org-scan-tags (action matcher todo-only &optional start-level)
13766 "Scan headline tags with inheritance and produce output ACTION.
13768 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13769 or `agenda' to produce an entry list for an agenda view. It can also be
13770 a Lisp form or a function that should be called at each matched headline, in
13771 this case the return value is a list of all return values from these calls.
13773 MATCHER is a function accepting three arguments, returning
13774 a non-nil value whenever a given set of tags qualifies a headline
13775 for inclusion. See `org-make-tags-matcher' for more information.
13776 As a special case, it can also be set to t (respectively nil) in
13777 order to match all (respectively none) headline.
13779 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13780 included in the output.
13782 START-LEVEL can be a string with asterisks, reducing the scope to
13783 headlines matching this string."
13784 (require 'org-agenda)
13785 (let* ((re (concat "^"
13786 (if start-level
13787 ;; Get the correct level to match
13788 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13789 org-outline-regexp)
13790 " *\\(\\<\\("
13791 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13792 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13793 (props (list 'face 'default
13794 'done-face 'org-agenda-done
13795 'undone-face 'default
13796 'mouse-face 'highlight
13797 'org-not-done-regexp org-not-done-regexp
13798 'org-todo-regexp org-todo-regexp
13799 'org-complex-heading-regexp org-complex-heading-regexp
13800 'help-echo
13801 (format "mouse-2 or RET jump to org file %s"
13802 (abbreviate-file-name
13803 (or (buffer-file-name (buffer-base-buffer))
13804 (buffer-name (buffer-base-buffer)))))))
13805 (org-map-continue-from nil)
13806 lspos tags tags-list
13807 (tags-alist (list (cons 0 org-file-tags)))
13808 (llast 0) rtn rtn1 level category i txt
13809 todo marker entry priority
13810 ts-date ts-date-type ts-date-pair)
13811 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13812 (setq action (list 'lambda nil action)))
13813 (save-excursion
13814 (goto-char (point-min))
13815 (when (eq action 'sparse-tree)
13816 (org-overview)
13817 (org-remove-occur-highlights))
13818 (while (let (case-fold-search)
13819 (re-search-forward re nil t))
13820 (setq org-map-continue-from nil)
13821 (catch :skip
13822 (setq todo
13823 ;; TODO: is the 1-2 difference a bug?
13824 (when (match-end 1) (match-string-no-properties 2))
13825 tags (when (match-end 4) (match-string-no-properties 4)))
13826 (goto-char (setq lspos (match-beginning 0)))
13827 (setq level (org-reduced-level (org-outline-level))
13828 category (org-get-category))
13829 (when (eq action 'agenda)
13830 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13831 ts-date (car ts-date-pair)
13832 ts-date-type (cdr ts-date-pair)))
13833 (setq i llast llast level)
13834 ;; remove tag lists from same and sublevels
13835 (while (>= i level)
13836 (when (setq entry (assoc i tags-alist))
13837 (setq tags-alist (delete entry tags-alist)))
13838 (setq i (1- i)))
13839 ;; add the next tags
13840 (when tags
13841 (setq tags (org-split-string tags ":")
13842 tags-alist
13843 (cons (cons level tags) tags-alist)))
13844 ;; compile tags for current headline
13845 (setq tags-list
13846 (if org-use-tag-inheritance
13847 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13848 tags)
13849 org-scanner-tags tags-list)
13850 (when org-use-tag-inheritance
13851 (setcdr (car tags-alist)
13852 (mapcar (lambda (x)
13853 (setq x (copy-sequence x))
13854 (org-add-prop-inherited x))
13855 (cdar tags-alist))))
13856 (when (and tags org-use-tag-inheritance
13857 (or (not (eq t org-use-tag-inheritance))
13858 org-tags-exclude-from-inheritance))
13859 ;; Selective inheritance, remove uninherited ones.
13860 (setcdr (car tags-alist)
13861 (org-remove-uninherited-tags (cdar tags-alist))))
13862 (when (and
13864 ;; eval matcher only when the todo condition is OK
13865 (and (or (not todo-only) (member todo org-todo-keywords-1))
13866 (if (functionp matcher)
13867 (let ((case-fold-search t) (org-trust-scanner-tags t))
13868 (funcall matcher todo tags-list level))
13869 matcher))
13871 ;; Call the skipper, but return t if it does not
13872 ;; skip, so that the `and' form continues evaluating.
13873 (progn
13874 (unless (eq action 'sparse-tree) (org-agenda-skip))
13877 ;; Check if timestamps are deselecting this entry
13878 (or (not todo-only)
13879 (and (member todo org-todo-keywords-1)
13880 (or (not org-agenda-tags-todo-honor-ignore-options)
13881 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13883 ;; select this headline
13884 (cond
13885 ((eq action 'sparse-tree)
13886 (and org-highlight-sparse-tree-matches
13887 (org-get-heading) (match-end 0)
13888 (org-highlight-new-match
13889 (match-beginning 1) (match-end 1)))
13890 (org-show-context 'tags-tree))
13891 ((eq action 'agenda)
13892 (setq txt (org-agenda-format-item
13894 (concat
13895 (if (eq org-tags-match-list-sublevels 'indented)
13896 (make-string (1- level) ?.) "")
13897 (org-get-heading))
13898 (make-string level ?\s)
13899 category
13900 tags-list)
13901 priority (org-get-priority txt))
13902 (goto-char lspos)
13903 (setq marker (org-agenda-new-marker))
13904 (org-add-props txt props
13905 'org-marker marker 'org-hd-marker marker 'org-category category
13906 'todo-state todo
13907 'ts-date ts-date
13908 'priority priority
13909 'type (concat "tagsmatch" ts-date-type))
13910 (push txt rtn))
13911 ((functionp action)
13912 (setq org-map-continue-from nil)
13913 (save-excursion
13914 (setq rtn1 (funcall action))
13915 (push rtn1 rtn)))
13916 (t (user-error "Invalid action")))
13918 ;; if we are to skip sublevels, jump to end of subtree
13919 (unless org-tags-match-list-sublevels
13920 (org-end-of-subtree t)
13921 (backward-char 1))))
13922 ;; Get the correct position from where to continue
13923 (if org-map-continue-from
13924 (goto-char org-map-continue-from)
13925 (and (= (point) lspos) (end-of-line 1)))))
13926 (when (and (eq action 'sparse-tree)
13927 (not org-sparse-tree-open-archived-trees))
13928 (org-hide-archived-subtrees (point-min) (point-max)))
13929 (nreverse rtn)))
13931 (defun org-remove-uninherited-tags (tags)
13932 "Remove all tags that are not inherited from the list TAGS."
13933 (cond
13934 ((eq org-use-tag-inheritance t)
13935 (if org-tags-exclude-from-inheritance
13936 (org-delete-all org-tags-exclude-from-inheritance tags)
13937 tags))
13938 ((not org-use-tag-inheritance) nil)
13939 ((stringp org-use-tag-inheritance)
13940 (delq nil (mapcar
13941 (lambda (x)
13942 (if (and (string-match org-use-tag-inheritance x)
13943 (not (member x org-tags-exclude-from-inheritance)))
13944 x nil))
13945 tags)))
13946 ((listp org-use-tag-inheritance)
13947 (delq nil (mapcar
13948 (lambda (x)
13949 (if (member x org-use-tag-inheritance) x nil))
13950 tags)))))
13952 (defun org-match-sparse-tree (&optional todo-only match)
13953 "Create a sparse tree according to tags string MATCH.
13955 MATCH is a string with match syntax. It can contain a selection
13956 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13957 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13958 those. See the manual for details.
13960 If optional argument TODO-ONLY is non-nil, only select lines that
13961 are also TODO tasks."
13962 (interactive "P")
13963 (org-agenda-prepare-buffers (list (current-buffer)))
13964 (let ((org--matcher-tags-todo-only todo-only))
13965 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13966 org--matcher-tags-todo-only)))
13968 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13970 (defvar org-cached-props nil)
13971 (defun org-cached-entry-get (pom property)
13972 (if (or (eq t org-use-property-inheritance)
13973 (and (stringp org-use-property-inheritance)
13974 (let ((case-fold-search t))
13975 (string-match-p org-use-property-inheritance property)))
13976 (and (listp org-use-property-inheritance)
13977 (member-ignore-case property org-use-property-inheritance)))
13978 ;; Caching is not possible, check it directly.
13979 (org-entry-get pom property 'inherit)
13980 ;; Get all properties, so we can do complicated checks easily.
13981 (cdr (assoc-string property
13982 (or org-cached-props
13983 (setq org-cached-props (org-entry-properties pom)))
13984 t))))
13986 (defun org-global-tags-completion-table (&optional files)
13987 "Return the list of all tags in all agenda buffer/files.
13988 Optional FILES argument is a list of files which can be used
13989 instead of the agenda files."
13990 (save-excursion
13991 (org-uniquify
13992 (delq nil
13993 (apply #'append
13994 (mapcar
13995 (lambda (file)
13996 (set-buffer (find-file-noselect file))
13997 (mapcar (lambda (x)
13998 (and (stringp (car-safe x))
13999 (list (car-safe x))))
14000 (or org-current-tag-alist (org-get-buffer-tags))))
14001 (if (car-safe files) files
14002 (org-agenda-files))))))))
14004 (defun org-make-tags-matcher (match)
14005 "Create the TAGS/TODO matcher form for the selection string MATCH.
14007 Returns a cons of the selection string MATCH and a function
14008 implementing the matcher.
14010 The matcher is to be called at an Org entry, with point on the
14011 headline, and returns non-nil if the entry matches the selection
14012 string MATCH. It must be called with three arguments: the TODO
14013 keyword at the entry (or nil if none), the list of all tags at
14014 the entry including inherited ones and the reduced level of the
14015 headline. Additionally, the category of the entry, if any, must
14016 be specified as the text property `org-category' on the headline.
14018 This function sets the variable `org--matcher-tags-todo-only' to
14019 a non-nil value if the matcher restricts matching to TODO
14020 entries, otherwise it is not touched.
14022 See also `org-scan-tags'."
14023 (unless match
14024 ;; Get a new match request, with completion against the global
14025 ;; tags table and the local tags in current buffer.
14026 (let ((org-last-tags-completion-table
14027 (org-uniquify
14028 (delq nil (append (org-get-buffer-tags)
14029 (org-global-tags-completion-table))))))
14030 (setq match
14031 (completing-read
14032 "Match: "
14033 'org-tags-completion-function nil nil nil 'org-tags-history))))
14035 (let ((match0 match)
14036 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14037 (start 0)
14038 tagsmatch todomatch tagsmatcher todomatcher)
14040 ;; Expand group tags.
14041 (setq match (org-tags-expand match))
14043 ;; Check if there is a TODO part of this match, which would be the
14044 ;; part after a "/". To make sure that this slash is not part of
14045 ;; a property value to be matched against, we also check that
14046 ;; there is no / after that slash. First, find the last slash.
14047 (let ((s 0))
14048 (while (string-match "/+" match s)
14049 (setq start (match-beginning 0))
14050 (setq s (match-end 0))))
14051 (if (and (string-match "/+" match start)
14052 (not (string-match-p "\"" match start)))
14053 ;; Match contains also a TODO-matching request.
14054 (progn
14055 (setq tagsmatch (substring match 0 (match-beginning 0)))
14056 (setq todomatch (substring match (match-end 0)))
14057 (when (string-prefix-p "!" todomatch)
14058 (setq org--matcher-tags-todo-only t)
14059 (setq todomatch (substring todomatch 1)))
14060 (when (string-match "\\`\\s-*\\'" todomatch)
14061 (setq todomatch nil)))
14062 ;; Only matching tags.
14063 (setq tagsmatch match)
14064 (setq todomatch nil))
14066 ;; Make the tags matcher.
14067 (when (org-string-nw-p tagsmatch)
14068 (let ((orlist nil)
14069 (orterms (org-split-string tagsmatch "|"))
14070 term)
14071 (while (setq term (pop orterms))
14072 (while (and (equal (substring term -1) "\\") orterms)
14073 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14074 (while (string-match re term)
14075 (let* ((rest (substring term (match-end 0)))
14076 (minus (and (match-end 1)
14077 (equal (match-string 1 term) "-")))
14078 (tag (save-match-data
14079 (replace-regexp-in-string
14080 "\\\\-" "-" (match-string 2 term))))
14081 (regexp (eq (string-to-char tag) ?{))
14082 (levelp (match-end 4))
14083 (propp (match-end 5))
14085 (cond
14086 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14087 (levelp
14088 `(,(org-op-to-function (match-string 3 term))
14089 level
14090 ,(string-to-number (match-string 4 term))))
14091 (propp
14092 (let* ((gv (pcase (upcase (match-string 5 term))
14093 ("CATEGORY"
14094 '(get-text-property (point) 'org-category))
14095 ("TODO" 'todo)
14096 (p `(org-cached-entry-get nil ,p))))
14097 (pv (match-string 7 term))
14098 (regexp (eq (string-to-char pv) ?{))
14099 (strp (eq (string-to-char pv) ?\"))
14100 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14101 (po (org-op-to-function (match-string 6 term)
14102 (if timep 'time strp))))
14103 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14104 (when timep (setq pv (org-matcher-time pv)))
14105 (cond ((and regexp (eq po 'org<>))
14106 `(not (string-match ,pv (or ,gv ""))))
14107 (regexp `(string-match ,pv (or ,gv "")))
14108 (strp `(,po (or ,gv "") ,pv))
14110 `(,po
14111 (string-to-number (or ,gv ""))
14112 ,(string-to-number pv))))))
14113 (t `(member ,tag tags-list)))))
14114 (push (if minus `(not ,mm) mm) tagsmatcher)
14115 (setq term rest)))
14116 (push `(and ,@tagsmatcher) orlist)
14117 (setq tagsmatcher nil))
14118 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14120 ;; Make the TODO matcher.
14121 (when (org-string-nw-p todomatch)
14122 (let ((orlist nil))
14123 (dolist (term (org-split-string todomatch "|"))
14124 (while (string-match re term)
14125 (let* ((minus (and (match-end 1)
14126 (equal (match-string 1 term) "-")))
14127 (kwd (match-string 2 term))
14128 (regexp (eq (string-to-char kwd) ?{))
14129 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14130 `(equal todo ,kwd))))
14131 (push (if minus `(not ,mm) mm) todomatcher))
14132 (setq term (substring term (match-end 0))))
14133 (push (if (> (length todomatcher) 1)
14134 (cons 'and todomatcher)
14135 (car todomatcher))
14136 orlist)
14137 (setq todomatcher nil))
14138 (setq todomatcher (cons 'or orlist))))
14140 ;; Return the string and function of the matcher. If no
14141 ;; tags-specific or todo-specific matcher exists, match
14142 ;; everything.
14143 (let ((matcher (if (and tagsmatcher todomatcher)
14144 `(and ,tagsmatcher ,todomatcher)
14145 (or tagsmatcher todomatcher t))))
14146 (when org--matcher-tags-todo-only
14147 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14148 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14150 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14151 "Expand group tags in MATCH.
14153 This replaces every group tag in MATCH with a regexp tag search.
14154 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14155 will be replaced like this:
14157 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14158 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14159 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14161 Replacing by a regexp preserves the structure of the match.
14162 E.g., this expansion
14164 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14166 will match anything tagged with \"Lab\" and \"Home\", or tagged
14167 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14169 A group tag in MATCH can contain regular expressions of its own.
14170 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14171 will be replaced like this:
14173 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14175 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14176 assumed to be a single group tag, and the function will return
14177 the list of tags in this group.
14179 When DOWNCASE is non-nil, expand downcased TAGS."
14180 (if org-group-tags
14181 (let* ((case-fold-search t)
14182 (stable org-mode-syntax-table)
14183 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14184 (taggroups (if downcased
14185 (mapcar (lambda (tg) (mapcar #'downcase tg))
14186 taggroups)
14187 taggroups))
14188 (taggroups-keys (mapcar #'car taggroups))
14189 (return-match (if downcased (downcase match) match))
14190 (count 0)
14191 (work-already-expanded tags-already-expanded)
14192 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14193 ;; @ and _ are allowed as word-components in tags.
14194 (modify-syntax-entry ?@ "w" stable)
14195 (modify-syntax-entry ?_ "w" stable)
14196 ;; Temporarily replace regexp-expressions in the match-expression.
14197 (while (string-match "{.+?}" return-match)
14198 (cl-incf count)
14199 (push (match-string 0 return-match) regexps-in-match)
14200 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14201 (while (and taggroups-keys
14202 (with-syntax-table stable
14203 (string-match
14204 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14205 (regexp-opt taggroups-keys) "\\>\\)")
14206 return-match)))
14207 (let* ((dir (match-string 1 return-match))
14208 (tag (match-string 2 return-match))
14209 (tag (if downcased (downcase tag) tag)))
14210 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14211 (member tag work-already-expanded))
14212 (setq tags-in-group (assoc tag taggroups))
14213 (push tag work-already-expanded)
14214 ;; Recursively expand each tag in the group, if the tag hasn't
14215 ;; already been expanded. Restore the match-data after all recursive calls.
14216 (save-match-data
14217 (let (tags-expanded)
14218 (dolist (x (cdr tags-in-group))
14219 (if (and (member x taggroups-keys)
14220 (not (member x work-already-expanded)))
14221 (setq tags-expanded
14222 (delete-dups
14223 (append
14224 (org-tags-expand x t downcased
14225 work-already-expanded)
14226 tags-expanded)))
14227 (setq tags-expanded
14228 (append (list x) tags-expanded)))
14229 (setq work-already-expanded
14230 (delete-dups
14231 (append tags-expanded
14232 work-already-expanded))))
14233 (setq tags-in-group
14234 (delete-dups (cons (car tags-in-group)
14235 tags-expanded)))))
14236 ;; Filter tag-regexps from tags.
14237 (setq regexp-in-group-escaped
14238 (delq nil (mapcar (lambda (x)
14239 (if (stringp x)
14240 (and (equal "{" (substring x 0 1))
14241 (equal "}" (substring x -1))
14244 tags-in-group))
14245 regexp-in-group
14246 (mapcar (lambda (x)
14247 (substring x 1 -1))
14248 regexp-in-group-escaped)
14249 tags-in-group
14250 (delq nil (mapcar (lambda (x)
14251 (if (stringp x)
14252 (and (not (equal "{" (substring x 0 1)))
14253 (not (equal "}" (substring x -1)))
14256 tags-in-group)))
14257 ;; If single-as-list, do no more in the while-loop.
14258 (if (not single-as-list)
14259 (progn
14260 (when regexp-in-group
14261 (setq regexp-in-group
14262 (concat "\\|"
14263 (mapconcat 'identity regexp-in-group
14264 "\\|"))))
14265 (setq tags-in-group
14266 (concat dir
14267 "{\\<"
14268 (regexp-opt tags-in-group)
14269 "\\>"
14270 regexp-in-group
14271 "}"))
14272 (when (stringp tags-in-group)
14273 (org-add-props tags-in-group '(grouptag t)))
14274 (setq return-match
14275 (replace-match tags-in-group t t return-match)))
14276 (setq tags-in-group
14277 (append regexp-in-group-escaped tags-in-group))))
14278 (setq taggroups-keys (delete tag taggroups-keys))))
14279 ;; Add the regular expressions back into the match-expression again.
14280 (while regexps-in-match
14281 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14282 (pop regexps-in-match)
14283 return-match t t))
14284 (cl-decf count))
14285 (if single-as-list
14286 (if tags-in-group tags-in-group (list return-match))
14287 return-match))
14288 (if single-as-list
14289 (list (if downcased (downcase match) match))
14290 match)))
14292 (defun org-op-to-function (op &optional stringp)
14293 "Turn an operator into the appropriate function."
14294 (setq op
14295 (cond
14296 ((equal op "<" ) '(< string< org-time<))
14297 ((equal op ">" ) '(> org-string> org-time>))
14298 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14299 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14300 ((member op '("=" "==")) '(= string= org-time=))
14301 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14302 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14304 (defun org<> (a b) (not (= a b)))
14305 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14306 (defun org-string>= (a b) (not (string< a b)))
14307 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14308 (defun org-string<> (a b) (not (string= a b)))
14309 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14310 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14311 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14312 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14313 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14314 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14315 (defun org-2ft (s)
14316 "Convert S to a floating point time.
14317 If S is already a number, just return it. If it is a string, parse
14318 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14319 (cond
14320 ((numberp s) s)
14321 ((stringp s)
14322 (condition-case nil
14323 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14324 (error 0.)))
14325 (t 0.)))
14327 (defun org-time-today ()
14328 "Time in seconds today at 0:00.
14329 Returns the float number of seconds since the beginning of the
14330 epoch to the beginning of today (00:00)."
14331 (float-time (apply 'encode-time
14332 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14334 (defun org-matcher-time (s)
14335 "Interpret a time comparison value."
14336 (save-match-data
14337 (cond
14338 ((string= s "<now>") (float-time))
14339 ((string= s "<today>") (org-time-today))
14340 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14341 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14342 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14343 (+ (org-time-today)
14344 (* (string-to-number (match-string 1 s))
14345 (cdr (assoc (match-string 2 s)
14346 '(("d" . 86400.0) ("w" . 604800.0)
14347 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14348 (t (org-2ft s)))))
14350 (defun org-match-any-p (re list)
14351 "Does re match any element of list?"
14352 (setq list (mapcar (lambda (x) (string-match re x)) list))
14353 (delq nil list))
14355 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14356 (defvar org-tags-overlay (make-overlay 1 1))
14357 (delete-overlay org-tags-overlay)
14359 (defun org-get-local-tags-at (&optional pos)
14360 "Get a list of tags defined in the current headline."
14361 (org-get-tags-at pos 'local))
14363 (defun org-get-local-tags ()
14364 "Get a list of tags defined in the current headline."
14365 (org-get-tags-at nil 'local))
14367 (defun org-get-tags-at (&optional pos local)
14368 "Get a list of all headline tags applicable at POS.
14369 POS defaults to point. If tags are inherited, the list contains
14370 the targets in the same sequence as the headlines appear, i.e.
14371 the tags of the current headline come last.
14372 When LOCAL is non-nil, only return tags from the current headline,
14373 ignore inherited ones."
14374 (interactive)
14375 (if (and org-trust-scanner-tags
14376 (or (not pos) (equal pos (point)))
14377 (not local))
14378 org-scanner-tags
14379 (let (tags ltags lastpos parent)
14380 (save-excursion
14381 (save-restriction
14382 (widen)
14383 (goto-char (or pos (point)))
14384 (save-match-data
14385 (catch 'done
14386 (condition-case nil
14387 (progn
14388 (org-back-to-heading t)
14389 (while (not (equal lastpos (point)))
14390 (setq lastpos (point))
14391 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14392 (setq ltags (org-split-string
14393 (match-string-no-properties 1) ":"))
14394 (when parent
14395 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14396 (setq tags (append
14397 (if parent
14398 (org-remove-uninherited-tags ltags)
14399 ltags)
14400 tags)))
14401 (or org-use-tag-inheritance (throw 'done t))
14402 (when local (throw 'done t))
14403 (or (org-up-heading-safe) (error nil))
14404 (setq parent t)))
14405 (error nil)))))
14406 (if local
14407 tags
14408 (reverse (delete-dups
14409 (reverse (append
14410 (org-remove-uninherited-tags
14411 org-file-tags)
14412 tags)))))))))
14414 (defun org-add-prop-inherited (s)
14415 (add-text-properties 0 (length s) '(inherited t) s)
14418 (defun org-toggle-tag (tag &optional onoff)
14419 "Toggle the tag TAG for the current line.
14420 If ONOFF is `on' or `off', don't toggle but set to this state."
14421 (save-excursion
14422 (org-back-to-heading t)
14423 (let ((current
14424 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14425 (line-end-position) t)
14426 (let ((tags (match-string 1)))
14427 ;; Clear current tags.
14428 (replace-match "")
14429 ;; Reverse the tags list so any new tag is appended to
14430 ;; the current list of tags.
14431 (nreverse (org-split-string tags ":")))))
14432 res)
14433 (pcase onoff
14434 (`off (setq current (delete tag current)))
14435 ((or `on (guard (not (member tag current))))
14436 (setq res t)
14437 (cl-pushnew tag current :test #'equal))
14438 (_ (setq current (delete tag current))))
14439 (end-of-line)
14440 (if current
14441 (progn
14442 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14443 (org-set-tags nil t))
14444 (delete-horizontal-space))
14445 (run-hooks 'org-after-tags-change-hook)
14446 res)))
14448 (defun org--align-tags-here (to-col)
14449 "Align tags on the current headline to TO-COL.
14450 Assume point is on a headline."
14451 (let ((pos (point)))
14452 (beginning-of-line)
14453 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14454 (>= pos (match-beginning 2)))
14455 ;; No tags or point within tags: do not align.
14456 (goto-char pos)
14457 (goto-char (match-beginning 1))
14458 (let ((shift (max (- (if (>= to-col 0) to-col
14459 (- (abs to-col) (string-width (match-string 2))))
14460 (current-column))
14461 1)))
14462 (replace-match (make-string shift ?\s) nil nil nil 1)
14463 ;; Preserve initial position, if possible. In any case, stop
14464 ;; before tags.
14465 (when (< pos (point)) (goto-char pos))))))
14467 (defun org-set-tags-command (&optional arg just-align)
14468 "Call the set-tags command for the current entry."
14469 (interactive "P")
14470 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14471 (org-set-tags arg just-align)
14472 (save-excursion
14473 (unless (and (org-region-active-p)
14474 org-loop-over-headlines-in-active-region)
14475 (org-back-to-heading t))
14476 (org-set-tags arg just-align))))
14478 (defun org-set-tags-to (data)
14479 "Set the tags of the current entry to DATA, replacing the current tags.
14480 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14481 If DATA is nil or the empty string, any tags will be removed."
14482 (interactive "sTags: ")
14483 (setq data
14484 (cond
14485 ((eq data nil) "")
14486 ((equal data "") "")
14487 ((stringp data)
14488 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14489 ":"))
14490 ((listp data)
14491 (concat ":" (mapconcat 'identity data ":") ":"))))
14492 (when data
14493 (save-excursion
14494 (org-back-to-heading t)
14495 (when (let ((case-fold-search nil))
14496 (looking-at org-complex-heading-regexp))
14497 (if (match-end 5)
14498 (progn
14499 (goto-char (match-beginning 5))
14500 (insert data)
14501 (delete-region (point) (point-at-eol))
14502 (org-set-tags nil 'align))
14503 (goto-char (point-at-eol))
14504 (insert " " data)
14505 (org-set-tags nil 'align)))
14506 (beginning-of-line 1)
14507 (when (looking-at ".*?\\([ \t]+\\)$")
14508 (delete-region (match-beginning 1) (match-end 1))))))
14510 (defun org-align-all-tags ()
14511 "Align the tags in all headings."
14512 (interactive)
14513 (save-excursion
14514 (or (ignore-errors (org-back-to-heading t))
14515 (outline-next-heading))
14516 (if (org-at-heading-p)
14517 (org-set-tags t)
14518 (message "No headings"))))
14520 (defvar org-indent-indentation-per-level)
14521 (defun org-set-tags (&optional arg just-align)
14522 "Set the tags for the current headline.
14523 With prefix ARG, realign all tags in headings in the current buffer.
14524 When JUST-ALIGN is non-nil, only align tags."
14525 (interactive "P")
14526 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14527 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14528 'region-start-level
14529 'region))
14530 org-loop-over-headlines-in-active-region)
14531 (org-map-entries
14532 ;; We don't use ARG and JUST-ALIGN here because these args
14533 ;; are not useful when looping over headlines.
14534 #'org-set-tags
14535 org-loop-over-headlines-in-active-region
14537 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14538 (let ((org-setting-tags t))
14539 (if arg
14540 (save-excursion
14541 (goto-char (point-min))
14542 (while (re-search-forward org-outline-regexp-bol nil t)
14543 (org-set-tags nil t)
14544 (end-of-line))
14545 (message "All tags realigned to column %d" org-tags-column))
14546 (let* ((current (org-get-tags-string))
14547 (tags
14548 (if just-align current
14549 ;; Get a new set of tags from the user.
14550 (save-excursion
14551 (let* ((seen)
14552 (table
14553 (setq
14554 org-last-tags-completion-table
14555 ;; Uniquify tags in alists, yet preserve
14556 ;; structure (i.e., keywords).
14557 (delq nil
14558 (mapcar
14559 (lambda (pair)
14560 (let ((head (car pair)))
14561 (cond ((symbolp head) pair)
14562 ((member head seen) nil)
14563 (t (push head seen)
14564 pair))))
14565 (append
14566 (or org-current-tag-alist
14567 (org-get-buffer-tags))
14568 (and
14569 org-complete-tags-always-offer-all-agenda-tags
14570 (org-global-tags-completion-table
14571 (org-agenda-files))))))))
14572 (current-tags (org-split-string current ":"))
14573 (inherited-tags
14574 (nreverse (nthcdr (length current-tags)
14575 (nreverse (org-get-tags-at))))))
14576 (replace-regexp-in-string
14577 "\\([-+&]+\\|,\\)"
14579 (if (or (eq t org-use-fast-tag-selection)
14580 (and org-use-fast-tag-selection
14581 (delq nil (mapcar #'cdr table))))
14582 (org-fast-tag-selection
14583 current-tags inherited-tags table
14584 (and org-fast-tag-selection-include-todo
14585 org-todo-key-alist))
14586 (let ((org-add-colon-after-tag-completion
14587 (< 1 (length table))))
14588 (org-trim
14589 (completing-read
14590 "Tags: "
14591 #'org-tags-completion-function
14592 nil nil current 'org-tags-history))))))))))
14594 (when org-tags-sort-function
14595 (setq tags
14596 (mapconcat
14597 #'identity
14598 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14599 org-tags-sort-function)
14600 ":")))
14602 (if (or (string= ":" tags)
14603 (string= "::" tags))
14604 (setq tags ""))
14605 (if (not (org-string-nw-p tags)) (setq tags "")
14606 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14607 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14609 ;; Insert new tags at the correct column.
14610 (unless (equal current tags)
14611 (save-excursion
14612 (beginning-of-line)
14613 (let ((case-fold-search nil))
14614 (looking-at org-complex-heading-regexp))
14615 ;; Remove current tags, if any.
14616 (when (match-end 5) (replace-match "" nil nil nil 5))
14617 ;; Insert new tags, if any. Otherwise, remove trailing
14618 ;; white spaces.
14619 (end-of-line)
14620 (if (not (equal tags ""))
14621 ;; When text is being inserted on an invisible
14622 ;; region boundary, it can be inadvertently sucked
14623 ;; into invisibility.
14624 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14625 (skip-chars-backward " \t")
14626 (delete-region (point) (line-end-position)))))
14627 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14628 ;; is on.
14629 (unless (equal tags "")
14630 (let* ((level (save-excursion
14631 (beginning-of-line)
14632 (skip-chars-forward "\\*")))
14633 (offset (if (bound-and-true-p org-indent-mode)
14634 (* (1- org-indent-indentation-per-level)
14635 (1- level))
14637 (tags-column
14638 (+ org-tags-column
14639 (if (> org-tags-column 0) (- offset) offset))))
14640 (org--align-tags-here tags-column))))
14641 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14643 (defun org-change-tag-in-region (beg end tag off)
14644 "Add or remove TAG for each entry in the region.
14645 This works in the agenda, and also in an Org buffer."
14646 (interactive
14647 (list (region-beginning) (region-end)
14648 (let ((org-last-tags-completion-table
14649 (if (derived-mode-p 'org-mode)
14650 (org-uniquify
14651 (delq nil (append (org-get-buffer-tags)
14652 (org-global-tags-completion-table))))
14653 (org-global-tags-completion-table))))
14654 (completing-read
14655 "Tag: " 'org-tags-completion-function nil nil nil
14656 'org-tags-history))
14657 (progn
14658 (message "[s]et or [r]emove? ")
14659 (equal (read-char-exclusive) ?r))))
14660 (when (fboundp 'deactivate-mark) (deactivate-mark))
14661 (let ((agendap (equal major-mode 'org-agenda-mode))
14662 l1 l2 m buf pos newhead (cnt 0))
14663 (goto-char end)
14664 (setq l2 (1- (org-current-line)))
14665 (goto-char beg)
14666 (setq l1 (org-current-line))
14667 (cl-loop for l from l1 to l2 do
14668 (org-goto-line l)
14669 (setq m (get-text-property (point) 'org-hd-marker))
14670 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14671 (and agendap m))
14672 (setq buf (if agendap (marker-buffer m) (current-buffer))
14673 pos (if agendap m (point)))
14674 (with-current-buffer buf
14675 (save-excursion
14676 (save-restriction
14677 (goto-char pos)
14678 (setq cnt (1+ cnt))
14679 (org-toggle-tag tag (if off 'off 'on))
14680 (setq newhead (org-get-heading)))))
14681 (and agendap (org-agenda-change-all-lines newhead m))))
14682 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14684 (defun org-tags-completion-function (string _predicate &optional flag)
14685 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14686 (confirm (lambda (x) (stringp (car x)))))
14687 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14688 (setq s1 (match-string 1 string)
14689 s2 (match-string 2 string))
14690 (setq s1 "" s2 string))
14691 (cond
14692 ((eq flag nil)
14693 ;; try completion
14694 (setq rtn (try-completion s2 ctable confirm))
14695 (when (stringp rtn)
14696 (setq rtn
14697 (concat s1 s2 (substring rtn (length s2))
14698 (if (and org-add-colon-after-tag-completion
14699 (assoc rtn ctable))
14700 ":" ""))))
14701 rtn)
14702 ((eq flag t)
14703 ;; all-completions
14704 (all-completions s2 ctable confirm))
14705 ((eq flag 'lambda)
14706 ;; exact match?
14707 (assoc s2 ctable)))))
14709 (defun org-fast-tag-insert (kwd tags face &optional end)
14710 "Insert KDW, and the TAGS, the latter with face FACE.
14711 Also insert END."
14712 (insert (format "%-12s" (concat kwd ":"))
14713 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14714 (or end "")))
14716 (defun org-fast-tag-show-exit (flag)
14717 (save-excursion
14718 (org-goto-line 3)
14719 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14720 (replace-match ""))
14721 (when flag
14722 (end-of-line 1)
14723 (org-move-to-column (- (window-width) 19) t)
14724 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14726 (defun org-set-current-tags-overlay (current prefix)
14727 "Add an overlay to CURRENT tag with PREFIX."
14728 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14729 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14730 (org-overlay-display org-tags-overlay (concat prefix s))))
14732 (defvar org-last-tag-selection-key nil)
14733 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14734 "Fast tag selection with single keys.
14735 CURRENT is the current list of tags in the headline, INHERITED is the
14736 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14737 possibly with grouping information. TODO-TABLE is a similar table with
14738 TODO keywords, should these have keys assigned to them.
14739 If the keys are nil, a-z are automatically assigned.
14740 Returns the new tags string, or nil to not change the current settings."
14741 (let* ((fulltable (append table todo-table))
14742 (maxlen (apply 'max (mapcar
14743 (lambda (x)
14744 (if (stringp (car x)) (string-width (car x)) 0))
14745 fulltable)))
14746 (buf (current-buffer))
14747 (expert (eq org-fast-tag-selection-single-key 'expert))
14748 (buffer-tags nil)
14749 (fwidth (+ maxlen 3 1 3))
14750 (ncol (/ (- (window-width) 4) fwidth))
14751 (i-face 'org-done)
14752 (c-face 'org-todo)
14753 tg cnt e c char c1 c2 ntable tbl rtn
14754 ov-start ov-end ov-prefix
14755 (exit-after-next org-fast-tag-selection-single-key)
14756 (done-keywords org-done-keywords)
14757 groups ingroup intaggroup)
14758 (save-excursion
14759 (beginning-of-line 1)
14760 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14761 (setq ov-start (match-beginning 1)
14762 ov-end (match-end 1)
14763 ov-prefix "")
14764 (setq ov-start (1- (point-at-eol))
14765 ov-end (1+ ov-start))
14766 (skip-chars-forward "^\n\r")
14767 (setq ov-prefix
14768 (concat
14769 (buffer-substring (1- (point)) (point))
14770 (if (> (current-column) org-tags-column)
14772 (make-string (- org-tags-column (current-column)) ?\ ))))))
14773 (move-overlay org-tags-overlay ov-start ov-end)
14774 (save-window-excursion
14775 (if expert
14776 (set-buffer (get-buffer-create " *Org tags*"))
14777 (delete-other-windows)
14778 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14779 (org-switch-to-buffer-other-window " *Org tags*"))
14780 (erase-buffer)
14781 (setq-local org-done-keywords done-keywords)
14782 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14783 (org-fast-tag-insert "Current" current c-face "\n\n")
14784 (org-fast-tag-show-exit exit-after-next)
14785 (org-set-current-tags-overlay current ov-prefix)
14786 (setq tbl fulltable char ?a cnt 0)
14787 (while (setq e (pop tbl))
14788 (cond
14789 ((eq (car e) :startgroup)
14790 (push '() groups) (setq ingroup t)
14791 (unless (zerop cnt)
14792 (setq cnt 0)
14793 (insert "\n"))
14794 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14795 ((eq (car e) :endgroup)
14796 (setq ingroup nil cnt 0)
14797 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14798 ((eq (car e) :startgrouptag)
14799 (setq intaggroup t)
14800 (unless (zerop cnt)
14801 (setq cnt 0)
14802 (insert "\n"))
14803 (insert "[ "))
14804 ((eq (car e) :endgrouptag)
14805 (setq intaggroup nil cnt 0)
14806 (insert "]\n"))
14807 ((equal e '(:newline))
14808 (unless (zerop cnt)
14809 (setq cnt 0)
14810 (insert "\n")
14811 (setq e (car tbl))
14812 (while (equal (car tbl) '(:newline))
14813 (insert "\n")
14814 (setq tbl (cdr tbl)))))
14815 ((equal e '(:grouptags)) (insert " : "))
14817 (setq tg (copy-sequence (car e)) c2 nil)
14818 (if (cdr e)
14819 (setq c (cdr e))
14820 ;; automatically assign a character.
14821 (setq c1 (string-to-char
14822 (downcase (substring
14823 tg (if (= (string-to-char tg) ?@) 1 0)))))
14824 (if (or (rassoc c1 ntable) (rassoc c1 table))
14825 (while (or (rassoc char ntable) (rassoc char table))
14826 (setq char (1+ char)))
14827 (setq c2 c1))
14828 (setq c (or c2 char)))
14829 (when ingroup (push tg (car groups)))
14830 (setq tg (org-add-props tg nil 'face
14831 (cond
14832 ((not (assoc tg table))
14833 (org-get-todo-face tg))
14834 ((member tg current) c-face)
14835 ((member tg inherited) i-face))))
14836 (when (equal (caar tbl) :grouptags)
14837 (org-add-props tg nil 'face 'org-tag-group))
14838 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14839 (insert "[" c "] " tg (make-string
14840 (- fwidth 4 (length tg)) ?\ ))
14841 (push (cons tg c) ntable)
14842 (when (= (cl-incf cnt) ncol)
14843 (insert "\n")
14844 (when (or ingroup intaggroup) (insert " "))
14845 (setq cnt 0)))))
14846 (setq ntable (nreverse ntable))
14847 (insert "\n")
14848 (goto-char (point-min))
14849 (unless expert (org-fit-window-to-buffer))
14850 (setq rtn
14851 (catch 'exit
14852 (while t
14853 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14854 (if (not groups) "no " "")
14855 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14856 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14857 (setq org-last-tag-selection-key c)
14858 (cond
14859 ((= c ?\r) (throw 'exit t))
14860 ((= c ?!)
14861 (setq groups (not groups))
14862 (goto-char (point-min))
14863 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14864 ((= c ?\C-c)
14865 (if (not expert)
14866 (org-fast-tag-show-exit
14867 (setq exit-after-next (not exit-after-next)))
14868 (setq expert nil)
14869 (delete-other-windows)
14870 (set-window-buffer (split-window-vertically) " *Org tags*")
14871 (org-switch-to-buffer-other-window " *Org tags*")
14872 (org-fit-window-to-buffer)))
14873 ((or (= c ?\C-g)
14874 (and (= c ?q) (not (rassoc c ntable))))
14875 (delete-overlay org-tags-overlay)
14876 (setq quit-flag t))
14877 ((= c ?\ )
14878 (setq current nil)
14879 (when exit-after-next (setq exit-after-next 'now)))
14880 ((= c ?\t)
14881 (condition-case nil
14882 (setq tg (completing-read
14883 "Tag: "
14884 (or buffer-tags
14885 (with-current-buffer buf
14886 (setq buffer-tags
14887 (org-get-buffer-tags))))))
14888 (quit (setq tg "")))
14889 (when (string-match "\\S-" tg)
14890 (cl-pushnew (list tg) buffer-tags :test #'equal)
14891 (if (member tg current)
14892 (setq current (delete tg current))
14893 (push tg current)))
14894 (when exit-after-next (setq exit-after-next 'now)))
14895 ((setq e (rassoc c todo-table) tg (car e))
14896 (with-current-buffer buf
14897 (save-excursion (org-todo tg)))
14898 (when exit-after-next (setq exit-after-next 'now)))
14899 ((setq e (rassoc c ntable) tg (car e))
14900 (if (member tg current)
14901 (setq current (delete tg current))
14902 (cl-loop for g in groups do
14903 (when (member tg g)
14904 (dolist (x g) (setq current (delete x current)))))
14905 (push tg current))
14906 (when exit-after-next (setq exit-after-next 'now))))
14908 ;; Create a sorted list
14909 (setq current
14910 (sort current
14911 (lambda (a b)
14912 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14913 (when (eq exit-after-next 'now) (throw 'exit t))
14914 (goto-char (point-min))
14915 (beginning-of-line 2)
14916 (delete-region (point) (point-at-eol))
14917 (org-fast-tag-insert "Current" current c-face)
14918 (org-set-current-tags-overlay current ov-prefix)
14919 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14920 (setq tg (match-string 1))
14921 (add-text-properties
14922 (match-beginning 1) (match-end 1)
14923 (list 'face
14924 (cond
14925 ((member tg current) c-face)
14926 ((member tg inherited) i-face)
14927 (t (get-text-property (match-beginning 1) 'face))))))
14928 (goto-char (point-min)))))
14929 (delete-overlay org-tags-overlay)
14930 (if rtn
14931 (mapconcat 'identity current ":")
14932 nil))))
14934 (defun org-get-tags-string ()
14935 "Get the TAGS string in the current headline."
14936 (unless (org-at-heading-p t)
14937 (user-error "Not on a heading"))
14938 (save-excursion
14939 (beginning-of-line 1)
14940 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14941 (match-string-no-properties 1)
14942 "")))
14944 (defun org-get-tags ()
14945 "Get the list of tags specified in the current headline."
14946 (org-split-string (org-get-tags-string) ":"))
14948 (defun org-get-buffer-tags ()
14949 "Get a table of all tags used in the buffer, for completion."
14950 (org-with-wide-buffer
14951 (goto-char (point-min))
14952 (let ((tag-re (concat org-outline-regexp-bol
14953 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14954 tags)
14955 (while (re-search-forward tag-re nil t)
14956 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14957 (push tag tags)))
14958 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14960 ;;;; The mapping API
14962 (defvar org-agenda-skip-comment-trees)
14963 (defvar org-agenda-skip-function)
14964 (defun org-map-entries (func &optional match scope &rest skip)
14965 "Call FUNC at each headline selected by MATCH in SCOPE.
14967 FUNC is a function or a lisp form. The function will be called without
14968 arguments, with the cursor positioned at the beginning of the headline.
14969 The return values of all calls to the function will be collected and
14970 returned as a list.
14972 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14973 does not need to preserve point. After evaluation, the cursor will be
14974 moved to the end of the line (presumably of the headline of the
14975 processed entry) and search continues from there. Under some
14976 circumstances, this may not produce the wanted results. For example,
14977 if you have removed (e.g. archived) the current (sub)tree it could
14978 mean that the next entry will be skipped entirely. In such cases, you
14979 can specify the position from where search should continue by making
14980 FUNC set the variable `org-map-continue-from' to the desired buffer
14981 position.
14983 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14984 Only headlines that are matched by this query will be considered during
14985 the iteration. When MATCH is nil or t, all headlines will be
14986 visited by the iteration.
14988 SCOPE determines the scope of this command. It can be any of:
14990 nil The current buffer, respecting the restriction if any
14991 tree The subtree started with the entry at point
14992 region The entries within the active region, if any
14993 region-start-level
14994 The entries within the active region, but only those at
14995 the same level than the first one.
14996 file The current buffer, without restriction
14997 file-with-archives
14998 The current buffer, and any archives associated with it
14999 agenda All agenda files
15000 agenda-with-archives
15001 All agenda files with any archive files associated with them
15002 \(file1 file2 ...)
15003 If this is a list, all files in the list will be scanned
15005 The remaining args are treated as settings for the skipping facilities of
15006 the scanner. The following items can be given here:
15008 archive skip trees with the archive tag
15009 comment skip trees with the COMMENT keyword
15010 function or Emacs Lisp form:
15011 will be used as value for `org-agenda-skip-function', so
15012 whenever the function returns a position, FUNC will not be
15013 called for that entry and search will continue from the
15014 position returned
15016 If your function needs to retrieve the tags including inherited tags
15017 at the *current* entry, you can use the value of the variable
15018 `org-scanner-tags' which will be much faster than getting the value
15019 with `org-get-tags-at'. If your function gets properties with
15020 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15021 to t around the call to `org-entry-properties' to get the same speedup.
15022 Note that if your function moves around to retrieve tags and properties at
15023 a *different* entry, you cannot use these techniques."
15024 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15025 (not (org-region-active-p)))
15026 (let* ((org-agenda-archives-mode nil) ; just to make sure
15027 (org-agenda-skip-archived-trees (memq 'archive skip))
15028 (org-agenda-skip-comment-trees (memq 'comment skip))
15029 (org-agenda-skip-function
15030 (car (org-delete-all '(comment archive) skip)))
15031 (org-tags-match-list-sublevels t)
15032 (start-level (eq scope 'region-start-level))
15033 matcher res
15034 org-todo-keywords-for-agenda
15035 org-done-keywords-for-agenda
15036 org-todo-keyword-alist-for-agenda
15037 org-tag-alist-for-agenda
15038 org--matcher-tags-todo-only)
15040 (cond
15041 ((eq match t) (setq matcher t))
15042 ((eq match nil) (setq matcher t))
15043 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15045 (save-excursion
15046 (save-restriction
15047 (cond ((eq scope 'tree)
15048 (org-back-to-heading t)
15049 (org-narrow-to-subtree)
15050 (setq scope nil))
15051 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15052 (org-region-active-p))
15053 ;; If needed, set start-level to a string like "2"
15054 (when start-level
15055 (save-excursion
15056 (goto-char (region-beginning))
15057 (unless (org-at-heading-p) (outline-next-heading))
15058 (setq start-level (org-current-level))))
15059 (narrow-to-region (region-beginning)
15060 (save-excursion
15061 (goto-char (region-end))
15062 (unless (and (bolp) (org-at-heading-p))
15063 (outline-next-heading))
15064 (point)))
15065 (setq scope nil)))
15067 (if (not scope)
15068 (progn
15069 (org-agenda-prepare-buffers
15070 (and buffer-file-name (list buffer-file-name)))
15071 (setq res
15072 (org-scan-tags
15073 func matcher org--matcher-tags-todo-only start-level)))
15074 ;; Get the right scope
15075 (cond
15076 ((and scope (listp scope) (symbolp (car scope)))
15077 (setq scope (eval scope)))
15078 ((eq scope 'agenda)
15079 (setq scope (org-agenda-files t)))
15080 ((eq scope 'agenda-with-archives)
15081 (setq scope (org-agenda-files t))
15082 (setq scope (org-add-archive-files scope)))
15083 ((eq scope 'file)
15084 (setq scope (and buffer-file-name (list buffer-file-name))))
15085 ((eq scope 'file-with-archives)
15086 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15087 (org-agenda-prepare-buffers scope)
15088 (dolist (file scope)
15089 (with-current-buffer (org-find-base-buffer-visiting file)
15090 (org-with-wide-buffer
15091 (goto-char (point-min))
15092 (setq res
15093 (append
15095 (org-scan-tags
15096 func matcher org--matcher-tags-todo-only)))))))))
15097 res)))
15099 ;;; Properties API
15101 (defconst org-special-properties
15102 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15103 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15104 "The special properties valid in Org mode.
15105 These are properties that are not defined in the property drawer,
15106 but in some other way.")
15108 (defconst org-default-properties
15109 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15110 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15111 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15112 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15113 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15114 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15115 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15116 "Some properties that are used by Org mode for various purposes.
15117 Being in this list makes sure that they are offered for completion.")
15119 (defun org--valid-property-p (property)
15120 "Non nil when string PROPERTY is a valid property name."
15121 (not
15122 (or (equal property "")
15123 (string-match-p "\\s-" property))))
15125 (defun org--update-property-plist (key val props)
15126 "Associate KEY to VAL in alist PROPS.
15127 Modifications are made by side-effect. Return new alist."
15128 (let* ((appending (string= (substring key -1) "+"))
15129 (key (if appending (substring key 0 -1) key))
15130 (old (assoc-string key props t)))
15131 (if (not old) (cons (cons key val) props)
15132 (setcdr old (if appending (concat (cdr old) " " val) val))
15133 props)))
15135 (defun org-get-property-block (&optional beg force)
15136 "Return the (beg . end) range of the body of the property drawer.
15137 BEG is the beginning of the current subtree, or of the part
15138 before the first headline. If it is not given, it will be found.
15139 If the drawer does not exist, create it if FORCE is non-nil, or
15140 return nil."
15141 (org-with-wide-buffer
15142 (when beg (goto-char beg))
15143 (unless (org-before-first-heading-p)
15144 (let ((beg (cond (beg)
15145 ((or (not (featurep 'org-inlinetask))
15146 (org-inlinetask-in-task-p))
15147 (org-back-to-heading t))
15148 (t (org-with-limited-levels (org-back-to-heading t))))))
15149 (forward-line)
15150 (when (looking-at-p org-planning-line-re) (forward-line))
15151 (cond ((looking-at org-property-drawer-re)
15152 (forward-line)
15153 (cons (point) (progn (goto-char (match-end 0))
15154 (line-beginning-position))))
15155 (force
15156 (goto-char beg)
15157 (org-insert-property-drawer)
15158 (let ((pos (save-excursion (search-forward ":END:")
15159 (line-beginning-position))))
15160 (cons pos pos))))))))
15162 (defun org-at-property-p ()
15163 "Non-nil when point is inside a property drawer.
15164 See `org-property-re' for match data, if applicable."
15165 (save-excursion
15166 (beginning-of-line)
15167 (and (looking-at org-property-re)
15168 (let ((property-drawer (save-match-data (org-get-property-block))))
15169 (and property-drawer
15170 (>= (point) (car property-drawer))
15171 (< (point) (cdr property-drawer)))))))
15173 (defun org-property-action ()
15174 "Do an action on properties."
15175 (interactive)
15176 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15177 (let ((c (read-char-exclusive)))
15178 (cl-case c
15179 (?s (call-interactively #'org-set-property))
15180 (?d (call-interactively #'org-delete-property))
15181 (?D (call-interactively #'org-delete-property-globally))
15182 (?c (call-interactively #'org-compute-property-at-point))
15183 (otherwise (user-error "No such property action %c" c)))))
15185 (defun org-inc-effort ()
15186 "Increment the value of the effort property in the current entry."
15187 (interactive)
15188 (org-set-effort nil t))
15190 (defvar org-clock-effort) ; Defined in org-clock.el.
15191 (defvar org-clock-current-task) ; Defined in org-clock.el.
15192 (defun org-set-effort (&optional value increment)
15193 "Set the effort property of the current entry.
15194 With numerical prefix arg, use the nth allowed value, 0 stands for the
15195 10th allowed value.
15197 When INCREMENT is non-nil, set the property to the next allowed value."
15198 (interactive "P")
15199 (when (equal value 0) (setq value 10))
15200 (let* ((completion-ignore-case t)
15201 (prop org-effort-property)
15202 (cur (org-entry-get nil prop))
15203 (allowed (org-property-get-allowed-values nil prop 'table))
15204 (existing (mapcar 'list (org-property-values prop)))
15205 (heading (nth 4 (org-heading-components)))
15207 (val (cond
15208 ((stringp value) value)
15209 ((and allowed (integerp value))
15210 (or (car (nth (1- value) allowed))
15211 (car (org-last allowed))))
15212 ((and allowed increment)
15213 (or (cl-caadr (member (list cur) allowed))
15214 (user-error "Allowed effort values are not set")))
15215 (allowed
15216 (message "Select 1-9,0, [RET%s]: %s"
15217 (if cur (concat "=" cur) "")
15218 (mapconcat 'car allowed " "))
15219 (setq rpl (read-char-exclusive))
15220 (if (equal rpl ?\r)
15222 (setq rpl (- rpl ?0))
15223 (when (equal rpl 0) (setq rpl 10))
15224 (if (and (> rpl 0) (<= rpl (length allowed)))
15225 (car (nth (1- rpl) allowed))
15226 (org-completing-read "Effort: " allowed nil))))
15228 (org-completing-read
15229 (concat "Effort" (and cur (string-match "\\S-" cur)
15230 (concat " [" cur "]"))
15231 ": ")
15232 existing nil nil "" nil cur)))))
15233 (unless (equal (org-entry-get nil prop) val)
15234 (org-entry-put nil prop val))
15235 (org-refresh-property
15236 '((effort . identity)
15237 (effort-minutes . org-duration-to-minutes))
15238 val)
15239 (when (equal heading (bound-and-true-p org-clock-current-task))
15240 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15241 (org-clock-update-mode-line))
15242 (message "%s is now %s" prop val)))
15244 (defun org-entry-properties (&optional pom which)
15245 "Get all properties of the current entry.
15247 When POM is a buffer position, get all properties from the entry
15248 there instead.
15250 This includes the TODO keyword, the tags, time strings for
15251 deadline, scheduled, and clocking, and any additional properties
15252 defined in the entry.
15254 If WHICH is nil or `all', get all properties. If WHICH is
15255 `special' or `standard', only get that subclass. If WHICH is
15256 a string, only get that property.
15258 Return value is an alist. Keys are properties, as upcased
15259 strings."
15260 (org-with-point-at pom
15261 (when (and (derived-mode-p 'org-mode)
15262 (ignore-errors (org-back-to-heading t)))
15263 (catch 'exit
15264 (let* ((beg (point))
15265 (specific (and (stringp which) (upcase which)))
15266 (which (cond ((not specific) which)
15267 ((member specific org-special-properties) 'special)
15268 (t 'standard)))
15269 props)
15270 ;; Get the special properties, like TODO and TAGS.
15271 (when (memq which '(nil all special))
15272 (when (or (not specific) (string= specific "CLOCKSUM"))
15273 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15274 (when clocksum
15275 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15276 props)))
15277 (when specific (throw 'exit props)))
15278 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15279 (let ((clocksumt (get-text-property (point)
15280 :org-clock-minutes-today)))
15281 (when clocksumt
15282 (push (cons "CLOCKSUM_T"
15283 (org-duration-from-minutes clocksumt))
15284 props)))
15285 (when specific (throw 'exit props)))
15286 (when (or (not specific) (string= specific "ITEM"))
15287 (let ((case-fold-search nil))
15288 (when (looking-at org-complex-heading-regexp)
15289 (push (cons "ITEM"
15290 (let ((title (match-string-no-properties 4)))
15291 (if (org-string-nw-p title)
15292 (org-remove-tabs title)
15293 "")))
15294 props)))
15295 (when specific (throw 'exit props)))
15296 (when (or (not specific) (string= specific "TODO"))
15297 (let ((case-fold-search nil))
15298 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15299 (push (cons "TODO" (match-string-no-properties 2)) props)))
15300 (when specific (throw 'exit props)))
15301 (when (or (not specific) (string= specific "PRIORITY"))
15302 (push (cons "PRIORITY"
15303 (if (looking-at org-priority-regexp)
15304 (match-string-no-properties 2)
15305 (char-to-string org-default-priority)))
15306 props)
15307 (when specific (throw 'exit props)))
15308 (when (or (not specific) (string= specific "FILE"))
15309 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15310 props)
15311 (when specific (throw 'exit props)))
15312 (when (or (not specific) (string= specific "TAGS"))
15313 (let ((value (org-string-nw-p (org-get-tags-string))))
15314 (when value (push (cons "TAGS" value) props)))
15315 (when specific (throw 'exit props)))
15316 (when (or (not specific) (string= specific "ALLTAGS"))
15317 (let ((value (org-get-tags-at)))
15318 (when value
15319 (push (cons "ALLTAGS"
15320 (format ":%s:" (mapconcat #'identity value ":")))
15321 props)))
15322 (when specific (throw 'exit props)))
15323 (when (or (not specific) (string= specific "BLOCKED"))
15324 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15325 (when specific (throw 'exit props)))
15326 (when (or (not specific)
15327 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15328 (forward-line)
15329 (when (looking-at-p org-planning-line-re)
15330 (end-of-line)
15331 (let ((bol (line-beginning-position))
15332 ;; Backward compatibility: time keywords used to
15333 ;; be configurable (before 8.3). Make sure we
15334 ;; get the correct keyword.
15335 (key-assoc `(("CLOSED" . ,org-closed-string)
15336 ("DEADLINE" . ,org-deadline-string)
15337 ("SCHEDULED" . ,org-scheduled-string))))
15338 (dolist (pair (if specific (list (assoc specific key-assoc))
15339 key-assoc))
15340 (save-excursion
15341 (when (search-backward (cdr pair) bol t)
15342 (goto-char (match-end 0))
15343 (skip-chars-forward " \t")
15344 (and (looking-at org-ts-regexp-both)
15345 (push (cons (car pair)
15346 (match-string-no-properties 0))
15347 props)))))))
15348 (when specific (throw 'exit props)))
15349 (when (or (not specific)
15350 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15351 (let ((find-ts
15352 (lambda (end ts)
15353 ;; Fix next time-stamp before END. TS is the
15354 ;; list of time-stamps found so far.
15355 (let ((ts ts)
15356 (regexp (cond
15357 ((string= specific "TIMESTAMP")
15358 org-ts-regexp)
15359 ((string= specific "TIMESTAMP_IA")
15360 org-ts-regexp-inactive)
15361 ((assoc "TIMESTAMP_IA" ts)
15362 org-ts-regexp)
15363 ((assoc "TIMESTAMP" ts)
15364 org-ts-regexp-inactive)
15365 (t org-ts-regexp-both))))
15366 (catch 'next
15367 (while (re-search-forward regexp end t)
15368 (backward-char)
15369 (let ((object (org-element-context)))
15370 ;; Accept to match timestamps in node
15371 ;; properties, too.
15372 (when (memq (org-element-type object)
15373 '(node-property timestamp))
15374 (let ((type
15375 (org-element-property :type object)))
15376 (cond
15377 ((and (memq type '(active active-range))
15378 (not (equal specific "TIMESTAMP_IA")))
15379 (unless (assoc "TIMESTAMP" ts)
15380 (push (cons "TIMESTAMP"
15381 (org-element-property
15382 :raw-value object))
15384 (when specific (throw 'exit ts))))
15385 ((and (memq type '(inactive inactive-range))
15386 (not (string= specific "TIMESTAMP")))
15387 (unless (assoc "TIMESTAMP_IA" ts)
15388 (push (cons "TIMESTAMP_IA"
15389 (org-element-property
15390 :raw-value object))
15392 (when specific (throw 'exit ts))))))
15393 ;; Both timestamp types are found,
15394 ;; move to next part.
15395 (when (= (length ts) 2) (throw 'next ts)))))
15396 ts)))))
15397 (goto-char beg)
15398 ;; First look for timestamps within headline.
15399 (let ((ts (funcall find-ts (line-end-position) nil)))
15400 (if (= (length ts) 2) (setq props (nconc ts props))
15401 ;; Then find timestamps in the section, skipping
15402 ;; planning line.
15403 (let ((end (save-excursion (outline-next-heading))))
15404 (forward-line)
15405 (when (looking-at-p org-planning-line-re) (forward-line))
15406 (setq props (nconc (funcall find-ts end ts) props))))))))
15407 ;; Get the standard properties, like :PROP:.
15408 (when (memq which '(nil all standard))
15409 ;; If we are looking after a specific property, delegate
15410 ;; to `org-entry-get', which is faster. However, make an
15411 ;; exception for "CATEGORY", since it can be also set
15412 ;; through keywords (i.e. #+CATEGORY).
15413 (if (and specific (not (equal specific "CATEGORY")))
15414 (let ((value (org-entry-get beg specific nil t)))
15415 (throw 'exit (and value (list (cons specific value)))))
15416 (let ((range (org-get-property-block beg)))
15417 (when range
15418 (let ((end (cdr range)) seen-base)
15419 (goto-char (car range))
15420 ;; Unlike to `org--update-property-plist', we
15421 ;; handle the case where base values is found
15422 ;; after its extension. We also forbid standard
15423 ;; properties to be named as special properties.
15424 (while (re-search-forward org-property-re end t)
15425 (let* ((key (upcase (match-string-no-properties 2)))
15426 (extendp (string-match-p "\\+\\'" key))
15427 (key-base (if extendp (substring key 0 -1) key))
15428 (value (match-string-no-properties 3)))
15429 (cond
15430 ((member-ignore-case key-base org-special-properties))
15431 (extendp
15432 (setq props
15433 (org--update-property-plist key value props)))
15434 ((member key seen-base))
15435 (t (push key seen-base)
15436 (let ((p (assoc-string key props t)))
15437 (if p (setcdr p (concat value " " (cdr p)))
15438 (push (cons key value) props))))))))))))
15439 (unless (assoc "CATEGORY" props)
15440 (push (cons "CATEGORY" (org-get-category beg)) props)
15441 (when (string= specific "CATEGORY") (throw 'exit props)))
15442 ;; Return value.
15443 props)))))
15445 (defun org--property-local-values (property literal-nil)
15446 "Return value for PROPERTY in current entry.
15447 Value is a list whose car is the base value for PROPERTY and cdr
15448 a list of accumulated values. Return nil if neither is found in
15449 the entry. Also return nil when PROPERTY is set to \"nil\",
15450 unless LITERAL-NIL is non-nil."
15451 (let ((range (org-get-property-block)))
15452 (when range
15453 (goto-char (car range))
15454 (let* ((case-fold-search t)
15455 (end (cdr range))
15456 (value
15457 ;; Base value.
15458 (save-excursion
15459 (let ((v (and (re-search-forward
15460 (org-re-property property nil t) end t)
15461 (match-string-no-properties 3))))
15462 (list (if literal-nil v (org-not-nil v)))))))
15463 ;; Find additional values.
15464 (let* ((property+ (org-re-property (concat property "+") nil t)))
15465 (while (re-search-forward property+ end t)
15466 (push (match-string-no-properties 3) value)))
15467 ;; Return final values.
15468 (and (not (equal value '(nil))) (nreverse value))))))
15470 (defun org--property-global-value (property literal-nil)
15471 "Return value for PROPERTY in current buffer.
15472 Return value is a string. Return nil if property is not set
15473 globally. Also return nil when PROPERTY is set to \"nil\",
15474 unless LITERAL-NIL is non-nil."
15475 (let ((global
15476 (cdr (or (assoc-string property org-file-properties t)
15477 (assoc-string property org-global-properties t)
15478 (assoc-string property org-global-properties-fixed t)))))
15479 (if literal-nil global (org-not-nil global))))
15481 (defun org-entry-get (pom property &optional inherit literal-nil)
15482 "Get value of PROPERTY for entry or content at point-or-marker POM.
15484 If INHERIT is non-nil and the entry does not have the property,
15485 then also check higher levels of the hierarchy. If INHERIT is
15486 the symbol `selective', use inheritance only if the setting in
15487 `org-use-property-inheritance' selects PROPERTY for inheritance.
15489 If the property is present but empty, the return value is the
15490 empty string. If the property is not present at all, nil is
15491 returned. In any other case, return the value as a string.
15492 Search is case-insensitive.
15494 If LITERAL-NIL is set, return the string value \"nil\" as
15495 a string, do not interpret it as the list atom nil. This is used
15496 for inheritance when a \"nil\" value can supersede a non-nil
15497 value higher up the hierarchy."
15498 (org-with-point-at pom
15499 (cond
15500 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15501 ;; We need a special property. Use `org-entry-properties' to
15502 ;; retrieve it, but specify the wanted property.
15503 (cdr (assoc-string property (org-entry-properties nil property))))
15504 ((and inherit
15505 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15506 (org-entry-get-with-inheritance property literal-nil))
15508 (let* ((local (org--property-local-values property literal-nil))
15509 (value (and local (mapconcat #'identity (delq nil local) " "))))
15510 (if literal-nil value (org-not-nil value)))))))
15512 (defun org-property-or-variable-value (var &optional inherit)
15513 "Check if there is a property fixing the value of VAR.
15514 If yes, return this value. If not, return the current value of the variable."
15515 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15516 (if (and prop (stringp prop) (string-match "\\S-" prop))
15517 (read prop)
15518 (symbol-value var))))
15520 (defun org-entry-delete (pom property)
15521 "Delete PROPERTY from entry at point-or-marker POM.
15522 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15523 non-nil when a property was removed."
15524 (org-with-point-at pom
15525 (pcase (org-get-property-block)
15526 (`(,begin . ,origin)
15527 (let* ((end (copy-marker origin))
15528 (re (org-re-property
15529 (concat (regexp-quote property) "\\+?") t t)))
15530 (goto-char begin)
15531 (while (re-search-forward re end t)
15532 (delete-region (match-beginning 0) (line-beginning-position 2)))
15533 ;; If drawer is empty, remove it altogether.
15534 (when (= begin end)
15535 (delete-region (line-beginning-position 0)
15536 (line-beginning-position 2)))
15537 ;; Return non-nil if some property was removed.
15538 (prog1 (/= end origin) (set-marker end nil))))
15539 (_ nil))))
15541 ;; Multi-values properties are properties that contain multiple values
15542 ;; These values are assumed to be single words, separated by whitespace.
15543 (defun org-entry-add-to-multivalued-property (pom property value)
15544 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15545 (let* ((old (org-entry-get pom property))
15546 (values (and old (split-string old))))
15547 (setq value (org-entry-protect-space value))
15548 (unless (member value values)
15549 (setq values (append values (list value)))
15550 (org-entry-put pom property (mapconcat #'identity values " ")))))
15552 (defun org-entry-remove-from-multivalued-property (pom property value)
15553 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15554 (let* ((old (org-entry-get pom property))
15555 (values (and old (split-string old))))
15556 (setq value (org-entry-protect-space value))
15557 (when (member value values)
15558 (setq values (delete value values))
15559 (org-entry-put pom property (mapconcat #'identity values " ")))))
15561 (defun org-entry-member-in-multivalued-property (pom property value)
15562 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15563 (let* ((old (org-entry-get pom property))
15564 (values (and old (split-string old))))
15565 (setq value (org-entry-protect-space value))
15566 (member value values)))
15568 (defun org-entry-get-multivalued-property (pom property)
15569 "Return a list of values in a multivalued property."
15570 (let* ((value (org-entry-get pom property))
15571 (values (and value (split-string value))))
15572 (mapcar #'org-entry-restore-space values)))
15574 (defun org-entry-put-multivalued-property (pom property &rest values)
15575 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15576 VALUES should be a list of strings. Spaces will be protected."
15577 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15578 (let* ((value (org-entry-get pom property))
15579 (values (and value (split-string value))))
15580 (mapcar #'org-entry-restore-space values)))
15582 (defun org-entry-protect-space (s)
15583 "Protect spaces and newline in string S."
15584 (while (string-match " " s)
15585 (setq s (replace-match "%20" t t s)))
15586 (while (string-match "\n" s)
15587 (setq s (replace-match "%0A" t t s)))
15590 (defun org-entry-restore-space (s)
15591 "Restore spaces and newline in string S."
15592 (while (string-match "%20" s)
15593 (setq s (replace-match " " t t s)))
15594 (while (string-match "%0A" s)
15595 (setq s (replace-match "\n" t t s)))
15598 (defvar org-entry-property-inherited-from (make-marker)
15599 "Marker pointing to the entry from where a property was inherited.
15600 Each call to `org-entry-get-with-inheritance' will set this marker to the
15601 location of the entry where the inheritance search matched. If there was
15602 no match, the marker will point nowhere.
15603 Note that also `org-entry-get' calls this function, if the INHERIT flag
15604 is set.")
15606 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15607 "Get PROPERTY of entry or content at point, search higher levels if needed.
15608 The search will stop at the first ancestor which has the property defined.
15609 If the value found is \"nil\", return nil to show that the property
15610 should be considered as undefined (this is the meaning of nil here).
15611 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15612 (move-marker org-entry-property-inherited-from nil)
15613 (org-with-wide-buffer
15614 (let (value)
15615 (catch 'exit
15616 (while t
15617 (let ((v (org--property-local-values property literal-nil)))
15618 (when v
15619 (setq value
15620 (concat (mapconcat #'identity (delq nil v) " ")
15621 (and value " ")
15622 value)))
15623 (cond
15624 ((car v)
15625 (org-back-to-heading t)
15626 (move-marker org-entry-property-inherited-from (point))
15627 (throw 'exit nil))
15628 ((org-up-heading-safe))
15630 (let ((global (org--property-global-value property literal-nil)))
15631 (cond ((not global))
15632 (value (setq value (concat global " " value)))
15633 (t (setq value global))))
15634 (throw 'exit nil))))))
15635 (if literal-nil value (org-not-nil value)))))
15637 (defvar org-property-changed-functions nil
15638 "Hook called when the value of a property has changed.
15639 Each hook function should accept two arguments, the name of the property
15640 and the new value.")
15642 (defun org-entry-put (pom property value)
15643 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15645 If the value is nil, it is converted to the empty string. If it
15646 is not a string, an error is raised. Also raise an error on
15647 invalid property names.
15649 PROPERTY can be any regular property (see
15650 `org-special-properties'). It can also be \"TODO\",
15651 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15653 For the last two properties, VALUE may have any of the special
15654 values \"earlier\" and \"later\". The function then increases or
15655 decreases scheduled or deadline date by one day."
15656 (cond ((null value) (setq value ""))
15657 ((not (stringp value)) (error "Properties values should be strings"))
15658 ((not (org--valid-property-p property))
15659 (user-error "Invalid property name: \"%s\"" property)))
15660 (org-with-point-at pom
15661 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15662 (org-back-to-heading t)
15663 (org-with-limited-levels (org-back-to-heading t)))
15664 (let ((beg (point)))
15665 (cond
15666 ((equal property "TODO")
15667 (cond ((not (org-string-nw-p value)) (setq value 'none))
15668 ((not (member value org-todo-keywords-1))
15669 (user-error "\"%s\" is not a valid TODO state" value)))
15670 (org-todo value)
15671 (org-set-tags nil 'align))
15672 ((equal property "PRIORITY")
15673 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15674 (org-set-tags nil 'align))
15675 ((equal property "SCHEDULED")
15676 (forward-line)
15677 (if (and (looking-at-p org-planning-line-re)
15678 (re-search-forward
15679 org-scheduled-time-regexp (line-end-position) t))
15680 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15681 ((string= value "later") (org-timestamp-change 1 'day))
15682 ((string= value "") (org-schedule '(4)))
15683 (t (org-schedule nil value)))
15684 (if (member value '("earlier" "later" ""))
15685 (call-interactively #'org-schedule)
15686 (org-schedule nil value))))
15687 ((equal property "DEADLINE")
15688 (forward-line)
15689 (if (and (looking-at-p org-planning-line-re)
15690 (re-search-forward
15691 org-deadline-time-regexp (line-end-position) t))
15692 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15693 ((string= value "later") (org-timestamp-change 1 'day))
15694 ((string= value "") (org-deadline '(4)))
15695 (t (org-deadline nil value)))
15696 (if (member value '("earlier" "later" ""))
15697 (call-interactively #'org-deadline)
15698 (org-deadline nil value))))
15699 ((member property org-special-properties)
15700 (error "The %s property cannot be set with `org-entry-put'" property))
15702 (let* ((range (org-get-property-block beg 'force))
15703 (end (cdr range))
15704 (case-fold-search t))
15705 (goto-char (car range))
15706 (if (re-search-forward (org-re-property property nil t) end t)
15707 (progn (delete-region (match-beginning 0) (match-end 0))
15708 (goto-char (match-beginning 0)))
15709 (goto-char end)
15710 (insert "\n")
15711 (backward-char))
15712 (insert ":" property ":")
15713 (when value (insert " " value))
15714 (org-indent-line)))))
15715 (run-hook-with-args 'org-property-changed-functions property value)))
15717 (defun org-buffer-property-keys (&optional specials defaults columns)
15718 "Get all property keys in the current buffer.
15720 When SPECIALS is non-nil, also list the special properties that
15721 reflect things like tags and TODO state.
15723 When DEFAULTS is non-nil, also include properties that has
15724 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15725 DESCRIPTION, LOCATION, and LOGGING and others.
15727 When COLUMNS in non-nil, also include property names given in
15728 COLUMN formats in the current buffer."
15729 (let ((case-fold-search t)
15730 (props (append
15731 (and specials org-special-properties)
15732 (and defaults (cons org-effort-property org-default-properties))
15733 nil)))
15734 (org-with-wide-buffer
15735 (goto-char (point-min))
15736 (while (re-search-forward org-property-start-re nil t)
15737 (catch :skip
15738 (let ((range (org-get-property-block)))
15739 (unless range (throw :skip nil))
15740 (goto-char (car range))
15741 (let ((begin (car range))
15742 (end (cdr range)))
15743 ;; Make sure that found property block is not located
15744 ;; before current point, as it would generate an infloop.
15745 ;; It can happen, for example, in the following
15746 ;; situation:
15748 ;; * Headline
15749 ;; :PROPERTIES:
15750 ;; ...
15751 ;; :END:
15752 ;; *************** Inlinetask
15753 ;; #+BEGIN_EXAMPLE
15754 ;; :PROPERTIES:
15755 ;; #+END_EXAMPLE
15757 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15758 (while (< (point) end)
15759 (let ((p (progn (looking-at org-property-re)
15760 (match-string-no-properties 2))))
15761 ;; Only add true property name, not extension symbol.
15762 (push (if (not (string-match-p "\\+\\'" p)) p
15763 (substring p 0 -1))
15764 props))
15765 (forward-line))))
15766 (outline-next-heading)))
15767 (when columns
15768 (goto-char (point-min))
15769 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15770 (let ((element (org-element-at-point)))
15771 (when (memq (org-element-type element) '(keyword node-property))
15772 (let ((value (org-element-property :value element))
15773 (start 0))
15774 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15775 \\(?:{[^}]+}\\)?"
15776 value start)
15777 (setq start (match-end 0))
15778 (let ((p (match-string-no-properties 1 value)))
15779 (unless (member-ignore-case p org-special-properties)
15780 (push p props))))))))))
15781 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15783 (defun org-property-values (key)
15784 "List all non-nil values of property KEY in current buffer."
15785 (org-with-wide-buffer
15786 (goto-char (point-min))
15787 (let ((case-fold-search t)
15788 (re (org-re-property key))
15789 values)
15790 (while (re-search-forward re nil t)
15791 (push (org-entry-get (point) key) values))
15792 (delete-dups values))))
15794 (defun org-insert-property-drawer ()
15795 "Insert a property drawer into the current entry."
15796 (org-with-wide-buffer
15797 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15798 (org-back-to-heading t)
15799 (org-with-limited-levels (org-back-to-heading t)))
15800 (forward-line)
15801 (when (looking-at-p org-planning-line-re) (forward-line))
15802 (unless (looking-at-p org-property-drawer-re)
15803 ;; Make sure we start editing a line from current entry, not from
15804 ;; next one. It prevents extending text properties or overlays
15805 ;; belonging to the latter.
15806 (when (bolp) (backward-char))
15807 (let ((begin (1+ (point)))
15808 (inhibit-read-only t))
15809 (insert "\n:PROPERTIES:\n:END:")
15810 (when (eobp) (insert "\n"))
15811 (org-indent-region begin (point))))))
15813 (defun org-insert-drawer (&optional arg drawer)
15814 "Insert a drawer at point.
15816 When optional argument ARG is non-nil, insert a property drawer.
15818 Optional argument DRAWER, when non-nil, is a string representing
15819 drawer's name. Otherwise, the user is prompted for a name.
15821 If a region is active, insert the drawer around that region
15822 instead.
15824 Point is left between drawer's boundaries."
15825 (interactive "P")
15826 (let* ((drawer (if arg "PROPERTIES"
15827 (or drawer (read-from-minibuffer "Drawer: ")))))
15828 (cond
15829 ;; With C-u, fall back on `org-insert-property-drawer'
15830 (arg (org-insert-property-drawer))
15831 ;; Check validity of suggested drawer's name.
15832 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15833 (user-error "Invalid drawer name"))
15834 ;; With an active region, insert a drawer at point.
15835 ((not (org-region-active-p))
15836 (progn
15837 (unless (bolp) (insert "\n"))
15838 (insert (format ":%s:\n\n:END:\n" drawer))
15839 (forward-line -2)))
15840 ;; Otherwise, insert the drawer at point
15842 (let ((rbeg (region-beginning))
15843 (rend (copy-marker (region-end))))
15844 (unwind-protect
15845 (progn
15846 (goto-char rbeg)
15847 (beginning-of-line)
15848 (when (save-excursion
15849 (re-search-forward org-outline-regexp-bol rend t))
15850 (user-error "Drawers cannot contain headlines"))
15851 ;; Position point at the beginning of the first
15852 ;; non-blank line in region. Insert drawer's opening
15853 ;; there, then indent it.
15854 (org-skip-whitespace)
15855 (beginning-of-line)
15856 (insert ":" drawer ":\n")
15857 (forward-line -1)
15858 (indent-for-tab-command)
15859 ;; Move point to the beginning of the first blank line
15860 ;; after the last non-blank line in region. Insert
15861 ;; drawer's closing, then indent it.
15862 (goto-char rend)
15863 (skip-chars-backward " \r\t\n")
15864 (insert "\n:END:")
15865 (deactivate-mark t)
15866 (indent-for-tab-command)
15867 (unless (eolp) (insert "\n")))
15868 ;; Clear marker, whatever the outcome of insertion is.
15869 (set-marker rend nil)))))))
15871 (defvar org-property-set-functions-alist nil
15872 "Property set function alist.
15873 Each entry should have the following format:
15875 (PROPERTY . READ-FUNCTION)
15877 The read function will be called with the same argument as
15878 `org-completing-read'.")
15880 (defun org-set-property-function (property)
15881 "Get the function that should be used to set PROPERTY.
15882 This is computed according to `org-property-set-functions-alist'."
15883 (or (cdr (assoc property org-property-set-functions-alist))
15884 'org-completing-read))
15886 (defun org-read-property-value (property)
15887 "Read PROPERTY value from user."
15888 (let* ((completion-ignore-case t)
15889 (allowed (org-property-get-allowed-values nil property 'table))
15890 (cur (org-entry-get nil property))
15891 (prompt (concat property " value"
15892 (if (and cur (string-match "\\S-" cur))
15893 (concat " [" cur "]") "") ": "))
15894 (set-function (org-set-property-function property))
15895 (val (if allowed
15896 (funcall set-function prompt allowed nil
15897 (not (get-text-property 0 'org-unrestricted
15898 (caar allowed))))
15899 (funcall set-function prompt
15900 (mapcar 'list (org-property-values property))
15901 nil nil "" nil cur))))
15902 (org-trim val)))
15904 (defvar org-last-set-property nil)
15905 (defvar org-last-set-property-value nil)
15906 (defun org-read-property-name ()
15907 "Read a property name."
15908 (let ((completion-ignore-case t)
15909 (default-prop (or (and (org-at-property-p)
15910 (match-string-no-properties 2))
15911 org-last-set-property)))
15912 (org-completing-read
15913 (concat "Property"
15914 (if default-prop (concat " [" default-prop "]") "")
15915 ": ")
15916 (mapcar #'list (org-buffer-property-keys nil t t))
15917 nil nil nil nil default-prop)))
15919 (defun org-set-property-and-value (use-last)
15920 "Allow to set [PROPERTY]: [value] direction from prompt.
15921 When use-default, don't even ask, just use the last
15922 \"[PROPERTY]: [value]\" string from the history."
15923 (interactive "P")
15924 (let* ((completion-ignore-case t)
15925 (pv (or (and use-last org-last-set-property-value)
15926 (org-completing-read
15927 "Enter a \"[Property]: [value]\" pair: "
15928 nil nil nil nil nil
15929 org-last-set-property-value)))
15930 prop val)
15931 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15932 (setq prop (match-string 1 pv)
15933 val (match-string 2 pv))
15934 (org-set-property prop val))))
15936 (defun org-set-property (property value)
15937 "In the current entry, set PROPERTY to VALUE.
15939 When called interactively, this will prompt for a property name, offering
15940 completion on existing and default properties. And then it will prompt
15941 for a value, offering completion either on allowed values (via an inherited
15942 xxx_ALL property) or on existing values in other instances of this property
15943 in the current file.
15945 Throw an error when trying to set a property with an invalid name."
15946 (interactive (list nil nil))
15947 (let ((property (or property (org-read-property-name))))
15948 ;; `org-entry-put' also makes the following check, but this one
15949 ;; avoids polluting `org-last-set-property' and
15950 ;; `org-last-set-property-value' needlessly.
15951 (unless (org--valid-property-p property)
15952 (user-error "Invalid property name: \"%s\"" property))
15953 (let ((value (or value (org-read-property-value property)))
15954 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15955 (setq org-last-set-property property)
15956 (setq org-last-set-property-value (concat property ": " value))
15957 ;; Possibly postprocess the inserted value:
15958 (when fn (setq value (funcall fn value)))
15959 (unless (equal (org-entry-get nil property) value)
15960 (org-entry-put nil property value)))))
15962 (defun org-find-property (property &optional value)
15963 "Find first entry in buffer that sets PROPERTY.
15965 When optional argument VALUE is non-nil, only consider an entry
15966 if it contains PROPERTY set to this value. If PROPERTY should be
15967 explicitly set to nil, use string \"nil\" for VALUE.
15969 Return position where the entry begins, or nil if there is no
15970 such entry. If narrowing is in effect, only search the visible
15971 part of the buffer."
15972 (save-excursion
15973 (goto-char (point-min))
15974 (let ((case-fold-search t)
15975 (re (org-re-property property nil (not value) value)))
15976 (catch 'exit
15977 (while (re-search-forward re nil t)
15978 (when (if value (org-at-property-p)
15979 (org-entry-get (point) property nil t))
15980 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15982 (defun org-delete-property (property)
15983 "In the current entry, delete PROPERTY."
15984 (interactive
15985 (let* ((completion-ignore-case t)
15986 (cat (org-entry-get (point) "CATEGORY"))
15987 (props0 (org-entry-properties nil 'standard))
15988 (props (if cat props0
15989 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15990 (prop (if (< 1 (length props))
15991 (completing-read "Property: " props nil t)
15992 (caar props))))
15993 (list prop)))
15994 (if (not property)
15995 (message "No property to delete in this entry")
15996 (org-entry-delete nil property)
15997 (message "Property \"%s\" deleted" property)))
15999 (defun org-delete-property-globally (property)
16000 "Remove PROPERTY globally, from all entries.
16001 This function ignores narrowing, if any."
16002 (interactive
16003 (let* ((completion-ignore-case t)
16004 (prop (completing-read
16005 "Globally remove property: "
16006 (mapcar #'list (org-buffer-property-keys)))))
16007 (list prop)))
16008 (org-with-wide-buffer
16009 (goto-char (point-min))
16010 (let ((count 0)
16011 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16012 (while (re-search-forward re nil t)
16013 (when (org-entry-delete (point) property) (cl-incf count)))
16014 (message "Property \"%s\" removed from %d entries" property count))))
16016 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16018 (defun org-compute-property-at-point ()
16019 "Compute the property at point.
16020 This looks for an enclosing column format, extracts the operator and
16021 then applies it to the property in the column format's scope."
16022 (interactive)
16023 (unless (org-at-property-p)
16024 (user-error "Not at a property"))
16025 (let ((prop (match-string-no-properties 2)))
16026 (org-columns-get-format-and-top-level)
16027 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16028 (user-error "No operator defined for property %s" prop))
16029 (org-columns-compute prop)))
16031 (defvar org-property-allowed-value-functions nil
16032 "Hook for functions supplying allowed values for a specific property.
16033 The functions must take a single argument, the name of the property, and
16034 return a flat list of allowed values. If \":ETC\" is one of
16035 the values, this means that these values are intended as defaults for
16036 completion, but that other values should be allowed too.
16037 The functions must return nil if they are not responsible for this
16038 property.")
16040 (defun org-property-get-allowed-values (pom property &optional table)
16041 "Get allowed values for the property PROPERTY.
16042 When TABLE is non-nil, return an alist that can directly be used for
16043 completion."
16044 (let (vals)
16045 (cond
16046 ((equal property "TODO")
16047 (setq vals (org-with-point-at pom
16048 (append org-todo-keywords-1 '("")))))
16049 ((equal property "PRIORITY")
16050 (let ((n org-lowest-priority))
16051 (while (>= n org-highest-priority)
16052 (push (char-to-string n) vals)
16053 (setq n (1- n)))))
16054 ((equal property "CATEGORY"))
16055 ((member property org-special-properties))
16056 ((setq vals (run-hook-with-args-until-success
16057 'org-property-allowed-value-functions property)))
16059 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16060 (when (and vals (string-match "\\S-" vals))
16061 (setq vals (car (read-from-string (concat "(" vals ")"))))
16062 (setq vals (mapcar (lambda (x)
16063 (cond ((stringp x) x)
16064 ((numberp x) (number-to-string x))
16065 ((symbolp x) (symbol-name x))
16066 (t "???")))
16067 vals)))))
16068 (when (member ":ETC" vals)
16069 (setq vals (remove ":ETC" vals))
16070 (org-add-props (car vals) '(org-unrestricted t)))
16071 (if table (mapcar 'list vals) vals)))
16073 (defun org-property-previous-allowed-value (&optional _previous)
16074 "Switch to the next allowed value for this property."
16075 (interactive)
16076 (org-property-next-allowed-value t))
16078 (defun org-property-next-allowed-value (&optional previous)
16079 "Switch to the next allowed value for this property."
16080 (interactive)
16081 (unless (org-at-property-p)
16082 (user-error "Not at a property"))
16083 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16084 (key (match-string 2))
16085 (value (match-string 3))
16086 (allowed (or (org-property-get-allowed-values (point) key)
16087 (and (member value '("[ ]" "[-]" "[X]"))
16088 '("[ ]" "[X]"))))
16089 (heading (save-match-data (nth 4 (org-heading-components))))
16090 nval)
16091 (unless allowed
16092 (user-error "Allowed values for this property have not been defined"))
16093 (when previous (setq allowed (reverse allowed)))
16094 (when (member value allowed)
16095 (setq nval (car (cdr (member value allowed)))))
16096 (setq nval (or nval (car allowed)))
16097 (when (equal nval value)
16098 (user-error "Only one allowed value for this property"))
16099 (org-at-property-p)
16100 (replace-match (concat " :" key ": " nval) t t)
16101 (org-indent-line)
16102 (beginning-of-line 1)
16103 (skip-chars-forward " \t")
16104 (when (equal prop org-effort-property)
16105 (org-refresh-property
16106 '((effort . identity)
16107 (effort-minutes . org-duration-to-minutes))
16108 nval)
16109 (when (string= org-clock-current-task heading)
16110 (setq org-clock-effort nval)
16111 (org-clock-update-mode-line)))
16112 (run-hook-with-args 'org-property-changed-functions key nval)))
16114 (defun org-find-olp (path &optional this-buffer)
16115 "Return a marker pointing to the entry at outline path OLP.
16116 If anything goes wrong, throw an error.
16117 You can wrap this call to catch the error like this:
16119 (condition-case msg
16120 (org-mobile-locate-entry (match-string 4))
16121 (error (nth 1 msg)))
16123 The return value will then be either a string with the error message,
16124 or a marker if everything is OK.
16126 If THIS-BUFFER is set, the outline path does not contain a file,
16127 only headings."
16128 (let* ((file (if this-buffer buffer-file-name (pop path)))
16129 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16130 (level 1)
16131 (lmin 1)
16132 (lmax 1)
16133 end found flevel)
16134 (unless buffer (error "File not found :%s" file))
16135 (with-current-buffer buffer
16136 (unless (derived-mode-p 'org-mode)
16137 (error "Buffer %s needs to be in Org mode" buffer))
16138 (org-with-wide-buffer
16139 (goto-char (point-min))
16140 (dolist (heading path)
16141 (let ((re (format org-complex-heading-regexp-format
16142 (regexp-quote heading)))
16143 (cnt 0))
16144 (while (re-search-forward re end t)
16145 (setq level (- (match-end 1) (match-beginning 1)))
16146 (when (and (>= level lmin) (<= level lmax))
16147 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16148 (when (= cnt 0)
16149 (error "Heading not found on level %d: %s" lmax heading))
16150 (when (> cnt 1)
16151 (error "Heading not unique on level %d: %s" lmax heading))
16152 (goto-char found)
16153 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16154 (setq end (save-excursion (org-end-of-subtree t t)))))
16155 (when (org-at-heading-p)
16156 (point-marker))))))
16158 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16159 "Find node HEADING in BUFFER.
16160 Return a marker to the heading if it was found, or nil if not.
16161 If POS-ONLY is set, return just the position instead of a marker.
16163 The heading text must match exact, but it may have a TODO keyword,
16164 a priority cookie and tags in the standard locations."
16165 (with-current-buffer (or buffer (current-buffer))
16166 (org-with-wide-buffer
16167 (goto-char (point-min))
16168 (let (case-fold-search)
16169 (when (re-search-forward
16170 (format org-complex-heading-regexp-format
16171 (regexp-quote heading)) nil t)
16172 (if pos-only
16173 (match-beginning 0)
16174 (move-marker (make-marker) (match-beginning 0))))))))
16176 (defun org-find-exact-heading-in-directory (heading &optional dir)
16177 "Find Org node headline HEADING in all .org files in directory DIR.
16178 When the target headline is found, return a marker to this location."
16179 (let ((files (directory-files (or dir default-directory)
16180 t "\\`[^.#].*\\.org\\'"))
16181 visiting m buffer)
16182 (catch 'found
16183 (dolist (file files)
16184 (message "trying %s" file)
16185 (setq visiting (org-find-base-buffer-visiting file))
16186 (setq buffer (or visiting (find-file-noselect file)))
16187 (setq m (org-find-exact-headline-in-buffer
16188 heading buffer))
16189 (when (and (not m) (not visiting)) (kill-buffer buffer))
16190 (and m (throw 'found m))))))
16192 (defun org-find-entry-with-id (ident)
16193 "Locate the entry that contains the ID property with exact value IDENT.
16194 IDENT can be a string, a symbol or a number, this function will search for
16195 the string representation of it.
16196 Return the position where this entry starts, or nil if there is no such entry."
16197 (interactive "sID: ")
16198 (let ((id (cond
16199 ((stringp ident) ident)
16200 ((symbolp ident) (symbol-name ident))
16201 ((numberp ident) (number-to-string ident))
16202 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16203 (org-with-wide-buffer (org-find-property "ID" id))))
16205 ;;;; Timestamps
16207 (defvar org-last-changed-timestamp nil)
16208 (defvar org-last-inserted-timestamp nil
16209 "The last time stamp inserted with `org-insert-time-stamp'.")
16211 (defun org-time-stamp (arg &optional inactive)
16212 "Prompt for a date/time and insert a time stamp.
16214 If the user specifies a time like HH:MM or if this command is
16215 called with at least one prefix argument, the time stamp contains
16216 the date and the time. Otherwise, only the date is included.
16218 All parts of a date not specified by the user are filled in from
16219 the timestamp at point, if any, or the current date/time
16220 otherwise.
16222 If there is already a timestamp at the cursor, it is replaced.
16224 With two universal prefix arguments, insert an active timestamp
16225 with the current time without prompting the user.
16227 When called from lisp, the timestamp is inactive if INACTIVE is
16228 non-nil."
16229 (interactive "P")
16230 (let* ((ts (cond
16231 ((org-at-date-range-p t)
16232 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16233 ((org-at-timestamp-p 'lax) (match-string 0))))
16234 ;; Default time is either the timestamp at point or today.
16235 ;; When entering a range, only the range start is considered.
16236 (default-time (if (not ts) (current-time)
16237 (apply #'encode-time (org-parse-time-string ts))))
16238 (default-input (and ts (org-get-compact-tod ts)))
16239 (repeater (and ts
16240 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16241 (match-string 0 ts)))
16242 org-time-was-given
16243 org-end-time-was-given
16244 (time
16245 (and (if (equal arg '(16)) (current-time)
16246 ;; Preserve `this-command' and `last-command'.
16247 (let ((this-command this-command)
16248 (last-command last-command))
16249 (org-read-date
16250 arg 'totime nil nil default-time default-input
16251 inactive))))))
16252 (cond
16253 ((and ts
16254 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16255 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16256 (insert "--")
16257 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16259 ;; Make sure we're on a timestamp. When in the middle of a date
16260 ;; range, move arbitrarily to range end.
16261 (unless (org-at-timestamp-p 'lax)
16262 (skip-chars-forward "-")
16263 (org-at-timestamp-p 'lax))
16264 (replace-match "")
16265 (setq org-last-changed-timestamp
16266 (org-insert-time-stamp
16267 time (or org-time-was-given arg)
16268 inactive nil nil (list org-end-time-was-given)))
16269 (when repeater
16270 (backward-char)
16271 (insert " " repeater)
16272 (setq org-last-changed-timestamp
16273 (concat (substring org-last-inserted-timestamp 0 -1)
16274 " " repeater ">")))
16275 (message "Timestamp updated"))
16276 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16277 (t (org-insert-time-stamp
16278 time (or org-time-was-given arg) inactive nil nil
16279 (list org-end-time-was-given))))))
16281 ;; FIXME: can we use this for something else, like computing time differences?
16282 (defun org-get-compact-tod (s)
16283 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16284 (let* ((t1 (match-string 1 s))
16285 (h1 (string-to-number (match-string 2 s)))
16286 (m1 (string-to-number (match-string 3 s)))
16287 (t2 (and (match-end 4) (match-string 5 s)))
16288 (h2 (and t2 (string-to-number (match-string 6 s))))
16289 (m2 (and t2 (string-to-number (match-string 7 s))))
16290 dh dm)
16291 (if (not t2)
16293 (setq dh (- h2 h1) dm (- m2 m1))
16294 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16295 (concat t1 "+" (number-to-string dh)
16296 (and (/= 0 dm) (format ":%02d" dm)))))))
16298 (defun org-time-stamp-inactive (&optional arg)
16299 "Insert an inactive time stamp.
16300 An inactive time stamp is enclosed in square brackets instead of angle
16301 brackets. It is inactive in the sense that it does not trigger agenda entries,
16302 does not link to the calendar and cannot be changed with the S-cursor keys.
16303 So these are more for recording a certain time/date."
16304 (interactive "P")
16305 (org-time-stamp arg 'inactive))
16307 (defvar org-date-ovl (make-overlay 1 1))
16308 (overlay-put org-date-ovl 'face 'org-date-selected)
16309 (delete-overlay org-date-ovl)
16311 (defvar org-ans1) ; dynamically scoped parameter
16312 (defvar org-ans2) ; dynamically scoped parameter
16314 (defvar org-plain-time-of-day-regexp) ; defined below
16316 (defvar org-overriding-default-time nil) ; dynamically scoped
16317 (defvar org-read-date-overlay nil)
16318 (defvar org-dcst nil) ; dynamically scoped
16319 (defvar org-read-date-history nil)
16320 (defvar org-read-date-final-answer nil)
16321 (defvar org-read-date-analyze-futurep nil)
16322 (defvar org-read-date-analyze-forced-year nil)
16323 (defvar org-read-date-inactive)
16325 (defvar org-read-date-minibuffer-local-map
16326 (let* ((map (make-sparse-keymap)))
16327 (set-keymap-parent map minibuffer-local-map)
16328 (org-defkey map (kbd ".")
16329 (lambda () (interactive)
16330 ;; Are we at the beginning of the prompt?
16331 (if (looking-back "^[^:]+: "
16332 (let ((inhibit-field-text-motion t))
16333 (line-beginning-position)))
16334 (org-eval-in-calendar '(calendar-goto-today))
16335 (insert "."))))
16336 (org-defkey map (kbd "C-.")
16337 (lambda () (interactive)
16338 (org-eval-in-calendar '(calendar-goto-today))))
16339 (org-defkey map [(meta shift left)]
16340 (lambda () (interactive)
16341 (org-eval-in-calendar '(calendar-backward-month 1))))
16342 (org-defkey map [(meta shift right)]
16343 (lambda () (interactive)
16344 (org-eval-in-calendar '(calendar-forward-month 1))))
16345 (org-defkey map [(meta shift up)]
16346 (lambda () (interactive)
16347 (org-eval-in-calendar '(calendar-backward-year 1))))
16348 (org-defkey map [(meta shift down)]
16349 (lambda () (interactive)
16350 (org-eval-in-calendar '(calendar-forward-year 1))))
16351 (org-defkey map [?\e (shift left)]
16352 (lambda () (interactive)
16353 (org-eval-in-calendar '(calendar-backward-month 1))))
16354 (org-defkey map [?\e (shift right)]
16355 (lambda () (interactive)
16356 (org-eval-in-calendar '(calendar-forward-month 1))))
16357 (org-defkey map [?\e (shift up)]
16358 (lambda () (interactive)
16359 (org-eval-in-calendar '(calendar-backward-year 1))))
16360 (org-defkey map [?\e (shift down)]
16361 (lambda () (interactive)
16362 (org-eval-in-calendar '(calendar-forward-year 1))))
16363 (org-defkey map [(shift up)]
16364 (lambda () (interactive)
16365 (org-eval-in-calendar '(calendar-backward-week 1))))
16366 (org-defkey map [(shift down)]
16367 (lambda () (interactive)
16368 (org-eval-in-calendar '(calendar-forward-week 1))))
16369 (org-defkey map [(shift left)]
16370 (lambda () (interactive)
16371 (org-eval-in-calendar '(calendar-backward-day 1))))
16372 (org-defkey map [(shift right)]
16373 (lambda () (interactive)
16374 (org-eval-in-calendar '(calendar-forward-day 1))))
16375 (org-defkey map "!"
16376 (lambda () (interactive)
16377 (org-eval-in-calendar '(diary-view-entries))
16378 (message "")))
16379 (org-defkey map ">"
16380 (lambda () (interactive)
16381 (org-eval-in-calendar '(calendar-scroll-left 1))))
16382 (org-defkey map "<"
16383 (lambda () (interactive)
16384 (org-eval-in-calendar '(calendar-scroll-right 1))))
16385 (org-defkey map "\C-v"
16386 (lambda () (interactive)
16387 (org-eval-in-calendar
16388 '(calendar-scroll-left-three-months 1))))
16389 (org-defkey map "\M-v"
16390 (lambda () (interactive)
16391 (org-eval-in-calendar
16392 '(calendar-scroll-right-three-months 1))))
16393 map)
16394 "Keymap for minibuffer commands when using `org-read-date'.")
16396 (defvar org-def)
16397 (defvar org-defdecode)
16398 (defvar org-with-time)
16400 (defvar calendar-setup) ; Dynamically scoped.
16401 (defun org-read-date (&optional with-time to-time from-string prompt
16402 default-time default-input inactive)
16403 "Read a date, possibly a time, and make things smooth for the user.
16404 The prompt will suggest to enter an ISO date, but you can also enter anything
16405 which will at least partially be understood by `parse-time-string'.
16406 Unrecognized parts of the date will default to the current day, month, year,
16407 hour and minute. If this command is called to replace a timestamp at point,
16408 or to enter the second timestamp of a range, the default time is taken
16409 from the existing stamp. Furthermore, the command prefers the future,
16410 so if you are giving a date where the year is not given, and the day-month
16411 combination is already past in the current year, it will assume you
16412 mean next year. For details, see the manual. A few examples:
16414 3-2-5 --> 2003-02-05
16415 feb 15 --> currentyear-02-15
16416 2/15 --> currentyear-02-15
16417 sep 12 9 --> 2009-09-12
16418 12:45 --> today 12:45
16419 22 sept 0:34 --> currentyear-09-22 0:34
16420 12 --> currentyear-currentmonth-12
16421 Fri --> nearest Friday after today
16422 -Tue --> last Tuesday
16423 etc.
16425 Furthermore you can specify a relative date by giving, as the *first* thing
16426 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16427 change in days weeks, months, years.
16428 With a single plus or minus, the date is relative to today. With a double
16429 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16430 +4d --> four days from today
16431 +4 --> same as above
16432 +2w --> two weeks from today
16433 ++5 --> five days from default date
16435 The function understands only English month and weekday abbreviations.
16437 While prompting, a calendar is popped up - you can also select the
16438 date with the mouse (button 1). The calendar shows a period of three
16439 months. To scroll it to other months, use the keys `>' and `<'.
16440 If you don't like the calendar, turn it off with
16441 (setq org-read-date-popup-calendar nil)
16443 With optional argument TO-TIME, the date will immediately be converted
16444 to an internal time.
16445 With an optional argument WITH-TIME, the prompt will suggest to
16446 also insert a time. Note that when WITH-TIME is not set, you can
16447 still enter a time, and this function will inform the calling routine
16448 about this change. The calling routine may then choose to change the
16449 format used to insert the time stamp into the buffer to include the time.
16450 With optional argument FROM-STRING, read from this string instead from
16451 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16452 the time/date that is used for everything that is not specified by the
16453 user."
16454 (require 'parse-time)
16455 (let* ((org-with-time with-time)
16456 (org-time-stamp-rounding-minutes
16457 (if (equal org-with-time '(16))
16458 '(0 0)
16459 org-time-stamp-rounding-minutes))
16460 (org-dcst org-display-custom-times)
16461 (ct (org-current-time))
16462 (org-def (or org-overriding-default-time default-time ct))
16463 (org-defdecode (decode-time org-def))
16464 (cur-frame (selected-frame))
16465 (mouse-autoselect-window nil) ; Don't let the mouse jump
16466 (calendar-setup
16467 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16468 (calendar-move-hook nil)
16469 (calendar-view-diary-initially-flag nil)
16470 (calendar-view-holidays-initially-flag nil)
16471 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16472 ;; Rationalize `org-def' and `org-defdecode', if required.
16473 (when (< (nth 2 org-defdecode) org-extend-today-until)
16474 (setf (nth 2 org-defdecode) -1)
16475 (setf (nth 1 org-defdecode) 59)
16476 (setq org-def (apply #'encode-time org-defdecode))
16477 (setq org-defdecode (decode-time org-def)))
16478 (let* ((timestr (format-time-string
16479 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16480 org-def))
16481 (prompt (concat (if prompt (concat prompt " ") "")
16482 (format "Date+time [%s]: " timestr))))
16483 (cond
16484 (from-string (setq ans from-string))
16485 (org-read-date-popup-calendar
16486 (save-excursion
16487 (save-window-excursion
16488 (calendar)
16489 (when (eq calendar-setup 'calendar-only)
16490 (setq cal-frame
16491 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16492 (select-frame cal-frame))
16493 (org-eval-in-calendar '(setq cursor-type nil) t)
16494 (unwind-protect
16495 (progn
16496 (calendar-forward-day (- (time-to-days org-def)
16497 (calendar-absolute-from-gregorian
16498 (calendar-current-date))))
16499 (org-eval-in-calendar nil t)
16500 (let* ((old-map (current-local-map))
16501 (map (copy-keymap calendar-mode-map))
16502 (minibuffer-local-map
16503 (copy-keymap org-read-date-minibuffer-local-map)))
16504 (org-defkey map (kbd "RET") 'org-calendar-select)
16505 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16506 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16507 (unwind-protect
16508 (progn
16509 (use-local-map map)
16510 (setq org-read-date-inactive inactive)
16511 (add-hook 'post-command-hook 'org-read-date-display)
16512 (setq org-ans0
16513 (read-string prompt
16514 default-input
16515 'org-read-date-history
16516 nil))
16517 ;; org-ans0: from prompt
16518 ;; org-ans1: from mouse click
16519 ;; org-ans2: from calendar motion
16520 (setq ans
16521 (concat org-ans0 " " (or org-ans1 org-ans2))))
16522 (remove-hook 'post-command-hook 'org-read-date-display)
16523 (use-local-map old-map)
16524 (when org-read-date-overlay
16525 (delete-overlay org-read-date-overlay)
16526 (setq org-read-date-overlay nil)))))
16527 (bury-buffer "*Calendar*")
16528 (when cal-frame
16529 (delete-frame cal-frame)
16530 (select-frame-set-input-focus cur-frame))))))
16532 (t ; Naked prompt only
16533 (unwind-protect
16534 (setq ans (read-string prompt default-input
16535 'org-read-date-history timestr))
16536 (when org-read-date-overlay
16537 (delete-overlay org-read-date-overlay)
16538 (setq org-read-date-overlay nil))))))
16540 (setq final (org-read-date-analyze ans org-def org-defdecode))
16542 (when org-read-date-analyze-forced-year
16543 (message "Year was forced into %s"
16544 (if org-read-date-force-compatible-dates
16545 "compatible range (1970-2037)"
16546 "range representable on this machine"))
16547 (ding))
16549 ;; One round trip to get rid of 34th of August and stuff like that....
16550 (setq final (decode-time (apply 'encode-time final)))
16552 (setq org-read-date-final-answer ans)
16554 (if to-time
16555 (apply 'encode-time final)
16556 (if (and (boundp 'org-time-was-given) org-time-was-given)
16557 (format "%04d-%02d-%02d %02d:%02d"
16558 (nth 5 final) (nth 4 final) (nth 3 final)
16559 (nth 2 final) (nth 1 final))
16560 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16562 (defun org-read-date-display ()
16563 "Display the current date prompt interpretation in the minibuffer."
16564 (when org-read-date-display-live
16565 (when org-read-date-overlay
16566 (delete-overlay org-read-date-overlay))
16567 (when (minibufferp (current-buffer))
16568 (save-excursion
16569 (end-of-line 1)
16570 (while (not (equal (buffer-substring
16571 (max (point-min) (- (point) 4)) (point))
16572 " "))
16573 (insert " ")))
16574 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16575 " " (or org-ans1 org-ans2)))
16576 (org-end-time-was-given nil)
16577 (f (org-read-date-analyze ans org-def org-defdecode))
16578 (fmts (if org-dcst
16579 org-time-stamp-custom-formats
16580 org-time-stamp-formats))
16581 (fmt (if (or org-with-time
16582 (and (boundp 'org-time-was-given) org-time-was-given))
16583 (cdr fmts)
16584 (car fmts)))
16585 (txt (format-time-string fmt (apply 'encode-time f)))
16586 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16587 (txt (concat "=> " txt)))
16588 (when (and org-end-time-was-given
16589 (string-match org-plain-time-of-day-regexp txt))
16590 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16591 org-end-time-was-given
16592 (substring txt (match-end 0)))))
16593 (when org-read-date-analyze-futurep
16594 (setq txt (concat txt " (=>F)")))
16595 (setq org-read-date-overlay
16596 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16597 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16599 (defun org-read-date-analyze (ans def defdecode)
16600 "Analyze the combined answer of the date prompt."
16601 ;; FIXME: cleanup and comment
16602 ;; Pass `current-time' result to `decode-time' (instead of calling
16603 ;; without arguments) so that only `current-time' has to be
16604 ;; overridden in tests.
16605 (let ((org-def def)
16606 (org-defdecode defdecode)
16607 (nowdecode (decode-time (current-time)))
16608 delta deltan deltaw deltadef year month day
16609 hour minute second wday pm h2 m2 tl wday1
16610 iso-year iso-weekday iso-week iso-date futurep kill-year)
16611 (setq org-read-date-analyze-futurep nil
16612 org-read-date-analyze-forced-year nil)
16613 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16614 (setq ans "+0"))
16616 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16617 (setq ans (replace-match "" t t ans)
16618 deltan (car delta)
16619 deltaw (nth 1 delta)
16620 deltadef (nth 2 delta)))
16622 ;; Check if there is an iso week date in there. If yes, store the
16623 ;; info and postpone interpreting it until the rest of the parsing
16624 ;; is done.
16625 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16626 (setq iso-year (when (match-end 1)
16627 (org-small-year-to-year
16628 (string-to-number (match-string 1 ans))))
16629 iso-weekday (when (match-end 3)
16630 (string-to-number (match-string 3 ans)))
16631 iso-week (string-to-number (match-string 2 ans)))
16632 (setq ans (replace-match "" t t ans)))
16634 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16635 (when (string-match
16636 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16637 (setq year (if (match-end 2)
16638 (string-to-number (match-string 2 ans))
16639 (progn (setq kill-year t)
16640 (string-to-number (format-time-string "%Y"))))
16641 month (string-to-number (match-string 3 ans))
16642 day (string-to-number (match-string 4 ans)))
16643 (setq year (org-small-year-to-year year))
16644 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16645 t nil ans)))
16647 ;; Help matching dotted european dates
16648 (when (string-match
16649 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16650 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16651 (setq kill-year t)
16652 (string-to-number (format-time-string "%Y")))
16653 day (string-to-number (match-string 1 ans))
16654 month (string-to-number (match-string 2 ans))
16655 ans (replace-match (format "%04d-%02d-%02d" year month day)
16656 t nil ans)))
16658 ;; Help matching american dates, like 5/30 or 5/30/7
16659 (when (string-match
16660 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16661 (setq year (if (match-end 4)
16662 (string-to-number (match-string 4 ans))
16663 (progn (setq kill-year t)
16664 (string-to-number (format-time-string "%Y"))))
16665 month (string-to-number (match-string 1 ans))
16666 day (string-to-number (match-string 2 ans)))
16667 (setq year (org-small-year-to-year year))
16668 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16669 t nil ans)))
16670 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16671 ;; If there is a time with am/pm, and *no* time without it, we convert
16672 ;; so that matching will be successful.
16673 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16674 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16675 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16676 (setq hour (string-to-number (match-string 1 ans))
16677 minute (if (match-end 3)
16678 (string-to-number (match-string 3 ans))
16680 pm (equal ?p
16681 (string-to-char (downcase (match-string 4 ans)))))
16682 (if (and (= hour 12) (not pm))
16683 (setq hour 0)
16684 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16685 (setq ans (replace-match (format "%02d:%02d" hour minute)
16686 t t ans))))
16688 ;; Check if a time range is given as a duration
16689 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16690 (setq hour (string-to-number (match-string 1 ans))
16691 h2 (+ hour (string-to-number (match-string 3 ans)))
16692 minute (string-to-number (match-string 2 ans))
16693 m2 (+ minute (if (match-end 5) (string-to-number
16694 (match-string 5 ans))0)))
16695 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16696 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16697 t t ans)))
16699 ;; Check if there is a time range
16700 (when (boundp 'org-end-time-was-given)
16701 (setq org-time-was-given nil)
16702 (when (and (string-match org-plain-time-of-day-regexp ans)
16703 (match-end 8))
16704 (setq org-end-time-was-given (match-string 8 ans))
16705 (setq ans (concat (substring ans 0 (match-beginning 7))
16706 (substring ans (match-end 7))))))
16708 (setq tl (parse-time-string ans)
16709 day (or (nth 3 tl) (nth 3 org-defdecode))
16710 month
16711 (cond ((nth 4 tl))
16712 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16713 ;; Day was specified. Make sure DAY+MONTH
16714 ;; combination happens in the future.
16715 ((nth 3 tl)
16716 (setq futurep t)
16717 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16718 (nth 4 nowdecode)))
16719 (t (nth 4 org-defdecode)))
16720 year
16721 (cond ((and (not kill-year) (nth 5 tl)))
16722 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16723 ;; Month was guessed in the future and is at least
16724 ;; equal to NOWDECODE's. Fix year accordingly.
16725 (futurep
16726 (if (or (> month (nth 4 nowdecode))
16727 (>= day (nth 3 nowdecode)))
16728 (nth 5 nowdecode)
16729 (1+ (nth 5 nowdecode))))
16730 ;; Month was specified. Make sure MONTH+YEAR
16731 ;; combination happens in the future.
16732 ((nth 4 tl)
16733 (setq futurep t)
16734 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16735 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16736 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16737 (t (nth 5 nowdecode))))
16738 (t (nth 5 org-defdecode)))
16739 hour (or (nth 2 tl) (nth 2 org-defdecode))
16740 minute (or (nth 1 tl) (nth 1 org-defdecode))
16741 second (or (nth 0 tl) 0)
16742 wday (nth 6 tl))
16744 (when (and (eq org-read-date-prefer-future 'time)
16745 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16746 (equal day (nth 3 nowdecode))
16747 (equal month (nth 4 nowdecode))
16748 (equal year (nth 5 nowdecode))
16749 (nth 2 tl)
16750 (or (< (nth 2 tl) (nth 2 nowdecode))
16751 (and (= (nth 2 tl) (nth 2 nowdecode))
16752 (nth 1 tl)
16753 (< (nth 1 tl) (nth 1 nowdecode)))))
16754 (setq day (1+ day)
16755 futurep t))
16757 ;; Special date definitions below
16758 (cond
16759 (iso-week
16760 ;; There was an iso week
16761 (require 'cal-iso)
16762 (setq futurep nil)
16763 (setq year (or iso-year year)
16764 day (or iso-weekday wday 1)
16765 wday nil ; to make sure that the trigger below does not match
16766 iso-date (calendar-gregorian-from-absolute
16767 (calendar-iso-to-absolute
16768 (list iso-week day year))))
16769 ; FIXME: Should we also push ISO weeks into the future?
16770 ; (when (and org-read-date-prefer-future
16771 ; (not iso-year)
16772 ; (< (calendar-absolute-from-gregorian iso-date)
16773 ; (time-to-days (current-time))))
16774 ; (setq year (1+ year)
16775 ; iso-date (calendar-gregorian-from-absolute
16776 ; (calendar-iso-to-absolute
16777 ; (list iso-week day year)))))
16778 (setq month (car iso-date)
16779 year (nth 2 iso-date)
16780 day (nth 1 iso-date)))
16781 (deltan
16782 (setq futurep nil)
16783 (unless deltadef
16784 ;; Pass `current-time' result to `decode-time' (instead of
16785 ;; calling without arguments) so that only `current-time' has
16786 ;; to be overridden in tests.
16787 (let ((now (decode-time (current-time))))
16788 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16789 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16790 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16791 ((equal deltaw "m") (setq month (+ month deltan)))
16792 ((equal deltaw "y") (setq year (+ year deltan)))))
16793 ((and wday (not (nth 3 tl)))
16794 ;; Weekday was given, but no day, so pick that day in the week
16795 ;; on or after the derived date.
16796 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16797 (unless (equal wday wday1)
16798 (setq day (+ day (% (- wday wday1 -7) 7))))))
16799 (when (and (boundp 'org-time-was-given)
16800 (nth 2 tl))
16801 (setq org-time-was-given t))
16802 (when (< year 100) (setq year (+ 2000 year)))
16803 ;; Check of the date is representable
16804 (if org-read-date-force-compatible-dates
16805 (progn
16806 (when (< year 1970)
16807 (setq year 1970 org-read-date-analyze-forced-year t))
16808 (when (> year 2037)
16809 (setq year 2037 org-read-date-analyze-forced-year t)))
16810 (condition-case nil
16811 (ignore (encode-time second minute hour day month year))
16812 (error
16813 (setq year (nth 5 org-defdecode))
16814 (setq org-read-date-analyze-forced-year t))))
16815 (setq org-read-date-analyze-futurep futurep)
16816 (list second minute hour day month year)))
16818 (defvar parse-time-weekdays)
16819 (defun org-read-date-get-relative (s today default)
16820 "Check string S for special relative date string.
16821 TODAY and DEFAULT are internal times, for today and for a default.
16822 Return shift list (N what def-flag)
16823 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16824 N is the number of WHATs to shift.
16825 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16826 the DEFAULT date rather than TODAY."
16827 (require 'parse-time)
16828 (when (and
16829 (string-match
16830 (concat
16831 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16832 "\\([0-9]+\\)?"
16833 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16834 "\\([ \t]\\|$\\)") s)
16835 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16836 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16837 (string-to-char (substring (match-string 1 s) -1))
16838 ?+))
16839 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16840 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16841 (what (if (match-end 3) (match-string 3 s) "d"))
16842 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16843 (date (if rel default today))
16844 (wday (nth 6 (decode-time date)))
16845 delta)
16846 (if wday1
16847 (progn
16848 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16849 (when (= delta 0) (setq delta 7))
16850 (when (= dir ?-)
16851 (setq delta (- delta 7))
16852 (when (= delta 0) (setq delta -7)))
16853 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16854 (list delta "d" rel))
16855 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16857 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16858 "Turn a user-specified date into the internal representation.
16859 The internal representation needed by the calendar is (month day year).
16860 This is a wrapper to handle the brain-dead convention in calendar that
16861 user function argument order change dependent on argument order."
16862 (pcase calendar-date-style
16863 (`american (list arg1 arg2 arg3))
16864 (`european (list arg2 arg1 arg3))
16865 (`iso (list arg2 arg3 arg1))))
16867 (defun org-eval-in-calendar (form &optional keepdate)
16868 "Eval FORM in the calendar window and return to current window.
16869 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16870 (let ((sf (selected-frame))
16871 (sw (selected-window)))
16872 (select-window (get-buffer-window "*Calendar*" t))
16873 (eval form)
16874 (when (and (not keepdate) (calendar-cursor-to-date))
16875 (let* ((date (calendar-cursor-to-date))
16876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16877 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16878 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16879 (select-window sw)
16880 (select-frame-set-input-focus sf)))
16882 (defun org-calendar-select ()
16883 "Return to `org-read-date' with the date currently selected.
16884 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16885 (interactive)
16886 (when (calendar-cursor-to-date)
16887 (let* ((date (calendar-cursor-to-date))
16888 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16889 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16890 (when (active-minibuffer-window) (exit-minibuffer))))
16892 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16893 "Insert a date stamp for the date given by the internal TIME.
16894 See `format-time-string' for the format of TIME.
16895 WITH-HM means use the stamp format that includes the time of the day.
16896 INACTIVE means use square brackets instead of angular ones, so that the
16897 stamp will not contribute to the agenda.
16898 PRE and POST are optional strings to be inserted before and after the
16899 stamp.
16900 The command returns the inserted time stamp."
16901 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16902 stamp)
16903 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16904 (insert-before-markers (or pre ""))
16905 (when (listp extra)
16906 (setq extra (car extra))
16907 (if (and (stringp extra)
16908 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16909 (setq extra (format "-%02d:%02d"
16910 (string-to-number (match-string 1 extra))
16911 (string-to-number (match-string 2 extra))))
16912 (setq extra nil)))
16913 (when extra
16914 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16915 (insert-before-markers (setq stamp (format-time-string fmt time)))
16916 (insert-before-markers (or post ""))
16917 (setq org-last-inserted-timestamp stamp)))
16919 (defun org-toggle-time-stamp-overlays ()
16920 "Toggle the use of custom time stamp formats."
16921 (interactive)
16922 (setq org-display-custom-times (not org-display-custom-times))
16923 (unless org-display-custom-times
16924 (let ((p (point-min)) (bmp (buffer-modified-p)))
16925 (while (setq p (next-single-property-change p 'display))
16926 (when (and (get-text-property p 'display)
16927 (eq (get-text-property p 'face) 'org-date))
16928 (remove-text-properties
16929 p (setq p (next-single-property-change p 'display))
16930 '(display t))))
16931 (set-buffer-modified-p bmp)))
16932 (org-restart-font-lock)
16933 (setq org-table-may-need-update t)
16934 (if org-display-custom-times
16935 (message "Time stamps are overlaid with custom format")
16936 (message "Time stamp overlays removed")))
16938 (defun org-display-custom-time (beg end)
16939 "Overlay modified time stamp format over timestamp between BEG and END."
16940 (let* ((ts (buffer-substring beg end))
16941 t1 with-hm tf time str (off 0))
16942 (save-match-data
16943 (setq t1 (org-parse-time-string ts t))
16944 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16945 (setq off (- (match-end 0) (match-beginning 0)))))
16946 (setq end (- end off))
16947 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16948 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16949 time (org-fix-decoded-time t1)
16950 str (org-add-props
16951 (format-time-string
16952 (substring tf 1 -1) (apply 'encode-time time))
16953 nil 'mouse-face 'highlight))
16954 (put-text-property beg end 'display str)))
16956 (defun org-fix-decoded-time (time)
16957 "Set 0 instead of nil for the first 6 elements of time.
16958 Don't touch the rest."
16959 (let ((n 0))
16960 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16962 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16963 "Difference between TIMESTAMP-STRING and now in days.
16964 If SECONDS is non-nil, return the difference in seconds."
16965 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16966 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16967 (funcall fdiff (current-time)))))
16969 (defun org-deadline-close-p (timestamp-string &optional ndays)
16970 "Is the time in TIMESTAMP-STRING close to the current date?"
16971 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16972 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16973 (not (org-entry-is-done-p))))
16975 (defun org-get-wdays (ts &optional delay zero-delay)
16976 "Get the deadline lead time appropriate for timestring TS.
16977 When DELAY is non-nil, get the delay time for scheduled items
16978 instead of the deadline lead time. When ZERO-DELAY is non-nil
16979 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16980 don't try to find the delay cookie in the scheduled timestamp."
16981 (let ((tv (if delay org-scheduled-delay-days
16982 org-deadline-warning-days)))
16983 (cond
16984 ((or (and delay (< tv 0))
16985 (and delay zero-delay (<= tv 0))
16986 (and (not delay) (<= tv 0)))
16987 ;; Enforce this value no matter what
16988 (- tv))
16989 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16990 ;; lead time is specified.
16991 (floor (* (string-to-number (match-string 1 ts))
16992 (cdr (assoc (match-string 2 ts)
16993 '(("d" . 1) ("w" . 7)
16994 ("m" . 30.4) ("y" . 365.25)
16995 ("h" . 0.041667)))))))
16996 ;; go for the default.
16997 (t tv))))
16999 (defun org-calendar-select-mouse (ev)
17000 "Return to `org-read-date' with the date currently selected.
17001 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17002 (interactive "e")
17003 (mouse-set-point ev)
17004 (when (calendar-cursor-to-date)
17005 (let* ((date (calendar-cursor-to-date))
17006 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17007 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17008 (when (active-minibuffer-window) (exit-minibuffer))))
17010 (defun org-check-deadlines (ndays)
17011 "Check if there are any deadlines due or past due.
17012 A deadline is considered due if it happens within `org-deadline-warning-days'
17013 days from today's date. If the deadline appears in an entry marked DONE,
17014 it is not shown. A numeric prefix argument NDAYS can be used to test that
17015 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17016 are shown."
17017 (interactive "P")
17018 (let* ((org-warn-days
17019 (cond
17020 ((equal ndays '(4)) 100000)
17021 (ndays (prefix-numeric-value ndays))
17022 (t (abs org-deadline-warning-days))))
17023 (case-fold-search nil)
17024 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17025 (callback
17026 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17027 (message "%d deadlines past-due or due within %d days"
17028 (org-occur regexp nil callback)
17029 org-warn-days)))
17031 (defsubst org-re-timestamp (type)
17032 "Return a regexp for timestamp TYPE.
17033 Allowed values for TYPE are:
17035 all: all timestamps
17036 active: only active timestamps (<...>)
17037 inactive: only inactive timestamps ([...])
17038 scheduled: only scheduled timestamps
17039 deadline: only deadline timestamps
17040 closed: only closed time-stamps
17042 When TYPE is nil, fall back on returning a regexp that matches
17043 both scheduled and deadline timestamps."
17044 (cl-case type
17045 (all org-ts-regexp-both)
17046 (active org-ts-regexp)
17047 (inactive org-ts-regexp-inactive)
17048 (scheduled org-scheduled-time-regexp)
17049 (deadline org-deadline-time-regexp)
17050 (closed org-closed-time-regexp)
17051 (otherwise
17052 (concat "\\<"
17053 (regexp-opt (list org-deadline-string org-scheduled-string))
17054 " *<\\([^>]+\\)>"))))
17056 (defun org-check-before-date (d)
17057 "Check if there are deadlines or scheduled entries before date D."
17058 (interactive (list (org-read-date)))
17059 (let* ((case-fold-search nil)
17060 (regexp (org-re-timestamp org-ts-type))
17061 (ts-type org-ts-type)
17062 (callback
17063 (lambda ()
17064 (let ((match (match-string 1)))
17065 (and (if (memq ts-type '(active inactive all))
17066 (eq (org-element-type (save-excursion
17067 (backward-char)
17068 (org-element-context)))
17069 'timestamp)
17070 (org-at-planning-p))
17071 (time-less-p
17072 (org-time-string-to-time match t)
17073 (org-time-string-to-time d t)))))))
17074 (message "%d entries before %s"
17075 (org-occur regexp nil callback)
17076 d)))
17078 (defun org-check-after-date (d)
17079 "Check if there are deadlines or scheduled entries after date D."
17080 (interactive (list (org-read-date)))
17081 (let* ((case-fold-search nil)
17082 (regexp (org-re-timestamp org-ts-type))
17083 (ts-type org-ts-type)
17084 (callback
17085 (lambda ()
17086 (let ((match (match-string 1)))
17087 (and (if (memq ts-type '(active inactive all))
17088 (eq (org-element-type (save-excursion
17089 (backward-char)
17090 (org-element-context)))
17091 'timestamp)
17092 (org-at-planning-p))
17093 (not (time-less-p
17094 (org-time-string-to-time match t)
17095 (org-time-string-to-time d t))))))))
17096 (message "%d entries after %s"
17097 (org-occur regexp nil callback)
17098 d)))
17100 (defun org-check-dates-range (start-date end-date)
17101 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17102 (interactive (list (org-read-date nil nil nil "Range starts")
17103 (org-read-date nil nil nil "Range end")))
17104 (let ((case-fold-search nil)
17105 (regexp (org-re-timestamp org-ts-type))
17106 (callback
17107 (let ((type org-ts-type))
17108 (lambda ()
17109 (let ((match (match-string 1)))
17110 (and
17111 (if (memq type '(active inactive all))
17112 (eq (org-element-type (save-excursion
17113 (backward-char)
17114 (org-element-context)))
17115 'timestamp)
17116 (org-at-planning-p))
17117 (not (time-less-p
17118 (org-time-string-to-time match t)
17119 (org-time-string-to-time start-date t)))
17120 (time-less-p
17121 (org-time-string-to-time match t)
17122 (org-time-string-to-time end-date t))))))))
17123 (message "%d entries between %s and %s"
17124 (org-occur regexp nil callback) start-date end-date)))
17126 (defun org-evaluate-time-range (&optional to-buffer)
17127 "Evaluate a time range by computing the difference between start and end.
17128 Normally the result is just printed in the echo area, but with prefix arg
17129 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17130 If the time range is actually in a table, the result is inserted into the
17131 next column.
17132 For time difference computation, a year is assumed to be exactly 365
17133 days in order to avoid rounding problems."
17134 (interactive "P")
17136 (org-clock-update-time-maybe)
17137 (save-excursion
17138 (unless (org-at-date-range-p t)
17139 (goto-char (point-at-bol))
17140 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17141 (unless (org-at-date-range-p t)
17142 (user-error "Not at a time-stamp range, and none found in current line")))
17143 (let* ((ts1 (match-string 1))
17144 (ts2 (match-string 2))
17145 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17146 (match-end (match-end 0))
17147 (time1 (org-time-string-to-time ts1))
17148 (time2 (org-time-string-to-time ts2))
17149 (t1 (float-time time1))
17150 (t2 (float-time time2))
17151 (diff (abs (- t2 t1)))
17152 (negative (< (- t2 t1) 0))
17153 ;; (ys (floor (* 365 24 60 60)))
17154 (ds (* 24 60 60))
17155 (hs (* 60 60))
17156 (fy "%dy %dd %02d:%02d")
17157 (fy1 "%dy %dd")
17158 (fd "%dd %02d:%02d")
17159 (fd1 "%dd")
17160 (fh "%02d:%02d")
17161 y d h m align)
17162 (if havetime
17163 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17165 d (floor (/ diff ds)) diff (mod diff ds)
17166 h (floor (/ diff hs)) diff (mod diff hs)
17167 m (floor (/ diff 60)))
17168 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17170 d (floor (+ (/ diff ds) 0.5))
17171 h 0 m 0))
17172 (if (not to-buffer)
17173 (message "%s" (org-make-tdiff-string y d h m))
17174 (if (org-at-table-p)
17175 (progn
17176 (goto-char match-end)
17177 (setq align t)
17178 (and (looking-at " *|") (goto-char (match-end 0))))
17179 (goto-char match-end))
17180 (when (looking-at
17181 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17182 (replace-match ""))
17183 (when negative (insert " -"))
17184 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17185 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17186 (insert " " (format fh h m))))
17187 (when align (org-table-align))
17188 (message "Time difference inserted")))))
17190 (defun org-make-tdiff-string (y d h m)
17191 (let ((fmt "")
17192 (l nil))
17193 (when (> y 0)
17194 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17195 (push y l))
17196 (when (> d 0)
17197 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17198 (push d l))
17199 (when (> h 0)
17200 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17201 (push h l))
17202 (when (> m 0)
17203 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17204 (push m l))
17205 (apply 'format fmt (nreverse l))))
17207 (defun org-time-string-to-time (s &optional zone)
17208 "Convert timestamp string S into internal time.
17209 The optional ZONE is omitted or nil for Emacs local time, t for
17210 Universal Time, ‘wall’ for system wall clock time, or a string as
17211 in the TZ environment variable."
17212 (apply #'encode-time (org-parse-time-string s nil zone)))
17214 (defun org-time-string-to-seconds (s &optional zone)
17215 "Convert a timestamp string S into a number of seconds.
17216 The optional ZONE is omitted or nil for Emacs local time, t for
17217 Universal Time, ‘wall’ for system wall clock time, or a string as
17218 in the TZ environment variable."
17219 (float-time (org-time-string-to-time s zone)))
17221 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17223 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17224 "Convert time stamp S to an absolute day number.
17226 If DAYNR in non-nil, and there is a specifier for a cyclic time
17227 stamp, get the closest date to DAYNR. If PREFER is
17228 `past' (respectively `future') return a date past (respectively
17229 after) or equal to DAYNR.
17231 POS is the location of time stamp S, as a buffer position in
17232 BUFFER.
17234 Diary sexp timestamps are matched against DAYNR, when non-nil.
17235 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17236 signaled."
17237 (cond
17238 ((string-match "\\`%%\\((.*)\\)" s)
17239 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17240 ;; only able to match individual dates. If it fails, raise an
17241 ;; error.
17242 (if (and daynr
17243 (org-diary-sexp-entry
17244 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17245 daynr
17246 (signal 'org-diary-sexp-no-match (list s))))
17247 (daynr (org-closest-date s daynr prefer))
17248 (t (time-to-days
17249 (condition-case errdata
17250 (apply #'encode-time (org-parse-time-string s))
17251 (error (error "Bad timestamp `%s'%s\nError was: %s"
17253 (if (not (and buffer pos)) ""
17254 (format-message " at %d in buffer `%s'" pos buffer))
17255 (cdr errdata))))))))
17257 (defun org-days-to-iso-week (days)
17258 "Return the iso week number."
17259 (require 'cal-iso)
17260 (car (calendar-iso-from-absolute days)))
17262 (defun org-small-year-to-year (year)
17263 "Convert 2-digit years into 4-digit years.
17264 YEAR is expanded into one of the 30 next years, if possible, or
17265 into a past one. Any year larger than 99 is returned unchanged."
17266 (if (>= year 100) year
17267 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17268 (century (/ current 100))
17269 (offset (- year (% current 100))))
17270 (cond ((> offset 30) (+ (* (1- century) 100) year))
17271 ((> offset -70) (+ (* century 100) year))
17272 (t (+ (* (1+ century) 100) year))))))
17274 (defun org-time-from-absolute (d)
17275 "Return the time corresponding to date D.
17276 D may be an absolute day number, or a calendar-type list (month day year)."
17277 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17278 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17280 (defvar org-agenda-current-date)
17281 (defun org-calendar-holiday ()
17282 "List of holidays, for Diary display in Org mode."
17283 (require 'holidays)
17284 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17285 (and hl (mapconcat #'identity hl "; "))))
17287 (defun org-diary-sexp-entry (sexp entry d)
17288 "Process a SEXP diary ENTRY for date D."
17289 (require 'diary-lib)
17290 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17291 ;; dynamically.
17292 (let* ((sexp `(let ((entry ,entry)
17293 (date ',d))
17294 ,(car (read-from-string sexp))))
17295 (result (if calendar-debug-sexp (eval sexp)
17296 (condition-case nil
17297 (eval sexp)
17298 (error
17299 (beep)
17300 (message "Bad sexp at line %d in %s: %s"
17301 (org-current-line)
17302 (buffer-file-name) sexp)
17303 (sleep-for 2))))))
17304 (cond ((stringp result) (split-string result "; "))
17305 ((and (consp result)
17306 (not (consp (cdr result)))
17307 (stringp (cdr result))) (cdr result))
17308 ((and (consp result)
17309 (stringp (car result))) result)
17310 (result entry))))
17312 (defun org-diary-to-ical-string (frombuf)
17313 "Get iCalendar entries from diary entries in buffer FROMBUF.
17314 This uses the icalendar.el library."
17315 (let* ((tmpdir temporary-file-directory)
17316 (tmpfile (make-temp-name
17317 (expand-file-name "orgics" tmpdir)))
17318 buf rtn b e)
17319 (with-current-buffer frombuf
17320 (icalendar-export-region (point-min) (point-max) tmpfile)
17321 (setq buf (find-buffer-visiting tmpfile))
17322 (set-buffer buf)
17323 (goto-char (point-min))
17324 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17325 (setq b (match-beginning 0)))
17326 (goto-char (point-max))
17327 (when (re-search-backward "^END:VEVENT" nil t)
17328 (setq e (match-end 0)))
17329 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17330 (kill-buffer buf)
17331 (delete-file tmpfile)
17332 rtn))
17334 (defun org-closest-date (start current prefer)
17335 "Return closest date to CURRENT starting from START.
17337 CURRENT and START are both time stamps.
17339 When PREFER is `past', return a date that is either CURRENT or
17340 past. When PREFER is `future', return a date that is either
17341 CURRENT or future.
17343 Only time stamps with a repeater are modified. Any other time
17344 stamp stay unchanged. In any case, return value is an absolute
17345 day number."
17346 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17347 ;; No repeater. Do not shift time stamp.
17348 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17349 (let ((value (string-to-number (match-string 1 start)))
17350 (type (match-string 2 start)))
17351 (if (= 0 value)
17352 ;; Repeater with a 0-value is considered as void.
17353 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17354 (let* ((base (org-date-to-gregorian start))
17355 (target (org-date-to-gregorian current))
17356 (sday (calendar-absolute-from-gregorian base))
17357 (cday (calendar-absolute-from-gregorian target))
17358 n1 n2)
17359 ;; If START is already past CURRENT, just return START.
17360 (if (<= cday sday) sday
17361 ;; Compute closest date before (N1) and closest date past
17362 ;; (N2) CURRENT.
17363 (pcase type
17364 ("h"
17365 (let ((missing-hours
17366 (mod (+ (- (* 24 (- cday sday))
17367 (nth 2 (org-parse-time-string start)))
17368 org-extend-today-until)
17369 value)))
17370 (setf n1 (if (= missing-hours 0) cday
17371 (- cday (1+ (/ missing-hours 24)))))
17372 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17373 ((or "d" "w")
17374 (let ((value (if (equal type "w") (* 7 value) value)))
17375 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17376 (setf n2 (+ n1 value))))
17377 ("m"
17378 (let* ((add-months
17379 (lambda (d n)
17380 ;; Add N months to gregorian date D, i.e.,
17381 ;; a list (MONTH DAY YEAR). Return a valid
17382 ;; gregorian date.
17383 (let ((m (+ (nth 0 d) n)))
17384 (list (mod m 12)
17385 (nth 1 d)
17386 (+ (/ m 12) (nth 2 d))))))
17387 (months ; Complete months to TARGET.
17388 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17389 (- (nth 0 target) (nth 0 base))
17390 ;; If START's day is greater than
17391 ;; TARGET's, remove incomplete month.
17392 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17393 value)
17394 value))
17395 (before (funcall add-months base months)))
17396 (setf n1 (calendar-absolute-from-gregorian before))
17397 (setf n2
17398 (calendar-absolute-from-gregorian
17399 (funcall add-months before value)))))
17401 (let* ((d (nth 1 base))
17402 (m (nth 0 base))
17403 (y (nth 2 base))
17404 (years ; Complete years to TARGET.
17405 (* (/ (- (nth 2 target)
17407 ;; If START's month and day are
17408 ;; greater than TARGET's, remove
17409 ;; incomplete year.
17410 (if (or (> (nth 0 target) m)
17411 (and (= (nth 0 target) m)
17412 (> (nth 1 target) d)))
17415 value)
17416 value))
17417 (before (list m d (+ y years))))
17418 (setf n1 (calendar-absolute-from-gregorian before))
17419 (setf n2 (calendar-absolute-from-gregorian
17420 (list m d (+ (nth 2 before) value)))))))
17421 ;; Handle PREFER parameter, if any.
17422 (cond
17423 ((eq prefer 'past) (if (= cday n2) n2 n1))
17424 ((eq prefer 'future) (if (= cday n1) n1 n2))
17425 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17427 (defun org-date-to-gregorian (d)
17428 "Turn any specification of date D into a Gregorian date for the calendar."
17429 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17430 ((and (listp d) (= (length d) 3)) d)
17431 ((stringp d)
17432 (let ((d (org-parse-time-string d)))
17433 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17434 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17436 (defun org-parse-time-string (s &optional nodefault zone)
17437 "Parse the standard Org time string.
17439 This should be a lot faster than the normal `parse-time-string'.
17441 If time is not given, defaults to 0:00. However, with optional
17442 NODEFAULT, hour and minute fields will be nil if not given.
17444 The optional ZONE is omitted or nil for Emacs local time, t for
17445 Universal Time, ‘wall’ for system wall clock time, or a string as
17446 in the TZ environment variable."
17447 (cond ((string-match org-ts-regexp0 s)
17448 (list 0
17449 (when (or (match-beginning 8) (not nodefault))
17450 (string-to-number (or (match-string 8 s) "0")))
17451 (when (or (match-beginning 7) (not nodefault))
17452 (string-to-number (or (match-string 7 s) "0")))
17453 (string-to-number (match-string 4 s))
17454 (string-to-number (match-string 3 s))
17455 (string-to-number (match-string 2 s))
17456 nil nil zone))
17457 ((string-match "^<[^>]+>$" s)
17458 ;; FIXME: `decode-time' needs to be called with ZONE as its
17459 ;; second argument. However, this requires at least Emacs
17460 ;; 25.1. We can do it when we switch to this version as our
17461 ;; minimal requirement.
17462 (decode-time (seconds-to-time (org-matcher-time s))))
17463 (t (error "Not a standard Org time string: %s" s))))
17465 (defun org-timestamp-up (&optional arg)
17466 "Increase the date item at the cursor by one.
17467 If the cursor is on the year, change the year. If it is on the month,
17468 the day or the time, change that.
17469 With prefix ARG, change by that many units."
17470 (interactive "p")
17471 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17473 (defun org-timestamp-down (&optional arg)
17474 "Decrease the date item at the cursor by one.
17475 If the cursor is on the year, change the year. If it is on the month,
17476 the day or the time, change that.
17477 With prefix ARG, change by that many units."
17478 (interactive "p")
17479 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17481 (defun org-timestamp-up-day (&optional arg)
17482 "Increase the date in the time stamp by one day.
17483 With prefix ARG, change that many days."
17484 (interactive "p")
17485 (if (and (not (org-at-timestamp-p 'lax))
17486 (org-at-heading-p))
17487 (org-todo 'up)
17488 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17490 (defun org-timestamp-down-day (&optional arg)
17491 "Decrease the date in the time stamp by one day.
17492 With prefix ARG, change that many days."
17493 (interactive "p")
17494 (if (and (not (org-at-timestamp-p 'lax))
17495 (org-at-heading-p))
17496 (org-todo 'down)
17497 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17499 (defun org-at-timestamp-p (&optional extended)
17500 "Non-nil if point is inside a timestamp.
17502 By default, the function only consider syntactically valid active
17503 timestamps. However, the caller may have a broader definition
17504 for timestamps. As a consequence, optional argument EXTENDED can
17505 be set to the following values
17507 `inactive'
17509 Include also syntactically valid inactive timestamps.
17511 `agenda'
17513 Include timestamps allowed in Agenda, i.e., those in
17514 properties drawers, planning lines and clock lines.
17516 `lax'
17518 Ignore context. The function matches any part of the
17519 document looking like a timestamp. This includes comments,
17520 example blocks...
17522 For backward-compatibility with Org 9.0, every other non-nil
17523 value is equivalent to `inactive'.
17525 When at a timestamp, return the position of the point as a symbol
17526 among `bracket', `after', `year', `month', `hour', `minute',
17527 `day' or a number of character from the last know part of the
17528 time stamp.
17530 When matching, the match groups are the following:
17531 group 1: year
17532 group 2: month
17533 group 3: day number
17534 group 4: day name
17535 group 5: hours, if any
17536 group 6: minutes, if any"
17537 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17538 (pos (point))
17539 (match?
17540 (let ((boundaries (org-in-regexp regexp)))
17541 (save-match-data
17542 (cond ((null boundaries) nil)
17543 ((eq extended 'lax) t)
17545 (or (and (eq extended 'agenda)
17546 (or (org-at-planning-p)
17547 (org-at-property-p)
17548 (and (bound-and-true-p
17549 org-agenda-include-inactive-timestamps)
17550 (org-at-clock-log-p))))
17551 (eq 'timestamp
17552 (save-excursion
17553 (when (= pos (cdr boundaries)) (forward-char -1))
17554 (org-element-type (org-element-context)))))))))))
17555 (cond
17556 ((not match?) nil)
17557 ((= pos (match-beginning 0)) 'bracket)
17558 ;; Distinguish location right before the closing bracket from
17559 ;; right after it.
17560 ((= pos (1- (match-end 0))) 'bracket)
17561 ((= pos (match-end 0)) 'after)
17562 ((org-pos-in-match-range pos 2) 'year)
17563 ((org-pos-in-match-range pos 3) 'month)
17564 ((org-pos-in-match-range pos 7) 'hour)
17565 ((org-pos-in-match-range pos 8) 'minute)
17566 ((or (org-pos-in-match-range pos 4)
17567 (org-pos-in-match-range pos 5)) 'day)
17568 ((and (> pos (or (match-end 8) (match-end 5)))
17569 (< pos (match-end 0)))
17570 (- pos (or (match-end 8) (match-end 5))))
17571 (t 'day))))
17573 (defun org-toggle-timestamp-type ()
17574 "Toggle the type (<active> or [inactive]) of a time stamp."
17575 (interactive)
17576 (when (org-at-timestamp-p 'lax)
17577 (let ((beg (match-beginning 0)) (end (match-end 0))
17578 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17579 (save-excursion
17580 (goto-char beg)
17581 (while (re-search-forward "[][<>]" end t)
17582 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17583 t t)))
17584 (message "Timestamp is now %sactive"
17585 (if (equal (char-after beg) ?<) "" "in")))))
17587 (defun org-at-clock-log-p ()
17588 "Non-nil if point is on a clock log line."
17589 (and (org-match-line org-clock-line-re)
17590 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17592 (defvar org-clock-history) ; defined in org-clock.el
17593 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17594 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17595 "Change the date in the time stamp at point.
17596 The date will be changed by N times WHAT. WHAT can be `day', `month',
17597 `year', `minute', `second'. If WHAT is not given, the cursor position
17598 in the timestamp determines what will be changed.
17599 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17600 (let ((origin (point))
17601 (timestamp? (org-at-timestamp-p 'lax))
17602 origin-cat
17603 with-hm inactive
17604 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17605 extra rem
17606 ts time time0 fixnext clrgx)
17607 (unless timestamp? (user-error "Not at a timestamp"))
17608 (if (and (not what) (eq timestamp? 'bracket))
17609 (org-toggle-timestamp-type)
17610 ;; Point isn't on brackets. Remember the part of the time-stamp
17611 ;; the point was in. Indeed, size of time-stamps may change,
17612 ;; but point must be kept in the same category nonetheless.
17613 (setq origin-cat timestamp?)
17614 (when (and (not what) (not (eq timestamp? 'day))
17615 org-display-custom-times
17616 (get-text-property (point) 'display)
17617 (not (get-text-property (1- (point)) 'display)))
17618 (setq timestamp? 'day))
17619 (setq timestamp? (or what timestamp?)
17620 inactive (= (char-after (match-beginning 0)) ?\[)
17621 ts (match-string 0))
17622 (replace-match "")
17623 (when (string-match
17624 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17626 (setq extra (match-string 1 ts))
17627 (when suppress-tmp-delay
17628 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17629 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17630 (setq with-hm t))
17631 (setq time0 (org-parse-time-string ts))
17632 (when (and updown
17633 (eq timestamp? 'minute)
17634 (not current-prefix-arg))
17635 ;; This looks like s-up and s-down. Change by one rounding step.
17636 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17637 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17638 (setcar (cdr time0) (+ (nth 1 time0)
17639 (if (> n 0) (- rem) (- dm rem))))))
17640 (setq time
17641 (apply #'encode-time
17642 (or (car time0) 0)
17643 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17644 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17645 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17646 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17647 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17648 (nthcdr 6 time0)))
17649 (when (and (memq timestamp? '(hour minute))
17650 extra
17651 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17652 (setq extra (org-modify-ts-extra
17653 extra
17654 (if (eq timestamp? 'hour) 2 5)
17655 n dm)))
17656 (when (integerp timestamp?)
17657 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17658 (when (eq what 'calendar)
17659 (let ((cal-date (org-get-date-from-calendar)))
17660 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17661 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17662 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17663 (setcar time0 (or (car time0) 0))
17664 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17665 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17666 (setq time (apply 'encode-time time0))))
17667 ;; Insert the new time-stamp, and ensure point stays in the same
17668 ;; category as before (i.e. not after the last position in that
17669 ;; category).
17670 (let ((pos (point)))
17671 ;; Stay before inserted string. `save-excursion' is of no use.
17672 (setq org-last-changed-timestamp
17673 (org-insert-time-stamp time with-hm inactive nil nil extra))
17674 (goto-char pos))
17675 (save-match-data
17676 (looking-at org-ts-regexp3)
17677 (goto-char
17678 (pcase origin-cat
17679 ;; `day' category ends before `hour' if any, or at the end
17680 ;; of the day name.
17681 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17682 (`hour (min (match-end 7) origin))
17683 (`minute (min (1- (match-end 8)) origin))
17684 ((pred integerp) (min (1- (match-end 0)) origin))
17685 ;; Point was right after the time-stamp. However, the
17686 ;; time-stamp length might have changed, so refer to
17687 ;; (match-end 0) instead.
17688 (`after (match-end 0))
17689 ;; `year' and `month' have both fixed size: point couldn't
17690 ;; have moved into another part.
17691 (_ origin))))
17692 ;; Update clock if on a CLOCK line.
17693 (org-clock-update-time-maybe)
17694 ;; Maybe adjust the closest clock in `org-clock-history'
17695 (when org-clock-adjust-closest
17696 (if (not (and (org-at-clock-log-p)
17697 (< 1 (length (delq nil (mapcar 'marker-position
17698 org-clock-history))))))
17699 (message "No clock to adjust")
17700 (cond ((save-excursion ; fix previous clock?
17701 (re-search-backward org-ts-regexp0 nil t)
17702 (looking-back (concat org-clock-string " \\[")
17703 (line-beginning-position)))
17704 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17705 ((save-excursion ; fix next clock?
17706 (re-search-backward org-ts-regexp0 nil t)
17707 (looking-at (concat org-ts-regexp0 "\\] =>")))
17708 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17709 (save-window-excursion
17710 ;; Find closest clock to point, adjust the previous/next one in history
17711 (let* ((p (save-excursion (org-back-to-heading t)))
17712 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17713 (clfixnth
17714 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17715 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17716 (if (not clfixpos)
17717 (message "No clock to adjust")
17718 (save-excursion
17719 (org-goto-marker-or-bmk clfixpos)
17720 (org-show-subtree)
17721 (when (re-search-forward clrgx nil t)
17722 (goto-char (match-beginning 1))
17723 (let (org-clock-adjust-closest)
17724 (org-timestamp-change n timestamp? updown))
17725 (message "Clock adjusted in %s for heading: %s"
17726 (file-name-nondirectory (buffer-file-name))
17727 (org-get-heading t t)))))))))
17728 ;; Try to recenter the calendar window, if any.
17729 (when (and org-calendar-follow-timestamp-change
17730 (get-buffer-window "*Calendar*" t)
17731 (memq timestamp? '(day month year)))
17732 (org-recenter-calendar (time-to-days time))))))
17734 (defun org-modify-ts-extra (s pos n dm)
17735 "Change the different parts of the lead-time and repeat fields in timestamp."
17736 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17737 ng h m new rem)
17738 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17739 (cond
17740 ((or (org-pos-in-match-range pos 2)
17741 (org-pos-in-match-range pos 3))
17742 (setq m (string-to-number (match-string 3 s))
17743 h (string-to-number (match-string 2 s)))
17744 (if (org-pos-in-match-range pos 2)
17745 (setq h (+ h n))
17746 (setq n (* dm (with-no-warnings (signum n))))
17747 (unless (= 0 (setq rem (% m dm)))
17748 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17749 (setq m (+ m n)))
17750 (when (< m 0) (setq m (+ m 60) h (1- h)))
17751 (when (> m 59) (setq m (- m 60) h (1+ h)))
17752 (setq h (mod h 24))
17753 (setq ng 1 new (format "-%02d:%02d" h m)))
17754 ((org-pos-in-match-range pos 6)
17755 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17756 ((org-pos-in-match-range pos 5)
17757 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17759 ((org-pos-in-match-range pos 9)
17760 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17761 ((org-pos-in-match-range pos 8)
17762 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17764 (when ng
17765 (setq s (concat
17766 (substring s 0 (match-beginning ng))
17768 (substring s (match-end ng))))))
17771 (defun org-recenter-calendar (d)
17772 "If the calendar is visible, recenter it to date D."
17773 (let ((cwin (get-buffer-window "*Calendar*" t)))
17774 (when cwin
17775 (let ((calendar-move-hook nil))
17776 (with-selected-window cwin
17777 (calendar-goto-date
17778 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17780 (defun org-goto-calendar (&optional arg)
17781 "Go to the Emacs calendar at the current date.
17782 If there is a time stamp in the current line, go to that date.
17783 A prefix ARG can be used to force the current date."
17784 (interactive "P")
17785 (let ((calendar-move-hook nil)
17786 (calendar-view-holidays-initially-flag nil)
17787 (calendar-view-diary-initially-flag nil)
17788 diff)
17789 (when (or (org-at-timestamp-p 'lax)
17790 (org-match-line (concat ".*" org-ts-regexp)))
17791 (let ((d1 (time-to-days (current-time)))
17792 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17793 (setq diff (- d2 d1))))
17794 (calendar)
17795 (calendar-goto-today)
17796 (when (and diff (not arg)) (calendar-forward-day diff))))
17798 (defun org-get-date-from-calendar ()
17799 "Return a list (month day year) of date at point in calendar."
17800 (with-current-buffer "*Calendar*"
17801 (save-match-data
17802 (calendar-cursor-to-date))))
17804 (defun org-date-from-calendar ()
17805 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17806 If there is already a time stamp at the cursor position, update it."
17807 (interactive)
17808 (if (org-at-timestamp-p 'lax)
17809 (org-timestamp-change 0 'calendar)
17810 (let ((cal-date (org-get-date-from-calendar)))
17811 (org-insert-time-stamp
17812 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17814 (defcustom org-effort-durations
17815 `(("min" . 1)
17816 ("h" . 60)
17817 ("d" . ,(* 60 8))
17818 ("w" . ,(* 60 8 5))
17819 ("m" . ,(* 60 8 5 4))
17820 ("y" . ,(* 60 8 5 40)))
17821 "Conversion factor to minutes for an effort modifier.
17823 Each entry has the form (MODIFIER . MINUTES).
17825 In an effort string, a number followed by MODIFIER is multiplied
17826 by the specified number of MINUTES to obtain an effort in
17827 minutes.
17829 For example, if the value of this variable is ((\"hours\" . 60)), then an
17830 effort string \"2hours\" is equivalent to 120 minutes."
17831 :group 'org-agenda
17832 :version "26.1"
17833 :package-version '(Org . "8.3")
17834 :type '(alist :key-type (string :tag "Modifier")
17835 :value-type (number :tag "Minutes")))
17837 (defcustom org-image-actual-width t
17838 "Should we use the actual width of images when inlining them?
17840 When set to t, always use the image width.
17842 When set to a number, use imagemagick (when available) to set
17843 the image's width to this value.
17845 When set to a number in a list, try to get the width from any
17846 #+ATTR.* keyword if it matches a width specification like
17848 #+ATTR_HTML: :width 300px
17850 and fall back on that number if none is found.
17852 When set to nil, try to get the width from an #+ATTR.* keyword
17853 and fall back on the original width if none is found.
17855 This requires Emacs >= 24.1, build with imagemagick support."
17856 :group 'org-appearance
17857 :version "24.4"
17858 :package-version '(Org . "8.0")
17859 :type '(choice
17860 (const :tag "Use the image width" t)
17861 (integer :tag "Use a number of pixels")
17862 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17863 (const :tag "Use #+ATTR* or don't resize" nil)))
17865 (defcustom org-agenda-inhibit-startup nil
17866 "Inhibit startup when preparing agenda buffers.
17867 When this variable is t, the initialization of the Org agenda
17868 buffers is inhibited: e.g. the visibility state is not set, the
17869 tables are not re-aligned, etc."
17870 :type 'boolean
17871 :version "24.3"
17872 :group 'org-agenda)
17874 (defcustom org-agenda-ignore-properties nil
17875 "Avoid updating text properties when building the agenda.
17876 Properties are used to prepare buffers for effort estimates,
17877 appointments, statistics and subtree-local categories.
17878 If you don't use these in the agenda, you can add them to this
17879 list and agenda building will be a bit faster.
17880 The value is a list, with zero or more of the symbols `effort', `appt',
17881 `stats' or `category'."
17882 :type '(set :greedy t
17883 (const effort)
17884 (const appt)
17885 (const stats)
17886 (const category))
17887 :version "26.1"
17888 :package-version '(Org . "8.3")
17889 :group 'org-agenda)
17891 ;;;; Files
17893 (defun org-save-all-org-buffers ()
17894 "Save all Org buffers without user confirmation."
17895 (interactive)
17896 (message "Saving all Org buffers...")
17897 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17898 (when (featurep 'org-id) (org-id-locations-save))
17899 (message "Saving all Org buffers... done"))
17901 (defun org-revert-all-org-buffers ()
17902 "Revert all Org buffers.
17903 Prompt for confirmation when there are unsaved changes.
17904 Be sure you know what you are doing before letting this function
17905 overwrite your changes.
17907 This function is useful in a setup where one tracks org files
17908 with a version control system, to revert on one machine after pulling
17909 changes from another. I believe the procedure must be like this:
17911 1. M-x org-save-all-org-buffers
17912 2. Pull changes from the other machine, resolve conflicts
17913 3. M-x org-revert-all-org-buffers"
17914 (interactive)
17915 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17916 (user-error "Abort"))
17917 (save-excursion
17918 (save-window-excursion
17919 (dolist (b (buffer-list))
17920 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17921 (with-current-buffer b buffer-file-name))
17922 (pop-to-buffer-same-window b)
17923 (revert-buffer t 'no-confirm)))
17924 (when (and (featurep 'org-id) org-id-track-globally)
17925 (org-id-locations-load)))))
17927 ;;;; Agenda files
17929 ;;;###autoload
17930 (defun org-switchb (&optional arg)
17931 "Switch between Org buffers.
17933 With `\\[universal-argument]' prefix, restrict available buffers to files.
17935 With `\\[universal-argument] \\[universal-argument]' \
17936 prefix, restrict available buffers to agenda files."
17937 (interactive "P")
17938 (let ((blist (org-buffer-list
17939 (cond ((equal arg '(4)) 'files)
17940 ((equal arg '(16)) 'agenda)))))
17941 (pop-to-buffer-same-window
17942 (completing-read "Org buffer: "
17943 (mapcar #'list (mapcar #'buffer-name blist))
17944 nil t))))
17946 (defun org-buffer-list (&optional predicate exclude-tmp)
17947 "Return a list of Org buffers.
17948 PREDICATE can be `export', `files' or `agenda'.
17950 export restrict the list to Export buffers.
17951 files restrict the list to buffers visiting Org files.
17952 agenda restrict the list to buffers visiting agenda files.
17954 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17955 (let* ((bfn nil)
17956 (agenda-files (and (eq predicate 'agenda)
17957 (mapcar 'file-truename (org-agenda-files t))))
17958 (filter
17959 (cond
17960 ((eq predicate 'files)
17961 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17962 ((eq predicate 'export)
17963 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17964 ((eq predicate 'agenda)
17965 (lambda (b)
17966 (with-current-buffer b
17967 (and (derived-mode-p 'org-mode)
17968 (setq bfn (buffer-file-name b))
17969 (member (file-truename bfn) agenda-files)))))
17970 (t (lambda (b) (with-current-buffer b
17971 (or (derived-mode-p 'org-mode)
17972 (string-match "\\*Org .*Export"
17973 (buffer-name b)))))))))
17974 (delq nil
17975 (mapcar
17976 (lambda(b)
17977 (if (and (funcall filter b)
17978 (or (not exclude-tmp)
17979 (not (string-match "tmp" (buffer-name b)))))
17981 nil))
17982 (buffer-list)))))
17984 (defun org-agenda-files (&optional unrestricted archives)
17985 "Get the list of agenda files.
17986 Optional UNRESTRICTED means return the full list even if a restriction
17987 is currently in place.
17988 When ARCHIVES is t, include all archive files that are really being
17989 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17990 `org-agenda-archives-mode' is t."
17991 (let ((files
17992 (cond
17993 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17994 ((stringp org-agenda-files) (org-read-agenda-file-list))
17995 ((listp org-agenda-files) org-agenda-files)
17996 (t (error "Invalid value of `org-agenda-files'")))))
17997 (setq files (apply 'append
17998 (mapcar (lambda (f)
17999 (if (file-directory-p f)
18000 (directory-files
18001 f t org-agenda-file-regexp)
18002 (list f)))
18003 files)))
18004 (when org-agenda-skip-unavailable-files
18005 (setq files (delq nil
18006 (mapcar (function
18007 (lambda (file)
18008 (and (file-readable-p file) file)))
18009 files))))
18010 (when (or (eq archives t)
18011 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18012 (setq files (org-add-archive-files files)))
18013 files))
18015 (defun org-agenda-file-p (&optional file)
18016 "Return non-nil, if FILE is an agenda file.
18017 If FILE is omitted, use the file associated with the current
18018 buffer."
18019 (let ((fname (or file (buffer-file-name))))
18020 (and fname
18021 (member (file-truename fname)
18022 (mapcar #'file-truename (org-agenda-files t))))))
18024 (defun org-edit-agenda-file-list ()
18025 "Edit the list of agenda files.
18026 Depending on setup, this either uses customize to edit the variable
18027 `org-agenda-files', or it visits the file that is holding the list. In the
18028 latter case, the buffer is set up in a way that saving it automatically kills
18029 the buffer and restores the previous window configuration."
18030 (interactive)
18031 (if (stringp org-agenda-files)
18032 (let ((cw (current-window-configuration)))
18033 (find-file org-agenda-files)
18034 (setq-local org-window-configuration cw)
18035 (add-hook 'after-save-hook
18036 (lambda ()
18037 (set-window-configuration
18038 (prog1 org-window-configuration
18039 (kill-buffer (current-buffer))))
18040 (org-install-agenda-files-menu)
18041 (message "New agenda file list installed"))
18042 nil 'local)
18043 (message "%s" (substitute-command-keys
18044 "Edit list and finish with \\[save-buffer]")))
18045 (customize-variable 'org-agenda-files)))
18047 (defun org-store-new-agenda-file-list (list)
18048 "Set new value for the agenda file list and save it correctly."
18049 (if (stringp org-agenda-files)
18050 (let ((fe (org-read-agenda-file-list t)) b u)
18051 (while (setq b (find-buffer-visiting org-agenda-files))
18052 (kill-buffer b))
18053 (with-temp-file org-agenda-files
18054 (insert
18055 (mapconcat
18056 (lambda (f) ;; Keep un-expanded entries.
18057 (if (setq u (assoc f fe))
18058 (cdr u)
18060 list "\n")
18061 "\n")))
18062 (let ((org-mode-hook nil) (org-inhibit-startup t)
18063 (org-insert-mode-line-in-empty-file nil))
18064 (setq org-agenda-files list)
18065 (customize-save-variable 'org-agenda-files org-agenda-files))))
18067 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18068 "Read the list of agenda files from a file.
18069 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18070 filenames, used by `org-store-new-agenda-file-list' to write back
18071 un-expanded file names."
18072 (when (file-directory-p org-agenda-files)
18073 (error "`org-agenda-files' cannot be a single directory"))
18074 (when (stringp org-agenda-files)
18075 (with-temp-buffer
18076 (insert-file-contents org-agenda-files)
18077 (mapcar
18078 (lambda (f)
18079 (let ((e (expand-file-name (substitute-in-file-name f)
18080 org-directory)))
18081 (if pair-with-expansion
18082 (cons e f)
18083 e)))
18084 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18086 ;;;###autoload
18087 (defun org-cycle-agenda-files ()
18088 "Cycle through the files in `org-agenda-files'.
18089 If the current buffer visits an agenda file, find the next one in the list.
18090 If the current buffer does not, find the first agenda file."
18091 (interactive)
18092 (let* ((fs (or (org-agenda-files t)
18093 (user-error "No agenda files")))
18094 (files (copy-sequence fs))
18095 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18096 file)
18097 (when tcf
18098 (while (and (setq file (pop files))
18099 (not (equal (file-truename file) tcf)))))
18100 (find-file (car (or files fs)))
18101 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18103 (defun org-agenda-file-to-front (&optional to-end)
18104 "Move/add the current file to the top of the agenda file list.
18105 If the file is not present in the list, it is added to the front. If it is
18106 present, it is moved there. With optional argument TO-END, add/move to the
18107 end of the list."
18108 (interactive "P")
18109 (let ((org-agenda-skip-unavailable-files nil)
18110 (file-alist (mapcar (lambda (x)
18111 (cons (file-truename x) x))
18112 (org-agenda-files t)))
18113 (ctf (file-truename
18114 (or buffer-file-name
18115 (user-error "Please save the current buffer to a file"))))
18116 x had)
18117 (setq x (assoc ctf file-alist) had x)
18119 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18120 (if to-end
18121 (setq file-alist (append (delq x file-alist) (list x)))
18122 (setq file-alist (cons x (delq x file-alist))))
18123 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18124 (org-install-agenda-files-menu)
18125 (message "File %s to %s of agenda file list"
18126 (if had "moved" "added") (if to-end "end" "front"))))
18128 (defun org-remove-file (&optional file)
18129 "Remove current file from the list of files in variable `org-agenda-files'.
18130 These are the files which are being checked for agenda entries.
18131 Optional argument FILE means use this file instead of the current."
18132 (interactive)
18133 (let* ((org-agenda-skip-unavailable-files nil)
18134 (file (or file buffer-file-name
18135 (user-error "Current buffer does not visit a file")))
18136 (true-file (file-truename file))
18137 (afile (abbreviate-file-name file))
18138 (files (delq nil (mapcar
18139 (lambda (x)
18140 (unless (equal true-file
18141 (file-truename x))
18143 (org-agenda-files t)))))
18144 (if (not (= (length files) (length (org-agenda-files t))))
18145 (progn
18146 (org-store-new-agenda-file-list files)
18147 (org-install-agenda-files-menu)
18148 (message "Removed from Org Agenda list: %s" afile))
18149 (message "File was not in list: %s (not removed)" afile))))
18151 (defun org-file-menu-entry (file)
18152 (vector file (list 'find-file file) t))
18154 (defun org-check-agenda-file (file)
18155 "Make sure FILE exists. If not, ask user what to do."
18156 (unless (file-exists-p file)
18157 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18158 (abbreviate-file-name file))
18159 (let ((r (downcase (read-char-exclusive))))
18160 (cond
18161 ((equal r ?r)
18162 (org-remove-file file)
18163 (throw 'nextfile t))
18164 (t (user-error "Abort"))))))
18166 (defun org-get-agenda-file-buffer (file)
18167 "Get an agenda buffer visiting FILE.
18168 If the buffer needs to be created, add it to the list of buffers
18169 which might be released later."
18170 (let ((buf (org-find-base-buffer-visiting file)))
18171 (if buf
18172 buf ; just return it
18173 ;; Make a new buffer and remember it
18174 (setq buf (find-file-noselect file))
18175 (when buf (push buf org-agenda-new-buffers))
18176 buf)))
18178 (defun org-release-buffers (blist)
18179 "Release all buffers in list, asking the user for confirmation when needed.
18180 When a buffer is unmodified, it is just killed. When modified, it is saved
18181 \(if the user agrees) and then killed."
18182 (let (file)
18183 (dolist (buf blist)
18184 (setq file (buffer-file-name buf))
18185 (when (and (buffer-modified-p buf)
18186 file
18187 (y-or-n-p (format "Save file %s? " file)))
18188 (with-current-buffer buf (save-buffer)))
18189 (kill-buffer buf))))
18191 (defun org-agenda-prepare-buffers (files)
18192 "Create buffers for all agenda files, protect archived trees and comments."
18193 (interactive)
18194 (let ((pa '(:org-archived t))
18195 (pc '(:org-comment t))
18196 (pall '(:org-archived t :org-comment t))
18197 (inhibit-read-only t)
18198 (org-inhibit-startup org-agenda-inhibit-startup)
18199 (rea (concat ":" org-archive-tag ":"))
18200 re pos)
18201 (setq org-tag-alist-for-agenda nil
18202 org-tag-groups-alist-for-agenda nil)
18203 (save-excursion
18204 (save-restriction
18205 (dolist (file files)
18206 (catch 'nextfile
18207 (if (bufferp file)
18208 (set-buffer file)
18209 (org-check-agenda-file file)
18210 (set-buffer (org-get-agenda-file-buffer file)))
18211 (widen)
18212 (org-set-regexps-and-options 'tags-only)
18213 (setq pos (point))
18214 (or (memq 'category org-agenda-ignore-properties)
18215 (org-refresh-category-properties))
18216 (or (memq 'stats org-agenda-ignore-properties)
18217 (org-refresh-stats-properties))
18218 (or (memq 'effort org-agenda-ignore-properties)
18219 (org-refresh-effort-properties))
18220 (or (memq 'appt org-agenda-ignore-properties)
18221 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18222 (setq org-todo-keywords-for-agenda
18223 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18224 (setq org-done-keywords-for-agenda
18225 (append org-done-keywords-for-agenda org-done-keywords))
18226 (setq org-todo-keyword-alist-for-agenda
18227 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18228 (setq org-tag-alist-for-agenda
18229 (org-uniquify
18230 (append org-tag-alist-for-agenda
18231 org-current-tag-alist)))
18232 ;; Merge current file's tag groups into global
18233 ;; `org-tag-groups-alist-for-agenda'.
18234 (when org-group-tags
18235 (dolist (alist org-tag-groups-alist)
18236 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18237 (if old
18238 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18239 (push alist org-tag-groups-alist-for-agenda)))))
18240 (org-with-silent-modifications
18241 (save-excursion
18242 (remove-text-properties (point-min) (point-max) pall)
18243 (when org-agenda-skip-archived-trees
18244 (goto-char (point-min))
18245 (while (re-search-forward rea nil t)
18246 (when (org-at-heading-p t)
18247 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18248 (goto-char (point-min))
18249 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18250 (while (re-search-forward re nil t)
18251 (when (save-match-data (org-in-commented-heading-p t))
18252 (add-text-properties
18253 (match-beginning 0) (org-end-of-subtree t) pc)))))
18254 (goto-char pos)))))
18255 (setq org-todo-keywords-for-agenda
18256 (org-uniquify org-todo-keywords-for-agenda))
18257 (setq org-todo-keyword-alist-for-agenda
18258 (org-uniquify org-todo-keyword-alist-for-agenda))))
18261 ;;;; CDLaTeX minor mode
18263 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18264 "Keymap for the minor `org-cdlatex-mode'.")
18266 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18267 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18268 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18269 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18270 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18272 (defvar org-cdlatex-texmathp-advice-is-done nil
18273 "Flag remembering if we have applied the advice to texmathp already.")
18275 (define-minor-mode org-cdlatex-mode
18276 "Toggle the minor `org-cdlatex-mode'.
18277 This mode supports entering LaTeX environment and math in LaTeX fragments
18278 in Org mode.
18279 \\{org-cdlatex-mode-map}"
18280 nil " OCDL" nil
18281 (when org-cdlatex-mode
18282 (require 'cdlatex)
18283 (run-hooks 'cdlatex-mode-hook)
18284 (cdlatex-compute-tables))
18285 (unless org-cdlatex-texmathp-advice-is-done
18286 (setq org-cdlatex-texmathp-advice-is-done t)
18287 (defadvice texmathp (around org-math-always-on activate)
18288 "Always return t in Org buffers.
18289 This is because we want to insert math symbols without dollars even outside
18290 the LaTeX math segments. If Org mode thinks that point is actually inside
18291 an embedded LaTeX fragment, let `texmathp' do its job.
18292 `\\[org-cdlatex-mode-map]'"
18293 (interactive)
18294 (let (p)
18295 (cond
18296 ((not (derived-mode-p 'org-mode)) ad-do-it)
18297 ((eq this-command 'cdlatex-math-symbol)
18298 (setq ad-return-value t
18299 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18301 (let ((p (org-inside-LaTeX-fragment-p)))
18302 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18303 (setq ad-return-value t
18304 texmathp-why '("Org mode embedded math" . 0))
18305 (when p ad-do-it)))))))))
18307 (defun turn-on-org-cdlatex ()
18308 "Unconditionally turn on `org-cdlatex-mode'."
18309 (org-cdlatex-mode 1))
18311 (defun org-try-cdlatex-tab ()
18312 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18313 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18314 - inside a LaTeX fragment, or
18315 - after the first word in a line, where an abbreviation expansion could
18316 insert a LaTeX environment."
18317 (when org-cdlatex-mode
18318 (cond
18319 ;; Before any word on the line: No expansion possible.
18320 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18321 ;; Just after first word on the line: Expand it. Make sure it
18322 ;; cannot happen on headlines, though.
18323 ((save-excursion
18324 (skip-chars-backward "a-zA-Z0-9*")
18325 (skip-chars-backward " \t")
18326 (and (bolp) (not (org-at-heading-p))))
18327 (cdlatex-tab) t)
18328 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18330 (defun org-cdlatex-underscore-caret (&optional _arg)
18331 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18332 Revert to the normal definition outside of these fragments."
18333 (interactive "P")
18334 (if (org-inside-LaTeX-fragment-p)
18335 (call-interactively 'cdlatex-sub-superscript)
18336 (let (org-cdlatex-mode)
18337 (call-interactively (key-binding (vector last-input-event))))))
18339 (defun org-cdlatex-math-modify (&optional _arg)
18340 "Execute `cdlatex-math-modify' in LaTeX fragments.
18341 Revert to the normal definition outside of these fragments."
18342 (interactive "P")
18343 (if (org-inside-LaTeX-fragment-p)
18344 (call-interactively 'cdlatex-math-modify)
18345 (let (org-cdlatex-mode)
18346 (call-interactively (key-binding (vector last-input-event))))))
18348 (defun org-cdlatex-environment-indent (&optional environment item)
18349 "Execute `cdlatex-environment' and indent the inserted environment.
18351 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18353 The inserted environment is indented to current indentation
18354 unless point is at the beginning of the line, in which the
18355 environment remains unintended."
18356 (interactive)
18357 ;; cdlatex-environment always return nil. Therefore, capture output
18358 ;; first and determine if an environment was selected.
18359 (let* ((beg (point-marker))
18360 (end (copy-marker (point) t))
18361 (inserted (progn
18362 (ignore-errors (cdlatex-environment environment item))
18363 (< beg end)))
18364 ;; Figure out how many lines to move forward after the
18365 ;; environment has been inserted.
18366 (lines (when inserted
18367 (save-excursion
18368 (- (cl-loop while (< beg (point))
18369 with x = 0
18370 do (forward-line -1)
18371 (cl-incf x)
18372 finally return x)
18373 (if (progn (goto-char beg)
18374 (and (progn (skip-chars-forward " \t") (eolp))
18375 (progn (skip-chars-backward " \t") (bolp))))
18376 1 0)))))
18377 (env (org-trim (delete-and-extract-region beg end))))
18378 (when inserted
18379 ;; Get indentation of next line unless at column 0.
18380 (let ((ind (if (bolp) 0
18381 (save-excursion
18382 (org-return-indent)
18383 (prog1 (org-get-indentation)
18384 (when (progn (skip-chars-forward " \t") (eolp))
18385 (delete-region beg (point)))))))
18386 (bol (progn (skip-chars-backward " \t") (bolp))))
18387 ;; Insert a newline before environment unless at column zero
18388 ;; to "escape" the current line. Insert a newline if
18389 ;; something is one the same line as \end{ENVIRONMENT}.
18390 (insert
18391 (concat (unless bol "\n") env
18392 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18393 (unless (zerop ind)
18394 (save-excursion
18395 (goto-char beg)
18396 (while (< (point) end)
18397 (unless (eolp) (indent-line-to ind))
18398 (forward-line))))
18399 (goto-char beg)
18400 (forward-line lines)
18401 (indent-line-to ind)))
18402 (set-marker beg nil)
18403 (set-marker end nil)))
18406 ;;;; LaTeX fragments
18408 (defun org-inside-LaTeX-fragment-p ()
18409 "Test if point is inside a LaTeX fragment.
18410 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18411 sequence appearing also before point.
18412 Even though the matchers for math are configurable, this function assumes
18413 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18414 delimiters are skipped when they have been removed by customization.
18415 The return value is nil, or a cons cell with the delimiter and the
18416 position of this delimiter.
18418 This function does a reasonably good job, but can locally be fooled by
18419 for example currency specifications. For example it will assume being in
18420 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18421 fragments that are properly closed, but during editing, we have to live
18422 with the uncertainty caused by missing closing delimiters. This function
18423 looks only before point, not after."
18424 (catch 'exit
18425 (let ((pos (point))
18426 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18427 (lim (save-excursion (org-backward-paragraph) (point)))
18428 dd-on str (start 0) m re)
18429 (goto-char pos)
18430 (when dodollar
18431 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18432 re (nth 1 (assoc "$" org-latex-regexps)))
18433 (while (string-match re str start)
18434 (cond
18435 ((= (match-end 0) (length str))
18436 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18437 ((= (match-end 0) (- (length str) 5))
18438 (throw 'exit nil))
18439 (t (setq start (match-end 0))))))
18440 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18441 (goto-char pos)
18442 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18443 (and (match-beginning 2) (throw 'exit nil))
18444 ;; count $$
18445 (while (re-search-backward "\\$\\$" lim t)
18446 (setq dd-on (not dd-on)))
18447 (goto-char pos)
18448 (when dd-on (cons "$$" m))))))
18450 (defun org-inside-latex-macro-p ()
18451 "Is point inside a LaTeX macro or its arguments?"
18452 (save-match-data
18453 (org-in-regexp
18454 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18456 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18457 "Build an overlay between BEG and END using IMAGE file.
18458 Argument IMAGETYPE is the extension of the displayed image,
18459 as a string. It defaults to \"png\"."
18460 (let ((ov (make-overlay beg end))
18461 (imagetype (or (intern imagetype) 'png)))
18462 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18463 (overlay-put ov 'evaporate t)
18464 (overlay-put ov
18465 'modification-hooks
18466 (list (lambda (o _flag _beg _end &optional _l)
18467 (delete-overlay o))))
18468 (overlay-put ov
18469 'display
18470 (list 'image :type imagetype :file image :ascent 'center))))
18472 (defun org--list-latex-overlays (&optional beg end)
18473 "List all Org LaTeX overlays in current buffer.
18474 Limit to overlays between BEG and END when those are provided."
18475 (cl-remove-if-not
18476 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18477 (overlays-in (or beg (point-min)) (or end (point-max)))))
18479 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18480 "Remove all overlays with LaTeX fragment images in current buffer.
18481 When optional arguments BEG and END are non-nil, remove all
18482 overlays between them instead. Return a non-nil value when some
18483 overlays were removed, nil otherwise."
18484 (let ((overlays (org--list-latex-overlays beg end)))
18485 (mapc #'delete-overlay overlays)
18486 overlays))
18488 (defun org-toggle-latex-fragment (&optional arg)
18489 "Preview the LaTeX fragment at point, or all locally or globally.
18491 If the cursor is on a LaTeX fragment, create the image and overlay
18492 it over the source code, if there is none. Remove it otherwise.
18493 If there is no fragment at point, display all fragments in the
18494 current section.
18496 With prefix ARG, preview or clear image for all fragments in the
18497 current subtree or in the whole buffer when used before the first
18498 headline. With a prefix ARG `\\[universal-argument] \
18499 \\[universal-argument]' preview or clear images
18500 for all fragments in the buffer."
18501 (interactive "P")
18502 (when (display-graphic-p)
18503 (catch 'exit
18504 (save-excursion
18505 (let (beg end msg)
18506 (cond
18507 ((or (equal arg '(16))
18508 (and (equal arg '(4))
18509 (org-with-limited-levels (org-before-first-heading-p))))
18510 (if (org-remove-latex-fragment-image-overlays)
18511 (progn (message "LaTeX fragments images removed from buffer")
18512 (throw 'exit nil))
18513 (setq msg "Creating images for buffer...")))
18514 ((equal arg '(4))
18515 (org-with-limited-levels (org-back-to-heading t))
18516 (setq beg (point))
18517 (setq end (progn (org-end-of-subtree t) (point)))
18518 (if (org-remove-latex-fragment-image-overlays beg end)
18519 (progn
18520 (message "LaTeX fragment images removed from subtree")
18521 (throw 'exit nil))
18522 (setq msg "Creating images for subtree...")))
18523 ((let ((datum (org-element-context)))
18524 (when (memq (org-element-type datum)
18525 '(latex-environment latex-fragment))
18526 (setq beg (org-element-property :begin datum))
18527 (setq end (org-element-property :end datum))
18528 (if (org-remove-latex-fragment-image-overlays beg end)
18529 (progn (message "LaTeX fragment image removed")
18530 (throw 'exit nil))
18531 (setq msg "Creating image...")))))
18533 (org-with-limited-levels
18534 (setq beg (if (org-at-heading-p) (line-beginning-position)
18535 (outline-previous-heading)
18536 (point)))
18537 (setq end (progn (outline-next-heading) (point)))
18538 (if (org-remove-latex-fragment-image-overlays beg end)
18539 (progn
18540 (message "LaTeX fragment images removed from section")
18541 (throw 'exit nil))
18542 (setq msg "Creating images for section...")))))
18543 (let ((file (buffer-file-name (buffer-base-buffer))))
18544 (org-format-latex
18545 (concat org-preview-latex-image-directory "org-ltximg")
18546 beg end
18547 ;; Emacs cannot overlay images from remote hosts. Create
18548 ;; it in `temporary-file-directory' instead.
18549 (if (or (not file) (file-remote-p file))
18550 temporary-file-directory
18551 default-directory)
18552 'overlays msg 'forbuffer org-preview-latex-default-process))
18553 (message (concat msg "done")))))))
18555 (defun org-format-latex
18556 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18557 "Replace LaTeX fragments with links to an image.
18559 The function takes care of creating the replacement image.
18561 Only consider fragments between BEG and END when those are
18562 provided.
18564 When optional argument OVERLAYS is non-nil, display the image on
18565 top of the fragment instead of replacing it.
18567 PROCESSING-TYPE is the conversion method to use, as a symbol.
18569 Some of the options can be changed using the variable
18570 `org-format-latex-options', which see."
18571 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18572 (unless (eq processing-type 'verbatim)
18573 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18574 (cnt 0)
18575 checkdir-flag)
18576 (goto-char (or beg (point-min)))
18577 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18578 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18579 (overlay-recenter (or end (point-max))))
18580 (while (re-search-forward math-regexp end t)
18581 (unless (and overlays
18582 (eq (get-char-property (point) 'org-overlay-type)
18583 'org-latex-overlay))
18584 (let* ((context (org-element-context))
18585 (type (org-element-type context)))
18586 (when (memq type '(latex-environment latex-fragment))
18587 (let ((block-type (eq type 'latex-environment))
18588 (value (org-element-property :value context))
18589 (beg (org-element-property :begin context))
18590 (end (save-excursion
18591 (goto-char (org-element-property :end context))
18592 (skip-chars-backward " \r\t\n")
18593 (point))))
18594 (cond
18595 ((eq processing-type 'mathjax)
18596 ;; Prepare for MathJax processing.
18597 (if (not (string-match "\\`\\$\\$?" value))
18598 (goto-char end)
18599 (delete-region beg end)
18600 (if (string= (match-string 0 value) "$$")
18601 (insert "\\[" (substring value 2 -2) "\\]")
18602 (insert "\\(" (substring value 1 -1) "\\)"))))
18603 ((assq processing-type org-preview-latex-process-alist)
18604 ;; Process to an image.
18605 (cl-incf cnt)
18606 (goto-char beg)
18607 (let* ((processing-info
18608 (cdr (assq processing-type org-preview-latex-process-alist)))
18609 (face (face-at-point))
18610 ;; Get the colors from the face at point.
18612 (let ((color (plist-get org-format-latex-options
18613 :foreground)))
18614 (if (and forbuffer (eq color 'auto))
18615 (face-attribute face :foreground nil 'default)
18616 color)))
18618 (let ((color (plist-get org-format-latex-options
18619 :background)))
18620 (if (and forbuffer (eq color 'auto))
18621 (face-attribute face :background nil 'default)
18622 color)))
18623 (hash (sha1 (prin1-to-string
18624 (list org-format-latex-header
18625 org-latex-default-packages-alist
18626 org-latex-packages-alist
18627 org-format-latex-options
18628 forbuffer value fg bg))))
18629 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18630 (absprefix (expand-file-name prefix dir))
18631 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18632 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18633 (sep (and block-type "\n\n"))
18634 (link (concat sep "[[file:" linkfile "]]" sep))
18635 (options
18636 (org-combine-plists
18637 org-format-latex-options
18638 `(:foreground ,fg :background ,bg))))
18639 (when msg (message msg cnt))
18640 (unless checkdir-flag ; Ensure the directory exists.
18641 (setq checkdir-flag t)
18642 (let ((todir (file-name-directory absprefix)))
18643 (unless (file-directory-p todir)
18644 (make-directory todir t))))
18645 (unless (file-exists-p movefile)
18646 (org-create-formula-image
18647 value movefile options forbuffer processing-type))
18648 (if overlays
18649 (progn
18650 (dolist (o (overlays-in beg end))
18651 (when (eq (overlay-get o 'org-overlay-type)
18652 'org-latex-overlay)
18653 (delete-overlay o)))
18654 (org--format-latex-make-overlay beg end movefile imagetype)
18655 (goto-char end))
18656 (delete-region beg end)
18657 (insert
18658 (org-add-props link
18659 (list 'org-latex-src
18660 (replace-regexp-in-string "\"" "" value)
18661 'org-latex-src-embed-type
18662 (if block-type 'paragraph 'character)))))))
18663 ((eq processing-type 'mathml)
18664 ;; Process to MathML.
18665 (unless (org-format-latex-mathml-available-p)
18666 (user-error "LaTeX to MathML converter not configured"))
18667 (cl-incf cnt)
18668 (when msg (message msg cnt))
18669 (goto-char beg)
18670 (delete-region beg end)
18671 (insert (org-format-latex-as-mathml
18672 value block-type prefix dir)))
18674 (error "Unknown conversion process %s for LaTeX fragments"
18675 processing-type)))))))))))
18677 (defun org-create-math-formula (latex-frag &optional mathml-file)
18678 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18679 Use `org-latex-to-mathml-convert-command'. If the conversion is
18680 sucessful, return the portion between \"<math...> </math>\"
18681 elements otherwise return nil. When MATHML-FILE is specified,
18682 write the results in to that file. When invoked as an
18683 interactive command, prompt for LATEX-FRAG, with initial value
18684 set to the current active region and echo the results for user
18685 inspection."
18686 (interactive (list (let ((frag (when (org-region-active-p)
18687 (buffer-substring-no-properties
18688 (region-beginning) (region-end)))))
18689 (read-string "LaTeX Fragment: " frag nil frag))))
18690 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18691 (let* ((tmp-in-file
18692 (let ((file (file-relative-name
18693 (make-temp-name (expand-file-name "ltxmathml-in")))))
18694 (write-region latex-frag nil file)
18695 file))
18696 (tmp-out-file (file-relative-name
18697 (make-temp-name (expand-file-name "ltxmathml-out"))))
18698 (cmd (format-spec
18699 org-latex-to-mathml-convert-command
18700 `((?j . ,(and org-latex-to-mathml-jar-file
18701 (shell-quote-argument
18702 (expand-file-name
18703 org-latex-to-mathml-jar-file))))
18704 (?I . ,(shell-quote-argument tmp-in-file))
18705 (?i . ,latex-frag)
18706 (?o . ,(shell-quote-argument tmp-out-file)))))
18707 mathml shell-command-output)
18708 (when (called-interactively-p 'any)
18709 (unless (org-format-latex-mathml-available-p)
18710 (user-error "LaTeX to MathML converter not configured")))
18711 (message "Running %s" cmd)
18712 (setq shell-command-output (shell-command-to-string cmd))
18713 (setq mathml
18714 (when (file-readable-p tmp-out-file)
18715 (with-current-buffer (find-file-noselect tmp-out-file t)
18716 (goto-char (point-min))
18717 (when (re-search-forward
18718 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18719 (regexp-quote
18720 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18721 nil t)
18722 (prog1 (match-string 0) (kill-buffer))))))
18723 (cond
18724 (mathml
18725 (setq mathml
18726 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18727 (when mathml-file
18728 (write-region mathml nil mathml-file))
18729 (when (called-interactively-p 'any)
18730 (message mathml)))
18731 ((message "LaTeX to MathML conversion failed")
18732 (message shell-command-output)))
18733 (delete-file tmp-in-file)
18734 (when (file-exists-p tmp-out-file)
18735 (delete-file tmp-out-file))
18736 mathml))
18738 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18739 prefix &optional dir)
18740 "Use `org-create-math-formula' but check local cache first."
18741 (let* ((absprefix (expand-file-name prefix dir))
18742 (print-length nil) (print-level nil)
18743 (formula-id (concat
18744 "formula-"
18745 (sha1
18746 (prin1-to-string
18747 (list latex-frag
18748 org-latex-to-mathml-convert-command)))))
18749 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18750 (formula-cache-dir (file-name-directory formula-cache)))
18752 (unless (file-directory-p formula-cache-dir)
18753 (make-directory formula-cache-dir t))
18755 (unless (file-exists-p formula-cache)
18756 (org-create-math-formula latex-frag formula-cache))
18758 (if (file-exists-p formula-cache)
18759 ;; Successful conversion. Return the link to MathML file.
18760 (org-add-props
18761 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18762 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18763 'org-latex-src-embed-type (if latex-frag-type
18764 'paragraph 'character)))
18765 ;; Failed conversion. Return the LaTeX fragment verbatim
18766 latex-frag)))
18768 (defun org--get-display-dpi ()
18769 "Get the DPI of the display.
18770 The function assumes that the display has the same pixel width in
18771 the horizontal and vertical directions."
18772 (if (display-graphic-p)
18773 (round (/ (display-pixel-height)
18774 (/ (display-mm-height) 25.4)))
18775 (error "Attempt to calculate the dpi of a non-graphic display")))
18777 (defun org-create-formula-image
18778 (string tofile options buffer &optional processing-type)
18779 "Create an image from LaTeX source using external processes.
18781 The LaTeX STRING is saved to a temporary LaTeX file, then
18782 converted to an image file by process PROCESSING-TYPE defined in
18783 `org-preview-latex-process-alist'. A nil value defaults to
18784 `org-preview-latex-default-process'.
18786 The generated image file is eventually moved to TOFILE.
18788 The OPTIONS argument controls the size, foreground color and
18789 background color of the generated image.
18791 When BUFFER non-nil, this function is used for LaTeX previewing.
18792 Otherwise, it is used to deal with LaTeX snippets showed in
18793 a HTML file."
18794 (let* ((processing-type (or processing-type
18795 org-preview-latex-default-process))
18796 (processing-info
18797 (cdr (assq processing-type org-preview-latex-process-alist)))
18798 (programs (plist-get processing-info :programs))
18799 (error-message (or (plist-get processing-info :message) ""))
18800 (use-xcolor (plist-get processing-info :use-xcolor))
18801 (image-input-type (plist-get processing-info :image-input-type))
18802 (image-output-type (plist-get processing-info :image-output-type))
18803 (post-clean (or (plist-get processing-info :post-clean)
18804 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18805 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18806 (latex-header
18807 (or (plist-get processing-info :latex-header)
18808 (org-latex-make-preamble
18809 (org-export-get-environment (org-export-get-backend 'latex))
18810 org-format-latex-header
18811 'snippet)))
18812 (latex-compiler (plist-get processing-info :latex-compiler))
18813 (image-converter (plist-get processing-info :image-converter))
18814 (tmpdir temporary-file-directory)
18815 (texfilebase (make-temp-name
18816 (expand-file-name "orgtex" tmpdir)))
18817 (texfile (concat texfilebase ".tex"))
18818 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18819 '(1.0 . 1.0)))
18820 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18821 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18822 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18823 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18824 "Black"))
18825 (bg (or (plist-get options (if buffer :background :html-background))
18826 "Transparent"))
18827 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18828 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18829 (dolist (program programs)
18830 (org-check-external-command program error-message))
18831 (if use-xcolor
18832 (progn (if (eq fg 'default)
18833 (setq fg (org-latex-color :foreground))
18834 (setq fg (org-latex-color-format fg)))
18835 (if (eq bg 'default)
18836 (setq bg (org-latex-color :background))
18837 (setq bg (org-latex-color-format
18838 (if (string= bg "Transparent") "white" bg))))
18839 (with-temp-file texfile
18840 (insert latex-header)
18841 (insert "\n\\begin{document}\n"
18842 "\\definecolor{fg}{rgb}{" fg "}\n"
18843 "\\definecolor{bg}{rgb}{" bg "}\n"
18844 "\n\\pagecolor{bg}\n"
18845 "\n{\\color{fg}\n"
18846 string
18847 "\n}\n"
18848 "\n\\end{document}\n")))
18849 (if (eq fg 'default)
18850 (setq fg (org-dvipng-color :foreground))
18851 (unless (string= fg "Transparent")
18852 (setq fg (org-dvipng-color-format fg))))
18853 (if (eq bg 'default)
18854 (setq bg (org-dvipng-color :background))
18855 (unless (string= bg "Transparent")
18856 (setq bg (org-dvipng-color-format bg))))
18857 (with-temp-file texfile
18858 (insert latex-header)
18859 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18861 (let* ((err-msg (format "Please adjust `%s' part of \
18862 `org-preview-latex-process-alist'."
18863 processing-type))
18864 (image-input-file
18865 (org-compile-file
18866 texfile latex-compiler image-input-type err-msg log-buf))
18867 (image-output-file
18868 (org-compile-file
18869 image-input-file image-converter image-output-type err-msg log-buf
18870 `((?F . ,(shell-quote-argument fg))
18871 (?B . ,(shell-quote-argument bg))
18872 (?D . ,(shell-quote-argument (format "%s" dpi)))
18873 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18874 (copy-file image-output-file tofile 'replace)
18875 (dolist (e post-clean)
18876 (when (file-exists-p (concat texfilebase e))
18877 (delete-file (concat texfilebase e))))
18878 image-output-file)))
18880 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18881 "Fill a LaTeX header template TPL.
18882 In the template, the following place holders will be recognized:
18884 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18885 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18886 [PACKAGES] \\usepackage statements for PKG
18887 [NO-PACKAGES] do not include PKG
18888 [EXTRA] the string EXTRA
18889 [NO-EXTRA] do not include EXTRA
18891 For backward compatibility, if both the positive and the negative place
18892 holder is missing, the positive one (without the \"NO-\") will be
18893 assumed to be present at the end of the template.
18894 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18895 EXTRA is a string.
18896 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18897 (let (rpl (end ""))
18898 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18899 (setq rpl (if (or (match-end 1) (not def-pkg))
18900 "" (org-latex-packages-to-string def-pkg snippets-p t))
18901 tpl (replace-match rpl t t tpl))
18902 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18904 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18905 (setq rpl (if (or (match-end 1) (not pkg))
18906 "" (org-latex-packages-to-string pkg snippets-p t))
18907 tpl (replace-match rpl t t tpl))
18908 (when pkg (setq end
18909 (concat end "\n"
18910 (org-latex-packages-to-string pkg snippets-p)))))
18912 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18913 (setq rpl (if (or (match-end 1) (not extra))
18914 "" (concat extra "\n"))
18915 tpl (replace-match rpl t t tpl))
18916 (when (and extra (string-match "\\S-" extra))
18917 (setq end (concat end "\n" extra))))
18919 (if (string-match "\\S-" end)
18920 (concat tpl "\n" end)
18921 tpl)))
18923 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18924 "Turn an alist of packages into a string with the \\usepackage macros."
18925 (setq pkg (mapconcat (lambda(p)
18926 (cond
18927 ((stringp p) p)
18928 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18929 (format "%% Package %s omitted" (cadr p)))
18930 ((equal "" (car p))
18931 (format "\\usepackage{%s}" (cadr p)))
18933 (format "\\usepackage[%s]{%s}"
18934 (car p) (cadr p)))))
18936 "\n"))
18937 (if newline (concat pkg "\n") pkg))
18939 (defun org-dvipng-color (attr)
18940 "Return a RGB color specification for dvipng."
18941 (org-dvipng-color-format (face-attribute 'default attr nil)))
18943 (defun org-dvipng-color-format (color-name)
18944 "Convert COLOR-NAME to a RGB color value for dvipng."
18945 (apply #'format "rgb %s %s %s"
18946 (mapcar 'org-normalize-color
18947 (color-values color-name))))
18949 (defun org-latex-color (attr)
18950 "Return a RGB color for the LaTeX color package."
18951 (org-latex-color-format (face-attribute 'default attr nil)))
18953 (defun org-latex-color-format (color-name)
18954 "Convert COLOR-NAME to a RGB color value."
18955 (apply #'format "%s,%s,%s"
18956 (mapcar 'org-normalize-color
18957 (color-values color-name))))
18959 (defun org-normalize-color (value)
18960 "Return string to be used as color value for an RGB component."
18961 (format "%g" (/ value 65535.0)))
18965 ;; Image display
18967 (defvar-local org-inline-image-overlays nil)
18969 (defun org-toggle-inline-images (&optional include-linked)
18970 "Toggle the display of inline images.
18971 INCLUDE-LINKED is passed to `org-display-inline-images'."
18972 (interactive "P")
18973 (if org-inline-image-overlays
18974 (progn
18975 (org-remove-inline-images)
18976 (when (called-interactively-p 'interactive)
18977 (message "Inline image display turned off")))
18978 (org-display-inline-images include-linked)
18979 (when (called-interactively-p 'interactive)
18980 (message (if org-inline-image-overlays
18981 (format "%d images displayed inline"
18982 (length org-inline-image-overlays))
18983 "No images to display inline")))))
18985 (defun org-redisplay-inline-images ()
18986 "Refresh the display of inline images."
18987 (interactive)
18988 (if (not org-inline-image-overlays)
18989 (org-toggle-inline-images)
18990 (org-toggle-inline-images)
18991 (org-toggle-inline-images)))
18993 (defun org-display-inline-images (&optional include-linked refresh beg end)
18994 "Display inline images.
18996 An inline image is a link which follows either of these
18997 conventions:
18999 1. Its path is a file with an extension matching return value
19000 from `image-file-name-regexp' and it has no contents.
19002 2. Its description consists in a single link of the previous
19003 type.
19005 When optional argument INCLUDE-LINKED is non-nil, also links with
19006 a text description part will be inlined. This can be nice for
19007 a quick look at those images, but it does not reflect what
19008 exported files will look like.
19010 When optional argument REFRESH is non-nil, refresh existing
19011 images between BEG and END. This will create new image displays
19012 only if necessary. BEG and END default to the buffer
19013 boundaries."
19014 (interactive "P")
19015 (when (display-graphic-p)
19016 (unless refresh
19017 (org-remove-inline-images)
19018 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19019 (org-with-wide-buffer
19020 (goto-char (or beg (point-min)))
19021 (let* ((case-fold-search t)
19022 (file-extension-re (image-file-name-regexp))
19023 (link-abbrevs (mapcar #'car
19024 (append org-link-abbrev-alist-local
19025 org-link-abbrev-alist)))
19026 ;; Check absolute, relative file names and explicit
19027 ;; "file:" links. Also check link abbreviations since
19028 ;; some might expand to "file" links.
19029 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19030 (if (not link-abbrevs) ""
19031 (format "\\|\\(?:%s:\\)"
19032 (regexp-opt link-abbrevs))))))
19033 (while (re-search-forward file-types-re end t)
19034 (let ((link (save-match-data (org-element-context))))
19035 ;; Check if we're at an inline image, i.e., an image file
19036 ;; link without a description (unless INCLUDE-LINKED is
19037 ;; non-nil).
19038 (when (and (equal "file" (org-element-property :type link))
19039 (or include-linked
19040 (null (org-element-contents link)))
19041 (string-match-p file-extension-re
19042 (org-element-property :path link)))
19043 (let ((file (expand-file-name
19044 (org-link-unescape
19045 (org-element-property :path link)))))
19046 (when (file-exists-p file)
19047 (let ((width
19048 ;; Apply `org-image-actual-width' specifications.
19049 (cond
19050 ((not (image-type-available-p 'imagemagick)) nil)
19051 ((eq org-image-actual-width t) nil)
19052 ((listp org-image-actual-width)
19054 ;; First try to find a width among
19055 ;; attributes associated to the paragraph
19056 ;; containing link.
19057 (let ((paragraph
19058 (let ((e link))
19059 (while (and (setq e (org-element-property
19060 :parent e))
19061 (not (eq (org-element-type e)
19062 'paragraph))))
19063 e)))
19064 (when paragraph
19065 (save-excursion
19066 (goto-char (org-element-property :begin paragraph))
19067 (when
19068 (re-search-forward
19069 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19070 (org-element-property
19071 :post-affiliated paragraph)
19073 (string-to-number (match-string 1))))))
19074 ;; Otherwise, fall-back to provided number.
19075 (car org-image-actual-width)))
19076 ((numberp org-image-actual-width)
19077 org-image-actual-width)))
19078 (old (get-char-property-and-overlay
19079 (org-element-property :begin link)
19080 'org-image-overlay)))
19081 (if (and (car-safe old) refresh)
19082 (image-refresh (overlay-get (cdr old) 'display))
19083 (let ((image (create-image file
19084 (and width 'imagemagick)
19086 :width width)))
19087 (when image
19088 (let ((ov (make-overlay
19089 (org-element-property :begin link)
19090 (progn
19091 (goto-char
19092 (org-element-property :end link))
19093 (skip-chars-backward " \t")
19094 (point)))))
19095 (overlay-put ov 'display image)
19096 (overlay-put ov 'face 'default)
19097 (overlay-put ov 'org-image-overlay t)
19098 (overlay-put
19099 ov 'modification-hooks
19100 (list 'org-display-inline-remove-overlay))
19101 (push ov org-inline-image-overlays)))))))))))))))
19103 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19104 "Remove inline-display overlay if a corresponding region is modified."
19105 (let ((inhibit-modification-hooks t))
19106 (when (and ov after)
19107 (delete ov org-inline-image-overlays)
19108 (delete-overlay ov))))
19110 (defun org-remove-inline-images ()
19111 "Remove inline display of images."
19112 (interactive)
19113 (mapc #'delete-overlay org-inline-image-overlays)
19114 (setq org-inline-image-overlays nil))
19116 ;;;; Key bindings
19118 (defun org-remap (map &rest commands)
19119 "In MAP, remap the functions given in COMMANDS.
19120 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19121 (let (new old)
19122 (while commands
19123 (setq old (pop commands) new (pop commands))
19124 (org-defkey map (vector 'remap old) new))))
19126 ;; Outline functions from `outline-mode-prefix-map'
19127 ;; that can be remapped in Org:
19128 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19129 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19130 (define-key org-mode-map [remap outline-forward-same-level]
19131 'org-forward-heading-same-level)
19132 (define-key org-mode-map [remap outline-backward-same-level]
19133 'org-backward-heading-same-level)
19134 (define-key org-mode-map [remap outline-show-branches]
19135 'org-kill-note-or-show-branches)
19136 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19137 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19138 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19139 (define-key org-mode-map [remap outline-next-visible-heading]
19140 'org-next-visible-heading)
19141 (define-key org-mode-map [remap outline-previous-visible-heading]
19142 'org-previous-visible-heading)
19143 (define-key org-mode-map [remap show-children] 'org-show-children)
19145 ;; Outline functions from `outline-mode-prefix-map' that can not
19146 ;; be remapped in Org:
19148 ;; - the column "key binding" shows whether the Outline function is still
19149 ;; available in Org mode on the same key that it has been bound to in
19150 ;; Outline mode:
19151 ;; - "overridden": key used for a different functionality in Org mode
19152 ;; - else: key still bound to the same Outline function in Org mode
19154 ;; | Outline function | key binding | Org replacement |
19155 ;; |------------------------------------+-------------+--------------------------|
19156 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19157 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19158 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19159 ;; | `show-entry' | overridden | no replacement |
19160 ;; | `show-branches' | `C-c C-k' | still same function |
19161 ;; | `show-subtree' | overridden | visibility cycling |
19162 ;; | `show-all' | overridden | no replacement |
19163 ;; | `hide-subtree' | overridden | visibility cycling |
19164 ;; | `hide-body' | overridden | no replacement |
19165 ;; | `hide-entry' | overridden | visibility cycling |
19166 ;; | `hide-leaves' | overridden | no replacement |
19167 ;; | `hide-sublevels' | overridden | no replacement |
19168 ;; | `hide-other' | overridden | no replacement |
19170 ;; Make `C-c C-x' a prefix key
19171 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19173 ;; TAB key with modifiers
19174 (org-defkey org-mode-map "\C-i" 'org-cycle)
19175 (org-defkey org-mode-map [(tab)] 'org-cycle)
19176 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19177 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19179 ;; The following line is necessary under Suse GNU/Linux
19180 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19181 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19182 (define-key org-mode-map [backtab] 'org-shifttab)
19184 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19185 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19186 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19188 ;; Cursor keys with modifiers
19189 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19190 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19191 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19192 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19194 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19195 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19196 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19197 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19198 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19199 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19201 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19202 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19203 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19204 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19206 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19207 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19208 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19209 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19211 ;; Babel keys
19212 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19213 (dolist (pair org-babel-key-bindings)
19214 (define-key org-babel-map (car pair) (cdr pair)))
19216 ;;; Extra keys for tty access.
19217 ;; We only set them when really needed because otherwise the
19218 ;; menus don't show the simple keys
19220 (when (or org-use-extra-keys (not window-system))
19221 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19222 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19223 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19224 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19225 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19226 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19227 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19228 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19229 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19230 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19231 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19232 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19233 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19234 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19235 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19236 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19237 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19238 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19239 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19240 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19241 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19242 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19243 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19244 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19245 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19246 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19247 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19248 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19250 ;; All the other keys
19251 (org-remap org-mode-map
19252 'self-insert-command 'org-self-insert-command
19253 'delete-char 'org-delete-char
19254 'delete-backward-char 'org-delete-backward-char)
19255 (org-defkey org-mode-map "|" 'org-force-self-insert)
19257 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19258 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19259 (if (boundp 'narrow-map)
19260 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19261 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19262 (if (boundp 'narrow-map)
19263 (org-defkey narrow-map "b" 'org-narrow-to-block)
19264 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19265 (if (boundp 'narrow-map)
19266 (org-defkey narrow-map "e" 'org-narrow-to-element)
19267 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19268 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19269 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19270 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19271 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19272 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19273 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19274 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19275 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19276 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19277 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19278 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19279 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19280 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19281 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19282 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19283 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19284 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19285 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19286 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19287 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19288 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19289 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19290 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19291 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19292 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19293 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19294 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19295 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19296 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19297 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19298 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19299 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19300 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19301 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19302 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19303 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19304 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19305 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19306 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19307 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19308 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19309 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19310 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19311 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19312 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19313 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19314 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19315 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19316 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19317 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19318 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19319 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19320 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19321 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19322 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19323 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19324 (org-defkey org-mode-map "\C-c^" 'org-sort)
19325 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19326 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19327 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19328 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19329 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19330 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19331 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19332 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19333 (org-defkey org-mode-map "\C-m" 'org-return)
19334 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19335 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19336 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19337 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19338 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19339 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19340 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19341 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19342 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19343 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19344 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19345 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19346 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19347 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19348 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19349 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19350 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19351 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19352 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19353 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19354 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19355 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19356 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19357 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19358 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19360 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19361 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19362 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19364 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19365 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19366 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19367 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19368 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19369 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19370 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19371 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19372 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19373 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19374 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19375 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19376 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19377 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19378 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19379 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19380 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19381 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19382 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19383 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19384 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19385 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19386 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19388 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19389 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19390 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19391 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19392 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19394 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19396 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19398 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19399 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19401 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19404 (defconst org-speed-commands-default
19406 ("Outline Navigation")
19407 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19408 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19409 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19410 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19411 ("F" . org-next-block)
19412 ("B" . org-previous-block)
19413 ("u" . (org-speed-move-safe 'outline-up-heading))
19414 ("j" . org-goto)
19415 ("g" . (org-refile t))
19416 ("Outline Visibility")
19417 ("c" . org-cycle)
19418 ("C" . org-shifttab)
19419 (" " . org-display-outline-path)
19420 ("s" . org-narrow-to-subtree)
19421 ("=" . org-columns)
19422 ("Outline Structure Editing")
19423 ("U" . org-metaup)
19424 ("D" . org-metadown)
19425 ("r" . org-metaright)
19426 ("l" . org-metaleft)
19427 ("R" . org-shiftmetaright)
19428 ("L" . org-shiftmetaleft)
19429 ("i" . (progn (forward-char 1) (call-interactively
19430 'org-insert-heading-respect-content)))
19431 ("^" . org-sort)
19432 ("w" . org-refile)
19433 ("a" . org-archive-subtree-default-with-confirmation)
19434 ("@" . org-mark-subtree)
19435 ("#" . org-toggle-comment)
19436 ("Clock Commands")
19437 ("I" . org-clock-in)
19438 ("O" . org-clock-out)
19439 ("Meta Data Editing")
19440 ("t" . org-todo)
19441 ("," . (org-priority))
19442 ("0" . (org-priority ?\ ))
19443 ("1" . (org-priority ?A))
19444 ("2" . (org-priority ?B))
19445 ("3" . (org-priority ?C))
19446 (":" . org-set-tags-command)
19447 ("e" . org-set-effort)
19448 ("E" . org-inc-effort)
19449 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19450 (org-entry-put (point) "APPT_WARNTIME" m)))
19451 ("Agenda Views etc")
19452 ("v" . org-agenda)
19453 ("/" . org-sparse-tree)
19454 ("Misc")
19455 ("o" . org-open-at-point)
19456 ("?" . org-speed-command-help)
19457 ("<" . (org-agenda-set-restriction-lock 'subtree))
19458 (">" . (org-agenda-remove-restriction-lock))
19460 "The default speed commands.")
19462 (defun org-print-speed-command (e)
19463 (if (> (length (car e)) 1)
19464 (progn
19465 (princ "\n")
19466 (princ (car e))
19467 (princ "\n")
19468 (princ (make-string (length (car e)) ?-))
19469 (princ "\n"))
19470 (princ (car e))
19471 (princ " ")
19472 (if (symbolp (cdr e))
19473 (princ (symbol-name (cdr e)))
19474 (prin1 (cdr e)))
19475 (princ "\n")))
19477 (defun org-speed-command-help ()
19478 "Show the available speed commands."
19479 (interactive)
19480 (if (not org-use-speed-commands)
19481 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19482 (with-output-to-temp-buffer "*Help*"
19483 (princ "User-defined Speed commands\n===========================\n")
19484 (mapc #'org-print-speed-command org-speed-commands-user)
19485 (princ "\n")
19486 (princ "Built-in Speed commands\n=======================\n")
19487 (mapc #'org-print-speed-command org-speed-commands-default))
19488 (with-current-buffer "*Help*"
19489 (setq truncate-lines t))))
19491 (defun org-speed-move-safe (cmd)
19492 "Execute CMD, but make sure that the cursor always ends up in a headline.
19493 If not, return to the original position and throw an error."
19494 (interactive)
19495 (let ((pos (point)))
19496 (call-interactively cmd)
19497 (unless (and (bolp) (org-at-heading-p))
19498 (goto-char pos)
19499 (error "Boundary reached while executing %s" cmd))))
19501 (defvar org-self-insert-command-undo-counter 0)
19503 (defvar org-table-auto-blank-field) ; defined in org-table.el
19504 (defvar org-speed-command nil)
19506 (defun org-speed-command-activate (keys)
19507 "Hook for activating single-letter speed commands.
19508 `org-speed-commands-default' specifies a minimal command set.
19509 Use `org-speed-commands-user' for further customization."
19510 (when (or (and (bolp) (looking-at org-outline-regexp))
19511 (and (functionp org-use-speed-commands)
19512 (funcall org-use-speed-commands)))
19513 (cdr (assoc keys (append org-speed-commands-user
19514 org-speed-commands-default)))))
19516 (defun org-babel-speed-command-activate (keys)
19517 "Hook for activating single-letter code block commands."
19518 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19519 (cdr (assoc keys org-babel-key-bindings))))
19521 (defcustom org-speed-command-hook
19522 '(org-speed-command-activate org-babel-speed-command-activate)
19523 "Hook for activating speed commands at strategic locations.
19524 Hook functions are called in sequence until a valid handler is
19525 found.
19527 Each hook takes a single argument, a user-pressed command key
19528 which is also a `self-insert-command' from the global map.
19530 Within the hook, examine the cursor position and the command key
19531 and return nil or a valid handler as appropriate. Handler could
19532 be one of an interactive command, a function, or a form.
19534 Set `org-use-speed-commands' to non-nil value to enable this
19535 hook. The default setting is `org-speed-command-activate'."
19536 :group 'org-structure
19537 :version "24.1"
19538 :type 'hook)
19540 (defun org-self-insert-command (N)
19541 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19542 If the cursor is in a table looking at whitespace, the whitespace is
19543 overwritten, and the table is not marked as requiring realignment."
19544 (interactive "p")
19545 (org-check-before-invisible-edit 'insert)
19546 (cond
19547 ((and org-use-speed-commands
19548 (let ((kv (this-command-keys-vector)))
19549 (setq org-speed-command
19550 (run-hook-with-args-until-success
19551 'org-speed-command-hook
19552 (make-string 1 (aref kv (1- (length kv))))))))
19553 (cond
19554 ((commandp org-speed-command)
19555 (setq this-command org-speed-command)
19556 (call-interactively org-speed-command))
19557 ((functionp org-speed-command)
19558 (funcall org-speed-command))
19559 ((and org-speed-command (listp org-speed-command))
19560 (eval org-speed-command))
19561 (t (let (org-use-speed-commands)
19562 (call-interactively 'org-self-insert-command)))))
19563 ((and
19564 (org-at-table-p)
19565 (eq N 1)
19566 (not (org-region-active-p))
19567 (progn
19568 ;; Check if we blank the field, and if that triggers align.
19569 (and (featurep 'org-table) org-table-auto-blank-field
19570 (memq last-command
19571 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19572 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19573 ;; Got extra space, this field does not determine
19574 ;; column width.
19575 (let (org-table-may-need-update) (org-table-blank-field))
19576 ;; No extra space, this field may determine column
19577 ;; width.
19578 (org-table-blank-field)))
19580 (looking-at "[^|\n]* \\( \\)|"))
19581 ;; There is room for insertion without re-aligning the table.
19582 (delete-region (match-beginning 1) (match-end 1))
19583 (self-insert-command N))
19585 (setq org-table-may-need-update t)
19586 (self-insert-command N)
19587 (org-fix-tags-on-the-fly)
19588 (when org-self-insert-cluster-for-undo
19589 (if (not (eq last-command 'org-self-insert-command))
19590 (setq org-self-insert-command-undo-counter 1)
19591 (if (>= org-self-insert-command-undo-counter 20)
19592 (setq org-self-insert-command-undo-counter 1)
19593 (and (> org-self-insert-command-undo-counter 0)
19594 buffer-undo-list (listp buffer-undo-list)
19595 (not (cadr buffer-undo-list)) ; remove nil entry
19596 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19597 (setq org-self-insert-command-undo-counter
19598 (1+ org-self-insert-command-undo-counter))))))))
19600 (defun org-check-before-invisible-edit (kind)
19601 "Check is editing if kind KIND would be dangerous with invisible text around.
19602 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19603 ;; First, try to get out of here as quickly as possible, to reduce overhead
19604 (when (and org-catch-invisible-edits
19605 (or (not (boundp 'visible-mode)) (not visible-mode))
19606 (or (get-char-property (point) 'invisible)
19607 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19608 ;; OK, we need to take a closer look. Do not consider
19609 ;; invisibility obtained through text properties (e.g., link
19610 ;; fontification), as it cannot be toggled.
19611 (let* ((invisible-at-point
19612 (pcase (get-char-property-and-overlay (point) 'invisible)
19613 (`(,_ . ,(and (pred overlayp) o)) o)))
19614 ;; Assume that point cannot land in the middle of an
19615 ;; overlay, or between two overlays.
19616 (invisible-before-point
19617 (and (not invisible-at-point)
19618 (not (bobp))
19619 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19620 (`(,_ . ,(and (pred overlayp) o)) o))))
19621 (border-and-ok-direction
19623 ;; Check if we are acting predictably before invisible
19624 ;; text.
19625 (and invisible-at-point
19626 (memq kind '(insert delete-backward)))
19627 ;; Check if we are acting predictably after invisible text
19628 ;; This works not well, and I have turned it off. It seems
19629 ;; better to always show and stop after invisible text.
19630 ;; (and (not invisible-at-point) invisible-before-point
19631 ;; (memq kind '(insert delete)))
19633 (when (or invisible-at-point invisible-before-point)
19634 (when (eq org-catch-invisible-edits 'error)
19635 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19636 (if (and org-custom-properties-overlays
19637 (y-or-n-p "Display invisible properties in this buffer? "))
19638 (org-toggle-custom-properties-visibility)
19639 ;; Make the area visible
19640 (save-excursion
19641 (when invisible-before-point
19642 (goto-char
19643 (previous-single-char-property-change (point) 'invisible)))
19644 ;; Remove whatever overlay is currently making yet-to-be
19645 ;; edited text invisible. Also remove nested invisibility
19646 ;; related overlays.
19647 (delete-overlay (or invisible-at-point invisible-before-point))
19648 (let ((origin (if invisible-at-point (point) (1- (point)))))
19649 (while (pcase (get-char-property-and-overlay origin 'invisible)
19650 (`(,_ . ,(and (pred overlayp) o))
19651 (delete-overlay o)
19652 t)))))
19653 (cond
19654 ((eq org-catch-invisible-edits 'show)
19655 ;; That's it, we do the edit after showing
19656 (message
19657 "Unfolding invisible region around point before editing")
19658 (sit-for 1))
19659 ((and (eq org-catch-invisible-edits 'smart)
19660 border-and-ok-direction)
19661 (message "Unfolding invisible region around point before editing"))
19663 ;; Don't do the edit, make the user repeat it in full visibility
19664 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19666 (defun org-fix-tags-on-the-fly ()
19667 "Align tags in headline at point.
19668 Unlike to `org-set-tags', it ignores region and sorting."
19669 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19670 (org-at-heading-p))
19671 (let ((org-ignore-region t)
19672 (org-tags-sort-function nil))
19673 (org-set-tags nil t))))
19675 (defun org-delete-backward-char (N)
19676 "Like `delete-backward-char', insert whitespace at field end in tables.
19677 When deleting backwards, in tables this function will insert whitespace in
19678 front of the next \"|\" separator, to keep the table aligned. The table will
19679 still be marked for re-alignment if the field did fill the entire column,
19680 because, in this case the deletion might narrow the column."
19681 (interactive "p")
19682 (save-match-data
19683 (org-check-before-invisible-edit 'delete-backward)
19684 (if (and (org-at-table-p)
19685 (eq N 1)
19686 (not (org-region-active-p))
19687 (string-match "|" (buffer-substring (point-at-bol) (point)))
19688 (looking-at ".*?|"))
19689 (let ((pos (point))
19690 (noalign (looking-at "[^|\n\r]* |"))
19691 (c org-table-may-need-update))
19692 (backward-delete-char N)
19693 (unless overwrite-mode
19694 (skip-chars-forward "^|")
19695 (insert " ")
19696 (goto-char (1- pos)))
19697 ;; noalign: if there were two spaces at the end, this field
19698 ;; does not determine the width of the column.
19699 (when noalign (setq org-table-may-need-update c)))
19700 (backward-delete-char N)
19701 (org-fix-tags-on-the-fly))))
19703 (defun org-delete-char (N)
19704 "Like `delete-char', but insert whitespace at field end in tables.
19705 When deleting characters, in tables this function will insert whitespace in
19706 front of the next \"|\" separator, to keep the table aligned. The table will
19707 still be marked for re-alignment if the field did fill the entire column,
19708 because, in this case the deletion might narrow the column."
19709 (interactive "p")
19710 (save-match-data
19711 (org-check-before-invisible-edit 'delete)
19712 (if (and (org-at-table-p)
19713 (not (bolp))
19714 (not (= (char-after) ?|))
19715 (eq N 1))
19716 (if (looking-at ".*?|")
19717 (let ((pos (point))
19718 (noalign (looking-at "[^|\n\r]* |"))
19719 (c org-table-may-need-update))
19720 (replace-match
19721 (concat (substring (match-string 0) 1 -1) " |") nil t)
19722 (goto-char pos)
19723 ;; noalign: if there were two spaces at the end, this field
19724 ;; does not determine the width of the column.
19725 (when noalign (setq org-table-may-need-update c)))
19726 (delete-char N))
19727 (delete-char N)
19728 (org-fix-tags-on-the-fly))))
19730 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19731 (put 'org-self-insert-command 'delete-selection
19732 (lambda ()
19733 (not (run-hook-with-args-until-success
19734 'self-insert-uses-region-functions))))
19735 (put 'orgtbl-self-insert-command 'delete-selection
19736 (lambda ()
19737 (not (run-hook-with-args-until-success
19738 'self-insert-uses-region-functions))))
19739 (put 'org-delete-char 'delete-selection 'supersede)
19740 (put 'org-delete-backward-char 'delete-selection 'supersede)
19741 (put 'org-yank 'delete-selection 'yank)
19743 ;; Make `flyspell-mode' delay after some commands
19744 (put 'org-self-insert-command 'flyspell-delayed t)
19745 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19746 (put 'org-delete-char 'flyspell-delayed t)
19747 (put 'org-delete-backward-char 'flyspell-delayed t)
19749 ;; Make pabbrev-mode expand after Org mode commands
19750 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19751 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19753 (defun org-transpose-words ()
19754 "Transpose words for Org.
19755 This uses the `org-mode-transpose-word-syntax-table' syntax
19756 table, which interprets characters in `org-emphasis-alist' as
19757 word constituents."
19758 (interactive)
19759 (with-syntax-table org-mode-transpose-word-syntax-table
19760 (call-interactively 'transpose-words)))
19761 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19763 (defvar org-ctrl-c-ctrl-c-hook nil
19764 "Hook for functions attaching themselves to `C-c C-c'.
19766 This can be used to add additional functionality to the C-c C-c
19767 key which executes context-dependent commands. This hook is run
19768 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19769 run after the last test.
19771 Each function will be called with no arguments. The function
19772 must check if the context is appropriate for it to act. If yes,
19773 it should do its thing and then return a non-nil value. If the
19774 context is wrong, just do nothing and return nil.")
19776 (defvar org-ctrl-c-ctrl-c-final-hook nil
19777 "Hook for functions attaching themselves to `C-c C-c'.
19779 This can be used to add additional functionality to the C-c C-c
19780 key which executes context-dependent commands. This hook is run
19781 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19782 before the first test.
19784 Each function will be called with no arguments. The function
19785 must check if the context is appropriate for it to act. If yes,
19786 it should do its thing and then return a non-nil value. If the
19787 context is wrong, just do nothing and return nil.")
19789 (defvar org-tab-first-hook nil
19790 "Hook for functions to attach themselves to TAB.
19791 See `org-ctrl-c-ctrl-c-hook' for more information.
19792 This hook runs as the first action when TAB is pressed, even before
19793 `org-cycle' messes around with the `outline-regexp' to cater for
19794 inline tasks and plain list item folding.
19795 If any function in this hook returns t, any other actions that
19796 would have been caused by TAB (such as table field motion or visibility
19797 cycling) will not occur.")
19799 (defvar org-tab-after-check-for-table-hook nil
19800 "Hook for functions to attach themselves to TAB.
19801 See `org-ctrl-c-ctrl-c-hook' for more information.
19802 This hook runs after it has been established that the cursor is not in a
19803 table, but before checking if the cursor is in a headline or if global cycling
19804 should be done.
19805 If any function in this hook returns t, not other actions like visibility
19806 cycling will be done.")
19808 (defvar org-tab-after-check-for-cycling-hook nil
19809 "Hook for functions to attach themselves to TAB.
19810 See `org-ctrl-c-ctrl-c-hook' for more information.
19811 This hook runs after it has been established that not table field motion and
19812 not visibility should be done because of current context. This is probably
19813 the place where a package like yasnippets can hook in.")
19815 (defvar org-tab-before-tab-emulation-hook nil
19816 "Hook for functions to attach themselves to TAB.
19817 See `org-ctrl-c-ctrl-c-hook' for more information.
19818 This hook runs after every other options for TAB have been exhausted, but
19819 before indentation and \t insertion takes place.")
19821 (defvar org-metaleft-hook nil
19822 "Hook for functions attaching themselves to `M-left'.
19823 See `org-ctrl-c-ctrl-c-hook' for more information.")
19824 (defvar org-metaright-hook nil
19825 "Hook for functions attaching themselves to `M-right'.
19826 See `org-ctrl-c-ctrl-c-hook' for more information.")
19827 (defvar org-metaup-hook nil
19828 "Hook for functions attaching themselves to `M-up'.
19829 See `org-ctrl-c-ctrl-c-hook' for more information.")
19830 (defvar org-metadown-hook nil
19831 "Hook for functions attaching themselves to `M-down'.
19832 See `org-ctrl-c-ctrl-c-hook' for more information.")
19833 (defvar org-shiftmetaleft-hook nil
19834 "Hook for functions attaching themselves to `M-S-left'.
19835 See `org-ctrl-c-ctrl-c-hook' for more information.")
19836 (defvar org-shiftmetaright-hook nil
19837 "Hook for functions attaching themselves to `M-S-right'.
19838 See `org-ctrl-c-ctrl-c-hook' for more information.")
19839 (defvar org-shiftmetaup-hook nil
19840 "Hook for functions attaching themselves to `M-S-up'.
19841 See `org-ctrl-c-ctrl-c-hook' for more information.")
19842 (defvar org-shiftmetadown-hook nil
19843 "Hook for functions attaching themselves to `M-S-down'.
19844 See `org-ctrl-c-ctrl-c-hook' for more information.")
19845 (defvar org-metareturn-hook nil
19846 "Hook for functions attaching themselves to `M-RET'.
19847 See `org-ctrl-c-ctrl-c-hook' for more information.")
19848 (defvar org-shiftup-hook nil
19849 "Hook for functions attaching themselves to `S-up'.
19850 See `org-ctrl-c-ctrl-c-hook' for more information.")
19851 (defvar org-shiftup-final-hook nil
19852 "Hook for functions attaching themselves to `S-up'.
19853 This one runs after all other options except shift-select have been excluded.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-shiftdown-hook nil
19856 "Hook for functions attaching themselves to `S-down'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-shiftdown-final-hook nil
19859 "Hook for functions attaching themselves to `S-down'.
19860 This one runs after all other options except shift-select have been excluded.
19861 See `org-ctrl-c-ctrl-c-hook' for more information.")
19862 (defvar org-shiftleft-hook nil
19863 "Hook for functions attaching themselves to `S-left'.
19864 See `org-ctrl-c-ctrl-c-hook' for more information.")
19865 (defvar org-shiftleft-final-hook nil
19866 "Hook for functions attaching themselves to `S-left'.
19867 This one runs after all other options except shift-select have been excluded.
19868 See `org-ctrl-c-ctrl-c-hook' for more information.")
19869 (defvar org-shiftright-hook nil
19870 "Hook for functions attaching themselves to `S-right'.
19871 See `org-ctrl-c-ctrl-c-hook' for more information.")
19872 (defvar org-shiftright-final-hook nil
19873 "Hook for functions attaching themselves to `S-right'.
19874 This one runs after all other options except shift-select have been excluded.
19875 See `org-ctrl-c-ctrl-c-hook' for more information.")
19877 (defun org-modifier-cursor-error ()
19878 "Throw an error, a modified cursor command was applied in wrong context."
19879 (user-error "This command is active in special context like tables, headlines or items"))
19881 (defun org-shiftselect-error ()
19882 "Throw an error because Shift-Cursor command was applied in wrong context."
19883 (if (and (boundp 'shift-select-mode) shift-select-mode)
19884 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19885 (user-error "This command works only in special context like headlines or timestamps")))
19887 (defun org-call-for-shift-select (cmd)
19888 (let ((this-command-keys-shift-translated t))
19889 (call-interactively cmd)))
19891 (defun org-shifttab (&optional arg)
19892 "Global visibility cycling or move to previous table field.
19893 Call `org-table-previous-field' within a table.
19894 When ARG is nil, cycle globally through visibility states.
19895 When ARG is a numeric prefix, show contents of this level."
19896 (interactive "P")
19897 (cond
19898 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19899 ((integerp arg)
19900 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19901 (message "Content view to level: %d" arg)
19902 (org-content (prefix-numeric-value arg2))
19903 (org-cycle-show-empty-lines t)
19904 (setq org-cycle-global-status 'overview)))
19905 (t (call-interactively 'org-global-cycle))))
19907 (defun org-shiftmetaleft ()
19908 "Promote subtree or delete table column.
19909 Calls `org-promote-subtree', `org-outdent-item-tree', or
19910 `org-table-delete-column', depending on context. See the
19911 individual commands for more information."
19912 (interactive)
19913 (cond
19914 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19915 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19916 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19917 ((if (not (org-region-active-p)) (org-at-item-p)
19918 (save-excursion (goto-char (region-beginning))
19919 (org-at-item-p)))
19920 (call-interactively 'org-outdent-item-tree))
19921 (t (org-modifier-cursor-error))))
19923 (defun org-shiftmetaright ()
19924 "Demote subtree or insert table column.
19925 Calls `org-demote-subtree', `org-indent-item-tree', or
19926 `org-table-insert-column', depending on context. See the
19927 individual commands for more information."
19928 (interactive)
19929 (cond
19930 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19931 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19932 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19933 ((if (not (org-region-active-p)) (org-at-item-p)
19934 (save-excursion (goto-char (region-beginning))
19935 (org-at-item-p)))
19936 (call-interactively 'org-indent-item-tree))
19937 (t (org-modifier-cursor-error))))
19939 (defun org-shiftmetaup (&optional _arg)
19940 "Drag the line at point up.
19941 In a table, kill the current row.
19942 On a clock timestamp, update the value of the timestamp like `S-<up>'
19943 but also adjust the previous clocked item in the clock history.
19944 Everywhere else, drag the line at point up."
19945 (interactive "P")
19946 (cond
19947 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19948 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19949 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19950 (call-interactively 'org-timestamp-up)))
19951 (t (call-interactively 'org-drag-line-backward))))
19953 (defun org-shiftmetadown (&optional _arg)
19954 "Drag the line at point down.
19955 In a table, insert an empty row at the current line.
19956 On a clock timestamp, update the value of the timestamp like `S-<down>'
19957 but also adjust the previous clocked item in the clock history.
19958 Everywhere else, drag the line at point down."
19959 (interactive "P")
19960 (cond
19961 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19962 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19963 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19964 (call-interactively 'org-timestamp-down)))
19965 (t (call-interactively 'org-drag-line-forward))))
19967 (defsubst org-hidden-tree-error ()
19968 (user-error
19969 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19971 (defun org-metaleft (&optional _arg)
19972 "Promote heading, list item at point or move table column left.
19974 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19975 depending on context. With no specific context, calls the Emacs
19976 default `backward-word'. See the individual commands for more
19977 information.
19979 This function runs the hook `org-metaleft-hook' as a first step,
19980 and returns at first non-nil value."
19981 (interactive "P")
19982 (cond
19983 ((run-hook-with-args-until-success 'org-metaleft-hook))
19984 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19985 ((org-with-limited-levels
19986 (or (org-at-heading-p)
19987 (and (org-region-active-p)
19988 (save-excursion
19989 (goto-char (region-beginning))
19990 (org-at-heading-p)))))
19991 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19992 (call-interactively 'org-do-promote))
19993 ;; At an inline task.
19994 ((org-at-heading-p)
19995 (call-interactively 'org-inlinetask-promote))
19996 ((or (org-at-item-p)
19997 (and (org-region-active-p)
19998 (save-excursion
19999 (goto-char (region-beginning))
20000 (org-at-item-p))))
20001 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20002 (call-interactively 'org-outdent-item))
20003 (t (call-interactively 'backward-word))))
20005 (defun org-metaright (&optional _arg)
20006 "Demote heading, list item at point or move table column right.
20008 In front of a drawer or a block keyword, indent it correctly.
20010 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20011 `org-indent-drawer' or `org-indent-block' depending on context.
20012 With no specific context, calls the Emacs default `forward-word'.
20013 See the individual commands for more information.
20015 This function runs the hook `org-metaright-hook' as a first step,
20016 and returns at first non-nil value."
20017 (interactive "P")
20018 (cond
20019 ((run-hook-with-args-until-success 'org-metaright-hook))
20020 ((org-at-table-p) (call-interactively 'org-table-move-column))
20021 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20022 ((org-at-block-p) (call-interactively 'org-indent-block))
20023 ((org-with-limited-levels
20024 (or (org-at-heading-p)
20025 (and (org-region-active-p)
20026 (save-excursion
20027 (goto-char (region-beginning))
20028 (org-at-heading-p)))))
20029 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20030 (call-interactively 'org-do-demote))
20031 ;; At an inline task.
20032 ((org-at-heading-p)
20033 (call-interactively 'org-inlinetask-demote))
20034 ((or (org-at-item-p)
20035 (and (org-region-active-p)
20036 (save-excursion
20037 (goto-char (region-beginning))
20038 (org-at-item-p))))
20039 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20040 (call-interactively 'org-indent-item))
20041 (t (call-interactively 'forward-word))))
20043 (defun org-check-for-hidden (what)
20044 "Check if there are hidden headlines/items in the current visual line.
20045 WHAT can be either `headlines' or `items'. If the current line is
20046 an outline or item heading and it has a folded subtree below it,
20047 this function returns t, nil otherwise."
20048 (let ((re (cond
20049 ((eq what 'headlines) org-outline-regexp-bol)
20050 ((eq what 'items) (org-item-beginning-re))
20051 (t (error "This should not happen"))))
20052 beg end)
20053 (save-excursion
20054 (catch 'exit
20055 (unless (org-region-active-p)
20056 (setq beg (point-at-bol))
20057 (beginning-of-line 2)
20058 (while (and (not (eobp)) ;; this is like `next-line'
20059 (get-char-property (1- (point)) 'invisible))
20060 (beginning-of-line 2))
20061 (setq end (point))
20062 (goto-char beg)
20063 (goto-char (point-at-eol))
20064 (setq end (max end (point)))
20065 (while (re-search-forward re end t)
20066 (when (get-char-property (match-beginning 0) 'invisible)
20067 (throw 'exit t))))
20068 nil))))
20070 (defun org-metaup (&optional _arg)
20071 "Move subtree up or move table row up.
20072 Calls `org-move-subtree-up' or `org-table-move-row' or
20073 `org-move-item-up', depending on context. See the individual commands
20074 for more information."
20075 (interactive "P")
20076 (cond
20077 ((run-hook-with-args-until-success 'org-metaup-hook))
20078 ((org-region-active-p)
20079 (let* ((a (min (region-beginning) (region-end)))
20080 (b (1- (max (region-beginning) (region-end))))
20081 (c (save-excursion (goto-char a)
20082 (move-beginning-of-line 0)))
20083 (d (save-excursion (goto-char a)
20084 (move-end-of-line 0) (point))))
20085 (transpose-regions a b c d)
20086 (goto-char c)))
20087 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20088 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20089 ((org-at-item-p) (call-interactively 'org-move-item-up))
20090 (t (org-drag-element-backward))))
20092 (defun org-metadown (&optional _arg)
20093 "Move subtree down or move table row down.
20094 Calls `org-move-subtree-down' or `org-table-move-row' or
20095 `org-move-item-down', depending on context. See the individual
20096 commands for more information."
20097 (interactive "P")
20098 (cond
20099 ((run-hook-with-args-until-success 'org-metadown-hook))
20100 ((org-region-active-p)
20101 (let* ((a (min (region-beginning) (region-end)))
20102 (b (max (region-beginning) (region-end)))
20103 (c (save-excursion (goto-char b)
20104 (move-beginning-of-line 1)))
20105 (d (save-excursion (goto-char b)
20106 (move-end-of-line 1) (1+ (point)))))
20107 (transpose-regions a b c d)
20108 (goto-char d)))
20109 ((org-at-table-p) (call-interactively 'org-table-move-row))
20110 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20111 ((org-at-item-p) (call-interactively 'org-move-item-down))
20112 (t (org-drag-element-forward))))
20114 (defun org-shiftup (&optional arg)
20115 "Increase item in timestamp or increase priority of current headline.
20116 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20117 depending on context. See the individual commands for more information."
20118 (interactive "P")
20119 (cond
20120 ((run-hook-with-args-until-success 'org-shiftup-hook))
20121 ((and org-support-shift-select (org-region-active-p))
20122 (org-call-for-shift-select 'previous-line))
20123 ((org-at-timestamp-p 'lax)
20124 (call-interactively (if org-edit-timestamp-down-means-later
20125 'org-timestamp-down 'org-timestamp-up)))
20126 ((and (not (eq org-support-shift-select 'always))
20127 org-enable-priority-commands
20128 (org-at-heading-p))
20129 (call-interactively 'org-priority-up))
20130 ((and (not org-support-shift-select) (org-at-item-p))
20131 (call-interactively 'org-previous-item))
20132 ((org-clocktable-try-shift 'up arg))
20133 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20134 (org-support-shift-select
20135 (org-call-for-shift-select 'previous-line))
20136 (t (org-shiftselect-error))))
20138 (defun org-shiftdown (&optional arg)
20139 "Decrease item in timestamp or decrease priority of current headline.
20140 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20141 depending on context. See the individual commands for more information."
20142 (interactive "P")
20143 (cond
20144 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20145 ((and org-support-shift-select (org-region-active-p))
20146 (org-call-for-shift-select 'next-line))
20147 ((org-at-timestamp-p 'lax)
20148 (call-interactively (if org-edit-timestamp-down-means-later
20149 'org-timestamp-up 'org-timestamp-down)))
20150 ((and (not (eq org-support-shift-select 'always))
20151 org-enable-priority-commands
20152 (org-at-heading-p))
20153 (call-interactively 'org-priority-down))
20154 ((and (not org-support-shift-select) (org-at-item-p))
20155 (call-interactively 'org-next-item))
20156 ((org-clocktable-try-shift 'down arg))
20157 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20158 (org-support-shift-select
20159 (org-call-for-shift-select 'next-line))
20160 (t (org-shiftselect-error))))
20162 (defun org-shiftright (&optional arg)
20163 "Cycle the thing at point or in the current line, depending on context.
20164 Depending on context, this does one of the following:
20166 - switch a timestamp at point one day into the future
20167 - on a headline, switch to the next TODO keyword.
20168 - on an item, switch entire list to the next bullet type
20169 - on a property line, switch to the next allowed value
20170 - on a clocktable definition line, move time block into the future"
20171 (interactive "P")
20172 (cond
20173 ((run-hook-with-args-until-success 'org-shiftright-hook))
20174 ((and org-support-shift-select (org-region-active-p))
20175 (org-call-for-shift-select 'forward-char))
20176 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20177 ((and (not (eq org-support-shift-select 'always))
20178 (org-at-heading-p))
20179 (let ((org-inhibit-logging
20180 (not org-treat-S-cursor-todo-selection-as-state-change))
20181 (org-inhibit-blocking
20182 (not org-treat-S-cursor-todo-selection-as-state-change)))
20183 (org-call-with-arg 'org-todo 'right)))
20184 ((or (and org-support-shift-select
20185 (not (eq org-support-shift-select 'always))
20186 (org-at-item-bullet-p))
20187 (and (not org-support-shift-select) (org-at-item-p)))
20188 (org-call-with-arg 'org-cycle-list-bullet nil))
20189 ((and (not (eq org-support-shift-select 'always))
20190 (org-at-property-p))
20191 (call-interactively 'org-property-next-allowed-value))
20192 ((org-clocktable-try-shift 'right arg))
20193 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20194 (org-support-shift-select
20195 (org-call-for-shift-select 'forward-char))
20196 (t (org-shiftselect-error))))
20198 (defun org-shiftleft (&optional arg)
20199 "Cycle the thing at point or in the current line, depending on context.
20200 Depending on context, this does one of the following:
20202 - switch a timestamp at point one day into the past
20203 - on a headline, switch to the previous TODO keyword.
20204 - on an item, switch entire list to the previous bullet type
20205 - on a property line, switch to the previous allowed value
20206 - on a clocktable definition line, move time block into the past"
20207 (interactive "P")
20208 (cond
20209 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20210 ((and org-support-shift-select (org-region-active-p))
20211 (org-call-for-shift-select 'backward-char))
20212 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20213 ((and (not (eq org-support-shift-select 'always))
20214 (org-at-heading-p))
20215 (let ((org-inhibit-logging
20216 (not org-treat-S-cursor-todo-selection-as-state-change))
20217 (org-inhibit-blocking
20218 (not org-treat-S-cursor-todo-selection-as-state-change)))
20219 (org-call-with-arg 'org-todo 'left)))
20220 ((or (and org-support-shift-select
20221 (not (eq org-support-shift-select 'always))
20222 (org-at-item-bullet-p))
20223 (and (not org-support-shift-select) (org-at-item-p)))
20224 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20225 ((and (not (eq org-support-shift-select 'always))
20226 (org-at-property-p))
20227 (call-interactively 'org-property-previous-allowed-value))
20228 ((org-clocktable-try-shift 'left arg))
20229 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20230 (org-support-shift-select
20231 (org-call-for-shift-select 'backward-char))
20232 (t (org-shiftselect-error))))
20234 (defun org-shiftcontrolright ()
20235 "Switch to next TODO set."
20236 (interactive)
20237 (cond
20238 ((and org-support-shift-select (org-region-active-p))
20239 (org-call-for-shift-select 'forward-word))
20240 ((and (not (eq org-support-shift-select 'always))
20241 (org-at-heading-p))
20242 (org-call-with-arg 'org-todo 'nextset))
20243 (org-support-shift-select
20244 (org-call-for-shift-select 'forward-word))
20245 (t (org-shiftselect-error))))
20247 (defun org-shiftcontrolleft ()
20248 "Switch to previous TODO set."
20249 (interactive)
20250 (cond
20251 ((and org-support-shift-select (org-region-active-p))
20252 (org-call-for-shift-select 'backward-word))
20253 ((and (not (eq org-support-shift-select 'always))
20254 (org-at-heading-p))
20255 (org-call-with-arg 'org-todo 'previousset))
20256 (org-support-shift-select
20257 (org-call-for-shift-select 'backward-word))
20258 (t (org-shiftselect-error))))
20260 (defun org-shiftcontrolup (&optional n)
20261 "Change timestamps synchronously up in CLOCK log lines.
20262 Optional argument N tells to change by that many units."
20263 (interactive "P")
20264 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20265 (let (org-support-shift-select)
20266 (org-clock-timestamps-up n))
20267 (user-error "Not at a clock log")))
20269 (defun org-shiftcontroldown (&optional n)
20270 "Change timestamps synchronously down in CLOCK log lines.
20271 Optional argument N tells to change by that many units."
20272 (interactive "P")
20273 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20274 (let (org-support-shift-select)
20275 (org-clock-timestamps-down n))
20276 (user-error "Not at a clock log")))
20278 (defun org-increase-number-at-point (&optional inc)
20279 "Increment the number at point.
20280 With an optional prefix numeric argument INC, increment using
20281 this numeric value."
20282 (interactive "p")
20283 (if (not (number-at-point))
20284 (user-error "Not on a number")
20285 (unless inc (setq inc 1))
20286 (let ((pos (point))
20287 (beg (skip-chars-backward "-+^/*0-9eE."))
20288 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20289 (setq nap (buffer-substring-no-properties
20290 (+ pos beg) (+ pos beg end)))
20291 (delete-region (+ pos beg) (+ pos beg end))
20292 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20293 (when (org-at-table-p)
20294 (org-table-align)
20295 (org-table-end-of-field 1))))
20297 (defun org-decrease-number-at-point (&optional inc)
20298 "Decrement the number at point.
20299 With an optional prefix numeric argument INC, decrement using
20300 this numeric value."
20301 (interactive "p")
20302 (org-increase-number-at-point (- (or inc 1))))
20304 (defun org-ctrl-c-ret ()
20305 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20306 (interactive)
20307 (cond
20308 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20309 (t (call-interactively 'org-insert-heading))))
20311 (defun org-find-visible ()
20312 (let ((s (point)))
20313 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20314 (get-char-property s 'invisible)))
20316 (defun org-find-invisible ()
20317 (let ((s (point)))
20318 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20319 (not (get-char-property s 'invisible))))
20322 (defun org-copy-visible (beg end)
20323 "Copy the visible parts of the region."
20324 (interactive "r")
20325 (let ((result ""))
20326 (while (/= beg end)
20327 (when (get-char-property beg 'invisible)
20328 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20329 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20330 (setq result (concat result (buffer-substring beg next)))
20331 (setq beg next)))
20332 (kill-new result)))
20334 (defun org-copy-special ()
20335 "Copy region in table or copy current subtree.
20336 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20337 context. See the individual commands for more information."
20338 (interactive)
20339 (call-interactively
20340 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20342 (defun org-cut-special ()
20343 "Cut region in table or cut current subtree.
20344 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20345 context. See the individual commands for more information."
20346 (interactive)
20347 (call-interactively
20348 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20350 (defun org-paste-special (arg)
20351 "Paste rectangular region into table, or past subtree relative to level.
20352 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20353 See the individual commands for more information."
20354 (interactive "P")
20355 (if (org-at-table-p)
20356 (org-table-paste-rectangle)
20357 (org-paste-subtree arg)))
20359 (defun org-edit-special (&optional arg)
20360 "Call a special editor for the element at point.
20361 When at a table, call the formula editor with `org-table-edit-formulas'.
20362 When in a source code block, call `org-edit-src-code'.
20363 When in a fixed-width region, call `org-edit-fixed-width-region'.
20364 When in an export block, call `org-edit-export-block'.
20365 When in a LaTeX environment, call `org-edit-latex-environment'.
20366 When at an #+INCLUDE keyword, visit the included file.
20367 When at a footnote reference, call `org-edit-footnote-reference'
20368 On a link, call `ffap' to visit the link at point.
20369 Otherwise, return a user error."
20370 (interactive "P")
20371 (let ((element (org-element-at-point)))
20372 (barf-if-buffer-read-only)
20373 (pcase (org-element-type element)
20374 (`src-block
20375 (if (not arg) (org-edit-src-code)
20376 (let* ((info (org-babel-get-src-block-info))
20377 (lang (nth 0 info))
20378 (params (nth 2 info))
20379 (session (cdr (assq :session params))))
20380 (if (not session) (org-edit-src-code)
20381 ;; At a src-block with a session and function called with
20382 ;; an ARG: switch to the buffer related to the inferior
20383 ;; process.
20384 (switch-to-buffer
20385 (funcall (intern (concat "org-babel-prep-session:" lang))
20386 session params))))))
20387 (`keyword
20388 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20389 (org-open-link-from-string
20390 (format "[[%s]]"
20391 (expand-file-name
20392 (let ((value (org-element-property :value element)))
20393 (cond ((org-file-url-p value)
20394 (user-error "The file is specified as a URL, cannot be edited"))
20395 ((not (org-string-nw-p value))
20396 (user-error "No file to edit"))
20397 ((string-match "\\`\"\\(.*?\\)\"" value)
20398 (match-string 1 value))
20399 ((string-match "\\`[^ \t\"]\\S-*" value)
20400 (match-string 0 value))
20401 (t (user-error "No valid file specified")))))))
20402 (user-error "No special environment to edit here")))
20403 (`table
20404 (if (eq (org-element-property :type element) 'table.el)
20405 (org-edit-table.el)
20406 (call-interactively 'org-table-edit-formulas)))
20407 ;; Only Org tables contain `table-row' type elements.
20408 (`table-row (call-interactively 'org-table-edit-formulas))
20409 (`example-block (org-edit-src-code))
20410 (`export-block (org-edit-export-block))
20411 (`fixed-width (org-edit-fixed-width-region))
20412 (`latex-environment (org-edit-latex-environment))
20414 ;; No notable element at point. Though, we may be at a link or
20415 ;; a footnote reference, which are objects. Thus, scan deeper.
20416 (let ((context (org-element-context element)))
20417 (pcase (org-element-type context)
20418 (`footnote-reference (org-edit-footnote-reference))
20419 (`inline-src-block (org-edit-inline-src-code))
20420 (`link (call-interactively #'ffap))
20421 (_ (user-error "No special environment to edit here"))))))))
20423 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20424 (defun org-ctrl-c-ctrl-c (&optional arg)
20425 "Set tags in headline, or update according to changed information at point.
20427 This command does many different things, depending on context:
20429 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20430 this is what we do.
20432 - If the cursor is on a statistics cookie, update it.
20434 - If the cursor is in a headline, prompt for tags and insert them
20435 into the current line, aligned to `org-tags-column'. When called
20436 with prefix arg, realign all tags in the current buffer.
20438 - If the cursor is in one of the special #+KEYWORD lines, this
20439 triggers scanning the buffer for these lines and updating the
20440 information.
20442 - If the cursor is inside a table, realign the table. This command
20443 works even if the automatic table editor has been turned off.
20445 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20446 the entire table.
20448 - If the cursor is at a footnote reference or definition, jump to
20449 the corresponding definition or references, respectively.
20451 - If the cursor is a the beginning of a dynamic block, update it.
20453 - If the current buffer is a capture buffer, close note and file it.
20455 - If the cursor is on a <<<target>>>, update radio targets and
20456 corresponding links in this buffer.
20458 - If the cursor is on a numbered item in a plain list, renumber the
20459 ordered list.
20461 - If the cursor is on a checkbox, toggle it.
20463 - If the cursor is on a code block, evaluate it. The variable
20464 `org-confirm-babel-evaluate' can be used to control prompting
20465 before code block evaluation, by default every code block
20466 evaluation requires confirmation. Code block evaluation can be
20467 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20468 (interactive "P")
20469 (cond
20470 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20471 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20472 (org-remove-occur-highlights)
20473 (message "Temporary highlights/overlays removed from current buffer"))
20474 ((and (local-variable-p 'org-finish-function)
20475 (fboundp org-finish-function))
20476 (funcall org-finish-function))
20477 ((org-babel-hash-at-point))
20478 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20480 (let* ((context
20481 (org-element-lineage
20482 (org-element-context)
20483 ;; Limit to supported contexts.
20484 '(babel-call clock dynamic-block footnote-definition
20485 footnote-reference inline-babel-call inline-src-block
20486 inlinetask item keyword node-property paragraph
20487 plain-list planning property-drawer radio-target
20488 src-block statistics-cookie table table-cell table-row
20489 timestamp)
20491 (type (org-element-type context)))
20492 ;; For convenience: at the first line of a paragraph on the same
20493 ;; line as an item, apply function on that item instead.
20494 (when (eq type 'paragraph)
20495 (let ((parent (org-element-property :parent context)))
20496 (when (and (eq (org-element-type parent) 'item)
20497 (= (line-beginning-position)
20498 (org-element-property :begin parent)))
20499 (setq context parent)
20500 (setq type 'item))))
20501 ;; Act according to type of element or object at point.
20503 ;; Do nothing on a blank line, except if it is contained in
20504 ;; a src block. Hence, we first check if point is in such
20505 ;; a block and then if it is at a blank line.
20506 (pcase type
20507 ((or `inline-src-block `src-block)
20508 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20509 (org-babel-eval-wipe-error-buffer)
20510 (org-babel-execute-src-block
20511 current-prefix-arg (org-babel-get-src-block-info nil context))))
20512 ((guard (org-match-line "[ \t]*$"))
20513 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20514 (user-error
20515 (substitute-command-keys
20516 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20517 ((or `babel-call `inline-babel-call)
20518 (let ((info (org-babel-lob-get-info context)))
20519 (when info (org-babel-execute-src-block nil info))))
20520 (`clock (org-clock-update-time-maybe))
20521 (`dynamic-block
20522 (save-excursion
20523 (goto-char (org-element-property :post-affiliated context))
20524 (org-update-dblock)))
20525 (`footnote-definition
20526 (goto-char (org-element-property :post-affiliated context))
20527 (call-interactively 'org-footnote-action))
20528 (`footnote-reference (call-interactively #'org-footnote-action))
20529 ((or `headline `inlinetask)
20530 (save-excursion (goto-char (org-element-property :begin context))
20531 (call-interactively #'org-set-tags)))
20532 (`item
20533 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20534 ;; unconditionally, whereas `C-u' will toggle its presence.
20535 ;; Without a universal argument, if the item has a checkbox,
20536 ;; toggle it. Otherwise repair the list.
20537 (let* ((box (org-element-property :checkbox context))
20538 (struct (org-element-property :structure context))
20539 (old-struct (copy-tree struct))
20540 (parents (org-list-parents-alist struct))
20541 (prevs (org-list-prevs-alist struct))
20542 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20543 (org-list-set-checkbox
20544 (org-element-property :begin context) struct
20545 (cond ((equal arg '(16)) "[-]")
20546 ((and (not box) (equal arg '(4))) "[ ]")
20547 ((or (not box) (equal arg '(4))) nil)
20548 ((eq box 'on) "[ ]")
20549 (t "[X]")))
20550 ;; Mimic `org-list-write-struct' but with grabbing a return
20551 ;; value from `org-list-struct-fix-box'.
20552 (org-list-struct-fix-ind struct parents 2)
20553 (org-list-struct-fix-item-end struct)
20554 (org-list-struct-fix-bul struct prevs)
20555 (org-list-struct-fix-ind struct parents)
20556 (let ((block-item
20557 (org-list-struct-fix-box struct parents prevs orderedp)))
20558 (if (and box (equal struct old-struct))
20559 (if (equal arg '(16))
20560 (message "Checkboxes already reset")
20561 (user-error "Cannot toggle this checkbox: %s"
20562 (if (eq box 'on)
20563 "all subitems checked"
20564 "unchecked subitems")))
20565 (org-list-struct-apply-struct struct old-struct)
20566 (org-update-checkbox-count-maybe))
20567 (when block-item
20568 (message "Checkboxes were removed due to empty box at line %d"
20569 (org-current-line block-item))))))
20570 (`keyword
20571 (let ((org-inhibit-startup-visibility-stuff t)
20572 (org-startup-align-all-tables nil))
20573 (when (boundp 'org-table-coordinate-overlays)
20574 (mapc #'delete-overlay org-table-coordinate-overlays)
20575 (setq org-table-coordinate-overlays nil))
20576 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20577 (message "Local setup has been refreshed"))
20578 (`plain-list
20579 ;; At a plain list, with a double C-u argument, set
20580 ;; checkboxes of each item to "[-]", whereas a single one
20581 ;; will toggle their presence according to the state of the
20582 ;; first item in the list. Without an argument, repair the
20583 ;; list.
20584 (let* ((begin (org-element-property :contents-begin context))
20585 (beginm (move-marker (make-marker) begin))
20586 (struct (org-element-property :structure context))
20587 (old-struct (copy-tree struct))
20588 (first-box (save-excursion
20589 (goto-char begin)
20590 (looking-at org-list-full-item-re)
20591 (match-string-no-properties 3)))
20592 (new-box (cond ((equal arg '(16)) "[-]")
20593 ((equal arg '(4)) (unless first-box "[ ]"))
20594 ((equal first-box "[X]") "[ ]")
20595 (t "[X]"))))
20596 (cond
20597 (arg
20598 (dolist (pos
20599 (org-list-get-all-items
20600 begin struct (org-list-prevs-alist struct)))
20601 (org-list-set-checkbox pos struct new-box)))
20602 ((and first-box (eq (point) begin))
20603 ;; For convenience, when point is at bol on the first
20604 ;; item of the list and no argument is provided, simply
20605 ;; toggle checkbox of that item, if any.
20606 (org-list-set-checkbox begin struct new-box)))
20607 (org-list-write-struct
20608 struct (org-list-parents-alist struct) old-struct)
20609 (org-update-checkbox-count-maybe)
20610 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20611 ((or `property-drawer `node-property)
20612 (call-interactively #'org-property-action))
20613 (`radio-target
20614 (call-interactively #'org-update-radio-target-regexp))
20615 (`statistics-cookie
20616 (call-interactively #'org-update-statistics-cookies))
20617 ((or `table `table-cell `table-row)
20618 ;; At a table, recalculate every field and align it. Also
20619 ;; send the table if necessary. If the table has
20620 ;; a `table.el' type, just give up. At a table row or cell,
20621 ;; maybe recalculate line but always align table.
20622 (if (eq (org-element-property :type context) 'table.el)
20623 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20624 Use `\\[org-edit-special]' to edit table.el tables"))
20625 (if (or (eq type 'table)
20626 ;; Check if point is at a TBLFM line.
20627 (and (eq type 'table-row)
20628 (= (point) (org-element-property :end context))))
20629 (save-excursion
20630 (if (org-at-TBLFM-p)
20631 (progn (require 'org-table)
20632 (org-table-calc-current-TBLFM))
20633 (goto-char (org-element-property :contents-begin context))
20634 (org-call-with-arg 'org-table-recalculate (or arg t))
20635 (orgtbl-send-table 'maybe)))
20636 (org-table-maybe-eval-formula)
20637 (cond (arg (call-interactively #'org-table-recalculate))
20638 ((org-table-maybe-recalculate-line))
20639 (t (org-table-align))))))
20640 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20641 (org-timestamp-change 0 'day))
20642 ((and `nil (guard (org-at-heading-p)))
20643 ;; When point is on an unsupported object type, we can miss
20644 ;; the fact that it also is at a heading. Handle it here.
20645 (call-interactively #'org-set-tags))
20646 ((guard
20647 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20649 (user-error
20650 (substitute-command-keys
20651 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20653 (defun org-mode-restart ()
20654 (interactive)
20655 (let ((indent-status (bound-and-true-p org-indent-mode)))
20656 (funcall major-mode)
20657 (hack-local-variables)
20658 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20659 (org-indent-mode -1))
20660 (org-reset-file-cache))
20661 (message "%s restarted" major-mode))
20663 (defun org-kill-note-or-show-branches ()
20664 "Abort storing current note, or call `outline-show-branches'."
20665 (interactive)
20666 (if (not org-finish-function)
20667 (progn
20668 (outline-hide-subtree)
20669 (call-interactively 'outline-show-branches))
20670 (let ((org-note-abort t))
20671 (funcall org-finish-function))))
20673 (defun org-delete-indentation (&optional arg)
20674 "Join current line to previous and fix whitespace at join.
20676 If previous line is a headline add to headline title. Otherwise
20677 the function calls `delete-indentation'.
20679 With a non-nil optional argument, join it to the following one."
20680 (interactive "*P")
20681 (if (save-excursion
20682 (beginning-of-line (if arg 1 0))
20683 (let ((case-fold-search nil))
20684 (looking-at org-complex-heading-regexp)))
20685 ;; At headline.
20686 (let ((tags-column (when (match-beginning 5)
20687 (save-excursion (goto-char (match-beginning 5))
20688 (current-column))))
20689 (string (concat " " (progn (when arg (forward-line 1))
20690 (org-trim (delete-and-extract-region
20691 (line-beginning-position)
20692 (line-end-position)))))))
20693 (unless (bobp) (delete-region (point) (1- (point))))
20694 (goto-char (or (match-end 4)
20695 (match-beginning 5)
20696 (match-end 0)))
20697 (skip-chars-backward " \t")
20698 (save-excursion (insert string))
20699 ;; Adjust alignment of tags.
20700 (cond
20701 ((not tags-column)) ;no tags
20702 (org-auto-align-tags (org-set-tags nil t))
20703 (t (org--align-tags-here tags-column)))) ;preserve tags column
20704 (delete-indentation arg)))
20706 (defun org-open-line (n)
20707 "Insert a new row in tables, call `open-line' elsewhere.
20708 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20709 As a special case, when a document starts with a table, allow to
20710 call `open-line' on the very first character."
20711 (interactive "*p")
20712 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20713 (org-table-insert-row)
20714 (open-line n)))
20716 (defun org-return (&optional indent)
20717 "Goto next table row or insert a newline.
20719 Calls `org-table-next-row' or `newline', depending on context.
20721 When optional INDENT argument is non-nil, call
20722 `newline-and-indent' instead of `newline'.
20724 When `org-return-follows-link' is non-nil and point is on
20725 a timestamp or a link, call `org-open-at-point'. However, it
20726 will not happen if point is in a table or on a \"dead\"
20727 object (e.g., within a comment). In these case, you need to use
20728 `org-open-at-point' directly."
20729 (interactive)
20730 (let ((context (if org-return-follows-link (org-element-context)
20731 (org-element-at-point))))
20732 (cond
20733 ;; In a table, call `org-table-next-row'.
20734 ((or (and (eq (org-element-type context) 'table)
20735 (>= (point) (org-element-property :contents-begin context))
20736 (< (point) (org-element-property :contents-end context)))
20737 (org-element-lineage context '(table-row table-cell) t))
20738 (org-table-justify-field-maybe)
20739 (call-interactively #'org-table-next-row))
20740 ;; On a link or a timestamp, call `org-open-at-point' if
20741 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20742 ;; locations, e.g., in a comment, as `org-open-at-point'.
20743 ((and org-return-follows-link
20744 (or (org-in-regexp org-ts-regexp-both nil t)
20745 (org-in-regexp org-tsr-regexp-both nil t)
20746 (org-in-regexp org-any-link-re nil t)))
20747 (call-interactively #'org-open-at-point))
20748 ;; Insert newline in heading, but preserve tags.
20749 ((and (not (bolp))
20750 (save-excursion (beginning-of-line)
20751 (let ((case-fold-search nil))
20752 (looking-at org-complex-heading-regexp))))
20753 ;; At headline. Split line. However, if point is on keyword,
20754 ;; priority cookie or tags, do not break any of them: add
20755 ;; a newline after the headline instead.
20756 (let ((tags-column (and (match-beginning 5)
20757 (save-excursion (goto-char (match-beginning 5))
20758 (current-column))))
20759 (string
20760 (when (and (match-end 4) (org-point-in-group (point) 4))
20761 (delete-and-extract-region (point) (match-end 4)))))
20762 ;; Adjust tag alignment.
20763 (cond
20764 ((not (and tags-column string)))
20765 (org-auto-align-tags (org-set-tags nil t))
20766 (t (org--align-tags-here tags-column))) ;preserve tags column
20767 (end-of-line)
20768 (org-show-entry)
20769 (if indent (newline-and-indent) (newline))
20770 (when string (save-excursion (insert (org-trim string))))))
20771 ;; In a list, make sure indenting keeps trailing text within.
20772 ((and indent
20773 (not (eolp))
20774 (org-element-lineage context '(item)))
20775 (let ((trailing-data
20776 (delete-and-extract-region (point) (line-end-position))))
20777 (newline-and-indent)
20778 (save-excursion (insert trailing-data))))
20779 (t (if indent (newline-and-indent) (newline))))))
20781 (defun org-return-indent ()
20782 "Goto next table row or insert a newline and indent.
20783 Calls `org-table-next-row' or `newline-and-indent', depending on
20784 context. See the individual commands for more information."
20785 (interactive)
20786 (org-return t))
20788 (defun org-ctrl-c-tab (&optional _arg)
20789 "Toggle columns width in a table, or show children.
20790 Call `org-table-toggle-column-width' if point is in a table.
20791 Otherwise, call `org-show-children'."
20792 (interactive "p")
20793 (call-interactively
20794 (if (org-at-table-p) #'org-table-toggle-column-width
20795 #'org-show-children)))
20797 (defun org-ctrl-c-star ()
20798 "Compute table, or change heading status of lines.
20799 Calls `org-table-recalculate' or `org-toggle-heading',
20800 depending on context."
20801 (interactive)
20802 (cond
20803 ((org-at-table-p)
20804 (call-interactively 'org-table-recalculate))
20806 ;; Convert all lines in region to list items
20807 (call-interactively 'org-toggle-heading))))
20809 (defun org-ctrl-c-minus ()
20810 "Insert separator line in table or modify bullet status of line.
20811 Also turns a plain line or a region of lines into list items.
20812 Calls `org-table-insert-hline', `org-toggle-item', or
20813 `org-cycle-list-bullet', depending on context."
20814 (interactive)
20815 (cond
20816 ((org-at-table-p)
20817 (call-interactively 'org-table-insert-hline))
20818 ((org-region-active-p)
20819 (call-interactively 'org-toggle-item))
20820 ((org-in-item-p)
20821 (call-interactively 'org-cycle-list-bullet))
20823 (call-interactively 'org-toggle-item))))
20825 (defun org-toggle-heading (&optional nstars)
20826 "Convert headings to normal text, or items or text to headings.
20827 If there is no active region, only convert the current line.
20829 With a `\\[universal-argument]' prefix, convert the whole list at
20830 point into heading.
20832 In a region:
20834 - If the first non blank line is a headline, remove the stars
20835 from all headlines in the region.
20837 - If it is a normal line, turn each and every normal line (i.e.,
20838 not an heading or an item) in the region into headings. If you
20839 want to convert only the first line of this region, use one
20840 universal prefix argument.
20842 - If it is a plain list item, turn all plain list items into headings.
20844 When converting a line into a heading, the number of stars is chosen
20845 such that the lines become children of the current entry. However,
20846 when a numeric prefix argument is given, its value determines the
20847 number of stars to add."
20848 (interactive "P")
20849 (let ((skip-blanks
20850 (function
20851 ;; Return beginning of first non-blank line, starting from
20852 ;; line at POS.
20853 (lambda (pos)
20854 (save-excursion
20855 (goto-char pos)
20856 (while (org-at-comment-p) (forward-line))
20857 (skip-chars-forward " \r\t\n")
20858 (point-at-bol)))))
20859 beg end toggled)
20860 ;; Determine boundaries of changes. If a universal prefix has
20861 ;; been given, put the list in a region. If region ends at a bol,
20862 ;; do not consider the last line to be in the region.
20864 (when (and current-prefix-arg (org-at-item-p))
20865 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20866 (org-mark-element))
20868 (if (org-region-active-p)
20869 (setq beg (funcall skip-blanks (region-beginning))
20870 end (copy-marker (save-excursion
20871 (goto-char (region-end))
20872 (if (bolp) (point) (point-at-eol)))))
20873 (setq beg (funcall skip-blanks (point-at-bol))
20874 end (copy-marker (point-at-eol))))
20875 ;; Ensure inline tasks don't count as headings.
20876 (org-with-limited-levels
20877 (save-excursion
20878 (goto-char beg)
20879 (cond
20880 ;; Case 1. Started at an heading: de-star headings.
20881 ((org-at-heading-p)
20882 (while (< (point) end)
20883 (when (org-at-heading-p t)
20884 (looking-at org-outline-regexp) (replace-match "")
20885 (setq toggled t))
20886 (forward-line)))
20887 ;; Case 2. Started at an item: change items into headlines.
20888 ;; One star will be added by `org-list-to-subtree'.
20889 ((org-at-item-p)
20890 (while (< (point) end)
20891 (when (org-at-item-p)
20892 ;; Pay attention to cases when region ends before list.
20893 (let* ((struct (org-list-struct))
20894 (list-end
20895 (min (org-list-get-bottom-point struct) (1+ end))))
20896 (save-restriction
20897 (narrow-to-region (point) list-end)
20898 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20899 (setq toggled t))
20900 (forward-line)))
20901 ;; Case 3. Started at normal text: make every line an heading,
20902 ;; skipping headlines and items.
20903 (t (let* ((stars
20904 (make-string
20905 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20906 (add-stars
20907 (cond (nstars "") ; stars from prefix only
20908 ((equal stars "") "*") ; before first heading
20909 (org-odd-levels-only "**") ; inside heading, odd
20910 (t "*"))) ; inside heading, oddeven
20911 (rpl (concat stars add-stars " "))
20912 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20913 (while (< (point) (if (equal nstars '(4)) lend end))
20914 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20915 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20916 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20917 (forward-line)))))))
20918 (unless toggled (message "Cannot toggle heading from here"))))
20920 (defun org-meta-return (&optional arg)
20921 "Insert a new heading or wrap a region in a table.
20922 Calls `org-insert-heading', `org-insert-item' or
20923 `org-table-wrap-region', depending on context. When called with
20924 an argument, unconditionally call `org-insert-heading'."
20925 (interactive "P")
20926 (org-check-before-invisible-edit 'insert)
20927 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20928 (call-interactively (cond (arg #'org-insert-heading)
20929 ((org-at-table-p) #'org-table-wrap-region)
20930 ((org-in-item-p) #'org-insert-item)
20931 (t #'org-insert-heading)))))
20933 ;;; Menu entries
20935 (defsubst org-in-subtree-not-table-p ()
20936 "Are we in a subtree and not in a table?"
20937 (and (not (org-before-first-heading-p))
20938 (not (org-at-table-p))))
20940 ;; Define the Org mode menus
20941 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20942 '("Tbl"
20943 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20944 ["Next Field" org-cycle (org-at-table-p)]
20945 ["Previous Field" org-shifttab (org-at-table-p)]
20946 ["Next Row" org-return (org-at-table-p)]
20947 "--"
20948 ["Blank Field" org-table-blank-field (org-at-table-p)]
20949 ["Edit Field" org-table-edit-field (org-at-table-p)]
20950 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20951 "--"
20952 ("Column"
20953 ["Move Column Left" org-metaleft (org-at-table-p)]
20954 ["Move Column Right" org-metaright (org-at-table-p)]
20955 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20956 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20957 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20958 ("Row"
20959 ["Move Row Up" org-metaup (org-at-table-p)]
20960 ["Move Row Down" org-metadown (org-at-table-p)]
20961 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20962 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20963 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20964 "--"
20965 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20966 ("Rectangle"
20967 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20968 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20969 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20970 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20971 "--"
20972 ("Calculate"
20973 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20974 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20975 ["Edit Formulas" org-edit-special (org-at-table-p)]
20976 "--"
20977 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20978 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20979 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20980 "--"
20981 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20982 "--"
20983 ["Sum Column/Rectangle" org-table-sum
20984 (or (org-at-table-p) (org-region-active-p))]
20985 ["Which Column?" org-table-current-column (org-at-table-p)])
20986 ["Debug Formulas"
20987 org-table-toggle-formula-debugger
20988 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20989 ["Show Col/Row Numbers"
20990 org-table-toggle-coordinate-overlays
20991 :style toggle
20992 :selected (bound-and-true-p org-table-overlay-coordinates)]
20993 "--"
20994 ["Create" org-table-create (not (org-at-table-p))]
20995 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20996 ["Import from File" org-table-import (not (org-at-table-p))]
20997 ["Export to File" org-table-export (org-at-table-p)]
20998 "--"
20999 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21000 "--"
21001 ("Plot"
21002 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21003 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21005 (easy-menu-define org-org-menu org-mode-map "Org menu"
21006 '("Org"
21007 ("Show/Hide"
21008 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21009 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21010 ["Sparse Tree..." org-sparse-tree t]
21011 ["Reveal Context" org-reveal t]
21012 ["Show All" outline-show-all t]
21013 "--"
21014 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21015 "--"
21016 ["New Heading" org-insert-heading t]
21017 ("Navigate Headings"
21018 ["Up" outline-up-heading t]
21019 ["Next" outline-next-visible-heading t]
21020 ["Previous" outline-previous-visible-heading t]
21021 ["Next Same Level" outline-forward-same-level t]
21022 ["Previous Same Level" outline-backward-same-level t]
21023 "--"
21024 ["Jump" org-goto t])
21025 ("Edit Structure"
21026 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21027 "--"
21028 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21029 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21030 "--"
21031 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21032 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21033 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21034 "--"
21035 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21036 "--"
21037 ["Copy visible text" org-copy-visible t]
21038 "--"
21039 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21040 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21041 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21042 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21043 "--"
21044 ["Sort Region/Children" org-sort t]
21045 "--"
21046 ["Convert to odd levels" org-convert-to-odd-levels t]
21047 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21048 ("Editing"
21049 ["Emphasis..." org-emphasize t]
21050 ["Edit Source Example" org-edit-special t]
21051 "--"
21052 ["Footnote new/jump" org-footnote-action t]
21053 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21054 ("Archive"
21055 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21056 "--"
21057 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21058 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21059 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21061 "--"
21062 ("Hyperlinks"
21063 ["Store Link (Global)" org-store-link t]
21064 ["Find existing link to here" org-occur-link-in-agenda-files t]
21065 ["Insert Link" org-insert-link t]
21066 ["Follow Link" org-open-at-point t]
21067 "--"
21068 ["Next link" org-next-link t]
21069 ["Previous link" org-previous-link t]
21070 "--"
21071 ["Descriptive Links"
21072 org-toggle-link-display
21073 :style radio
21074 :selected org-descriptive-links
21076 ["Literal Links"
21077 org-toggle-link-display
21078 :style radio
21079 :selected (not org-descriptive-links)])
21080 "--"
21081 ("TODO Lists"
21082 ["TODO/DONE/-" org-todo t]
21083 ("Select keyword"
21084 ["Next keyword" org-shiftright (org-at-heading-p)]
21085 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21086 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21087 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21088 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21089 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21090 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21091 "--"
21092 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21093 :selected org-enforce-todo-dependencies :style toggle :active t]
21094 "Settings for tree at point"
21095 ["Do Children sequentially" org-toggle-ordered-property :style radio
21096 :selected (org-entry-get nil "ORDERED")
21097 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21098 ["Do Children parallel" org-toggle-ordered-property :style radio
21099 :selected (not (org-entry-get nil "ORDERED"))
21100 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21101 "--"
21102 ["Set Priority" org-priority t]
21103 ["Priority Up" org-shiftup t]
21104 ["Priority Down" org-shiftdown t]
21105 "--"
21106 ["Get news from all feeds" org-feed-update-all t]
21107 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21108 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21109 ("TAGS and Properties"
21110 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21111 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21112 "--"
21113 ["Set property" org-set-property (not (org-before-first-heading-p))]
21114 ["Column view of properties" org-columns t]
21115 ["Insert Column View DBlock" org-columns-insert-dblock t])
21116 ("Dates and Scheduling"
21117 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21118 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21119 ("Change Date"
21120 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21121 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21122 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21123 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21124 ["Compute Time Range" org-evaluate-time-range t]
21125 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21126 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21127 "--"
21128 ["Custom time format" org-toggle-time-stamp-overlays
21129 :style radio :selected org-display-custom-times]
21130 "--"
21131 ["Goto Calendar" org-goto-calendar t]
21132 ["Date from Calendar" org-date-from-calendar t]
21133 "--"
21134 ["Start/Restart Timer" org-timer-start t]
21135 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21136 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21137 ["Insert Timer String" org-timer t]
21138 ["Insert Timer Item" org-timer-item t])
21139 ("Logging work"
21140 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21141 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21142 ["Clock out" org-clock-out t]
21143 ["Clock cancel" org-clock-cancel t]
21144 "--"
21145 ["Mark as default task" org-clock-mark-default-task t]
21146 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21147 ["Goto running clock" org-clock-goto t]
21148 "--"
21149 ["Display times" org-clock-display t]
21150 ["Create clock table" org-clock-report t]
21151 "--"
21152 ["Record DONE time"
21153 (progn (setq org-log-done (not org-log-done))
21154 (message "Switching to %s will %s record a timestamp"
21155 (car org-done-keywords)
21156 (if org-log-done "automatically" "not")))
21157 :style toggle :selected org-log-done])
21158 "--"
21159 ["Agenda Command..." org-agenda t]
21160 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21161 ("File List for Agenda")
21162 ("Special views current file"
21163 ["TODO Tree" org-show-todo-tree t]
21164 ["Check Deadlines" org-check-deadlines t]
21165 ["Tags/Property tree" org-match-sparse-tree t])
21166 "--"
21167 ["Export/Publish..." org-export-dispatch t]
21168 ("LaTeX"
21169 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21170 :selected org-cdlatex-mode]
21171 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21172 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21173 ["Modify math symbol" org-cdlatex-math-modify
21174 (org-inside-LaTeX-fragment-p)]
21175 ["Insert citation" org-reftex-citation t])
21176 "--"
21177 ("MobileOrg"
21178 ["Push Files and Views" org-mobile-push t]
21179 ["Get Captured and Flagged" org-mobile-pull t]
21180 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21181 "--"
21182 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21183 "--"
21184 ("Documentation"
21185 ["Show Version" org-version t]
21186 ["Info Documentation" org-info t])
21187 ("Customize"
21188 ["Browse Org Group" org-customize t]
21189 "--"
21190 ["Expand This Menu" org-create-customize-menu
21191 (fboundp 'customize-menu-create)])
21192 ["Send bug report" org-submit-bug-report t]
21193 "--"
21194 ("Refresh/Reload"
21195 ["Refresh setup current buffer" org-mode-restart t]
21196 ["Reload Org (after update)" org-reload t]
21197 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21200 (defun org-info (&optional node)
21201 "Read documentation for Org in the info system.
21202 With optional NODE, go directly to that node."
21203 (interactive)
21204 (info (format "(org)%s" (or node ""))))
21206 ;;;###autoload
21207 (defun org-submit-bug-report ()
21208 "Submit a bug report on Org via mail.
21210 Don't hesitate to report any problems or inaccurate documentation.
21212 If you don't have setup sending mail from (X)Emacs, please copy the
21213 output buffer into your mail program, as it gives us important
21214 information about your Org version and configuration."
21215 (interactive)
21216 (require 'reporter)
21217 (defvar reporter-prompt-for-summary-p)
21218 (org-load-modules-maybe)
21219 (org-require-autoloaded-modules)
21220 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21221 (reporter-submit-bug-report
21222 "emacs-orgmode@gnu.org"
21223 (org-version nil 'full)
21224 (let (list)
21225 (save-window-excursion
21226 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21227 (delete-other-windows)
21228 (erase-buffer)
21229 (insert "You are about to submit a bug report to the Org mailing list.
21231 We would like to add your full Org and Outline configuration to the
21232 bug report. This greatly simplifies the work of the maintainer and
21233 other experts on the mailing list.
21235 HOWEVER, some variables you have customized may contain private
21236 information. The names of customers, colleagues, or friends, might
21237 appear in the form of file names, tags, todo states, or search strings.
21238 If you answer yes to the prompt, you might want to check and remove
21239 such private information before sending the email.")
21240 (add-text-properties (point-min) (point-max) '(face org-warning))
21241 (when (yes-or-no-p "Include your Org configuration ")
21242 (mapatoms
21243 (lambda (v)
21244 (and (boundp v)
21245 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21246 (or (and (symbol-value v)
21247 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21248 (and
21249 (get v 'custom-type) (get v 'standard-value)
21250 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21251 (push v list)))))
21252 (kill-buffer (get-buffer "*Warn about privacy*"))
21253 list))
21254 nil nil
21255 "Remember to cover the basics, that is, what you expected to happen and
21256 what in fact did happen. You don't know how to make a good report? See
21258 http://orgmode.org/manual/Feedback.html#Feedback
21260 Your bug report will be posted to the Org mailing list.
21261 ------------------------------------------------------------------------")
21262 (save-excursion
21263 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21264 (replace-match "\\1Bug: \\3 [\\2]")))))
21267 (defun org-install-agenda-files-menu ()
21268 (let ((bl (buffer-list)))
21269 (save-excursion
21270 (while bl
21271 (set-buffer (pop bl))
21272 (when (derived-mode-p 'org-mode) (setq bl nil)))
21273 (when (derived-mode-p 'org-mode)
21274 (easy-menu-change
21275 '("Org") "File List for Agenda"
21276 (append
21277 (list
21278 ["Edit File List" (org-edit-agenda-file-list) t]
21279 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21280 ["Remove Current File from List" org-remove-file t]
21281 ["Cycle through agenda files" org-cycle-agenda-files t]
21282 ["Occur in all agenda files" org-occur-in-agenda-files t]
21283 "--")
21284 (mapcar 'org-file-menu-entry
21285 ;; Prevent initialization from failing.
21286 (ignore-errors (org-agenda-files t)))))))))
21288 ;;;; Documentation
21290 (defun org-require-autoloaded-modules ()
21291 (interactive)
21292 (mapc #'require
21293 '(org-agenda org-archive org-attach org-clock org-colview org-id
21294 org-table org-timer)))
21296 ;;;###autoload
21297 (defun org-reload (&optional uncompiled)
21298 "Reload all org lisp files.
21299 With prefix arg UNCOMPILED, load the uncompiled versions."
21300 (interactive "P")
21301 (require 'loadhist)
21302 (let* ((org-dir (org-find-library-dir "org"))
21303 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21304 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21305 (remove-re (format "\\`%s\\'"
21306 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21307 (feats (delete-dups
21308 (mapcar 'file-name-sans-extension
21309 (mapcar 'file-name-nondirectory
21310 (delq nil
21311 (mapcar 'feature-file
21312 features))))))
21313 (lfeat (append
21314 (sort
21315 (setq feats
21316 (delq nil (mapcar
21317 (lambda (f)
21318 (if (and (string-match feature-re f)
21319 (not (string-match remove-re f)))
21320 f nil))
21321 feats)))
21322 'string-lessp)
21323 (list "org-version" "org")))
21324 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21325 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21326 load-uncore load-misses)
21327 (setq load-misses
21328 (delq 't
21329 (mapcar (lambda (f)
21330 (or (org-load-noerror-mustsuffix (concat org-dir f))
21331 (and (string= org-dir contrib-dir)
21332 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21333 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21334 (add-to-list 'load-uncore f 'append)
21337 lfeat)))
21338 (when load-uncore
21339 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21340 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21341 (if load-misses
21342 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21343 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21344 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21346 ;;;###autoload
21347 (defun org-customize ()
21348 "Call the customize function with org as argument."
21349 (interactive)
21350 (org-load-modules-maybe)
21351 (org-require-autoloaded-modules)
21352 (customize-browse 'org))
21354 (defun org-create-customize-menu ()
21355 "Create a full customization menu for Org mode, insert it into the menu."
21356 (interactive)
21357 (org-load-modules-maybe)
21358 (org-require-autoloaded-modules)
21359 (if (fboundp 'customize-menu-create)
21360 (progn
21361 (easy-menu-change
21362 '("Org") "Customize"
21363 `(["Browse Org group" org-customize t]
21364 "--"
21365 ,(customize-menu-create 'org)
21366 ["Set" Custom-set t]
21367 ["Save" Custom-save t]
21368 ["Reset to Current" Custom-reset-current t]
21369 ["Reset to Saved" Custom-reset-saved t]
21370 ["Reset to Standard Settings" Custom-reset-standard t]))
21371 (message "\"Org\"-menu now contains full customization menu"))
21372 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21374 ;;;; Miscellaneous stuff
21376 ;;; Generally useful functions
21378 (defun org-link-display-format (s)
21379 "Replace links in string S with their description.
21380 If there is no description, use the link target."
21381 (save-match-data
21382 (replace-regexp-in-string
21383 org-bracket-link-analytic-regexp
21384 (lambda (m)
21385 (if (match-end 5) (match-string 5 m)
21386 (concat (match-string 1 m) (match-string 3 m))))
21387 s nil t)))
21389 (defun org-toggle-link-display ()
21390 "Toggle the literal or descriptive display of links."
21391 (interactive)
21392 (if org-descriptive-links
21393 (progn (org-remove-from-invisibility-spec '(org-link))
21394 (org-restart-font-lock)
21395 (setq org-descriptive-links nil))
21396 (progn (add-to-invisibility-spec '(org-link))
21397 (org-restart-font-lock)
21398 (setq org-descriptive-links t))))
21400 (defun org-in-clocktable-p ()
21401 "Check if the cursor is in a clocktable."
21402 (let ((pos (point)) start)
21403 (save-excursion
21404 (end-of-line 1)
21405 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21406 (setq start (match-beginning 0))
21407 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21408 (>= (match-end 0) pos)
21409 start))))
21411 (defun org-in-verbatim-emphasis ()
21412 (save-match-data
21413 (and (org-in-regexp org-verbatim-re 2)
21414 (>= (point) (match-beginning 3))
21415 (<= (point) (match-end 4)))))
21417 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21418 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21419 (if (and marker (marker-buffer marker)
21420 (buffer-live-p (marker-buffer marker)))
21421 (progn
21422 (pop-to-buffer-same-window (marker-buffer marker))
21423 (when (or (> marker (point-max)) (< marker (point-min)))
21424 (widen))
21425 (goto-char marker)
21426 (org-show-context 'org-goto))
21427 (if bookmark
21428 (bookmark-jump bookmark)
21429 (error "Cannot find location"))))
21431 (defun org-quote-csv-field (s)
21432 "Quote field for inclusion in CSV material."
21433 (if (string-match "[\",]" s)
21434 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21437 (defun org-force-self-insert (N)
21438 "Needed to enforce self-insert under remapping."
21439 (interactive "p")
21440 (self-insert-command N))
21442 (defun org-get-indentation (&optional line)
21443 "Get the indentation of the current line, interpreting tabs.
21444 When LINE is given, assume it represents a line and compute its indentation."
21445 (if line
21446 (when (string-match "^ *" (org-remove-tabs line))
21447 (match-end 0))
21448 (save-excursion
21449 (beginning-of-line 1)
21450 (skip-chars-forward " \t")
21451 (current-column))))
21453 (defun org-get-string-indentation (s)
21454 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21455 (let ((n -1) (i 0) (w tab-width) c)
21456 (catch 'exit
21457 (while (< (setq n (1+ n)) (length s))
21458 (setq c (aref s n))
21459 (cond ((= c ?\ ) (setq i (1+ i)))
21460 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21461 (t (throw 'exit t)))))
21464 (defun org-fix-indentation (line ind)
21465 "Fix indentation in LINE.
21466 IND is a cons cell with target and minimum indentation.
21467 If the current indentation in LINE is smaller than the minimum,
21468 leave it alone. If it is larger than ind, set it to the target."
21469 (let* ((l (org-remove-tabs line))
21470 (i (org-get-indentation l))
21471 (i1 (car ind)) (i2 (cdr ind)))
21472 (when (>= i i2) (setq l (substring line i2)))
21473 (if (> i1 0)
21474 (concat (make-string i1 ?\ ) l)
21475 l)))
21477 (defun org-fill-template (template alist)
21478 "Find each %key of ALIST in TEMPLATE and replace it."
21479 (let ((case-fold-search nil))
21480 (dolist (entry (sort (copy-sequence alist)
21481 (lambda (a b) (< (length (car a)) (length (car b))))))
21482 (setq template
21483 (replace-regexp-in-string
21484 (concat "%" (regexp-quote (car entry)))
21485 (or (cdr entry) "") template t t)))
21486 template))
21488 (defun org-quote-vert (s)
21489 "Replace \"|\" with \"\\vert\"."
21490 (while (string-match "|" s)
21491 (setq s (replace-match "\\vert" t t s)))
21494 (defun org-uuidgen-p (s)
21495 "Is S an ID created by UUIDGEN?"
21496 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21498 (defun org-in-src-block-p (&optional inside)
21499 "Whether point is in a code source block.
21500 When INSIDE is non-nil, don't consider we are within a src block
21501 when point is at #+BEGIN_SRC or #+END_SRC."
21502 (let ((case-fold-search t))
21503 (or (and (eq (get-char-property (point) 'src-block) t))
21504 (and (not inside)
21505 (save-match-data
21506 (save-excursion
21507 (beginning-of-line)
21508 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21510 (defun org-context ()
21511 "Return a list of contexts of the current cursor position.
21512 If several contexts apply, all are returned.
21513 Each context entry is a list with a symbol naming the context, and
21514 two positions indicating start and end of the context. Possible
21515 contexts are:
21517 :headline anywhere in a headline
21518 :headline-stars on the leading stars in a headline
21519 :todo-keyword on a TODO keyword (including DONE) in a headline
21520 :tags on the TAGS in a headline
21521 :priority on the priority cookie in a headline
21522 :item on the first line of a plain list item
21523 :item-bullet on the bullet/number of a plain list item
21524 :checkbox on the checkbox in a plain list item
21525 :table in an Org table
21526 :table-special on a special filed in a table
21527 :table-table in a table.el table
21528 :clocktable in a clocktable
21529 :src-block in a source block
21530 :link on a hyperlink
21531 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21532 :target on a <<target>>
21533 :radio-target on a <<<radio-target>>>
21534 :latex-fragment on a LaTeX fragment
21535 :latex-preview on a LaTeX fragment with overlaid preview image
21537 This function expects the position to be visible because it uses font-lock
21538 faces as a help to recognize the following contexts: :table-special, :link,
21539 and :keyword."
21540 (let* ((f (get-text-property (point) 'face))
21541 (faces (if (listp f) f (list f)))
21542 (case-fold-search t)
21543 (p (point)) clist o)
21544 ;; First the large context
21545 (cond
21546 ((org-at-heading-p t)
21547 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21548 (when (progn
21549 (beginning-of-line 1)
21550 (looking-at org-todo-line-tags-regexp))
21551 (push (org-point-in-group p 1 :headline-stars) clist)
21552 (push (org-point-in-group p 2 :todo-keyword) clist)
21553 (push (org-point-in-group p 4 :tags) clist))
21554 (goto-char p)
21555 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21556 (when (looking-at "\\[#[A-Z0-9]\\]")
21557 (push (org-point-in-group p 0 :priority) clist)))
21559 ((org-at-item-p)
21560 (push (org-point-in-group p 2 :item-bullet) clist)
21561 (push (list :item (point-at-bol)
21562 (save-excursion (org-end-of-item) (point)))
21563 clist)
21564 (and (org-at-item-checkbox-p)
21565 (push (org-point-in-group p 0 :checkbox) clist)))
21567 ((org-at-table-p)
21568 (push (list :table (org-table-begin) (org-table-end)) clist)
21569 (when (memq 'org-formula faces)
21570 (push (list :table-special
21571 (previous-single-property-change p 'face)
21572 (next-single-property-change p 'face)) clist)))
21573 ((org-at-table-p 'any)
21574 (push (list :table-table) clist)))
21575 (goto-char p)
21577 (let ((case-fold-search t))
21578 ;; New the "medium" contexts: clocktables, source blocks
21579 (cond ((org-in-clocktable-p)
21580 (push (list :clocktable
21581 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21582 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21583 (match-beginning 1))
21584 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21585 (match-end 0))) clist))
21586 ((org-in-src-block-p)
21587 (push (list :src-block
21588 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21589 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21590 (match-beginning 1))
21591 (and (search-forward "#+END_SRC" nil t)
21592 (match-beginning 0))) clist))))
21593 (goto-char p)
21595 ;; Now the small context
21596 (cond
21597 ((org-at-timestamp-p)
21598 (push (org-point-in-group p 0 :timestamp) clist))
21599 ((memq 'org-link faces)
21600 (push (list :link
21601 (previous-single-property-change p 'face)
21602 (next-single-property-change p 'face)) clist))
21603 ((memq 'org-special-keyword faces)
21604 (push (list :keyword
21605 (previous-single-property-change p 'face)
21606 (next-single-property-change p 'face)) clist))
21607 ((org-at-target-p)
21608 (push (org-point-in-group p 0 :target) clist)
21609 (goto-char (1- (match-beginning 0)))
21610 (when (looking-at org-radio-target-regexp)
21611 (push (org-point-in-group p 0 :radio-target) clist))
21612 (goto-char p))
21613 ((setq o (cl-some
21614 (lambda (o)
21615 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21617 (overlays-at (point))))
21618 (push (list :latex-fragment
21619 (overlay-start o) (overlay-end o)) clist)
21620 (push (list :latex-preview
21621 (overlay-start o) (overlay-end o)) clist))
21622 ((org-inside-LaTeX-fragment-p)
21623 ;; FIXME: positions wrong.
21624 (push (list :latex-fragment (point) (point)) clist)))
21626 (setq clist (nreverse (delq nil clist)))
21627 clist))
21629 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21630 "Non-nil when point is between matches of START-RE and END-RE.
21632 Also return a non-nil value when point is on one of the matches.
21634 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21635 buffer positions. Default values are the positions of headlines
21636 surrounding the point.
21638 The functions returns a cons cell whose car (resp. cdr) is the
21639 position before START-RE (resp. after END-RE)."
21640 (save-match-data
21641 (let ((pos (point))
21642 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21643 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21644 beg end)
21645 (save-excursion
21646 ;; Point is on a block when on START-RE or if START-RE can be
21647 ;; found before it...
21648 (and (or (org-in-regexp start-re)
21649 (re-search-backward start-re limit-up t))
21650 (setq beg (match-beginning 0))
21651 ;; ... and END-RE after it...
21652 (goto-char (match-end 0))
21653 (re-search-forward end-re limit-down t)
21654 (> (setq end (match-end 0)) pos)
21655 ;; ... without another START-RE in-between.
21656 (goto-char (match-beginning 0))
21657 (not (re-search-backward start-re (1+ beg) t))
21658 ;; Return value.
21659 (cons beg end))))))
21661 (defun org-in-block-p (names)
21662 "Non-nil when point belongs to a block whose name belongs to NAMES.
21664 NAMES is a list of strings containing names of blocks.
21666 Return first block name matched, or nil. Beware that in case of
21667 nested blocks, the returned name may not belong to the closest
21668 block from point."
21669 (save-match-data
21670 (catch 'exit
21671 (let ((case-fold-search t)
21672 (lim-up (save-excursion (outline-previous-heading)))
21673 (lim-down (save-excursion (outline-next-heading))))
21674 (dolist (name names)
21675 (let ((n (regexp-quote name)))
21676 (when (org-between-regexps-p
21677 (concat "^[ \t]*#\\+begin_" n)
21678 (concat "^[ \t]*#\\+end_" n)
21679 lim-up lim-down)
21680 (throw 'exit n)))))
21681 nil)))
21683 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21684 "Call `multi-occur' with buffers for all agenda files."
21685 (interactive "sOrg-files matching: ")
21686 (let* ((files (org-agenda-files))
21687 (tnames (mapcar #'file-truename files))
21688 (extra org-agenda-text-search-extra-files))
21689 (when (eq (car extra) 'agenda-archives)
21690 (setq extra (cdr extra))
21691 (setq files (org-add-archive-files files)))
21692 (dolist (f extra)
21693 (unless (member (file-truename f) tnames)
21694 (unless (member f files) (setq files (append files (list f))))
21695 (setq tnames (append tnames (list (file-truename f))))))
21696 (multi-occur
21697 (mapcar (lambda (x)
21698 (with-current-buffer
21699 ;; FIXME: Why not just (find-file-noselect x)?
21700 ;; Is it to avoid the "revert buffer" prompt?
21701 (or (get-file-buffer x) (find-file-noselect x))
21702 (widen)
21703 (current-buffer)))
21704 files)
21705 regexp)))
21707 (add-hook 'occur-mode-find-occurrence-hook
21708 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21710 (defun org-occur-link-in-agenda-files ()
21711 "Create a link and search for it in the agendas.
21712 The link is not stored in `org-stored-links', it is just created
21713 for the search purpose."
21714 (interactive)
21715 (let ((link (condition-case nil
21716 (org-store-link nil)
21717 (error "Unable to create a link to here"))))
21718 (org-occur-in-agenda-files (regexp-quote link))))
21720 (defun org-back-over-empty-lines ()
21721 "Move backwards over whitespace, to the beginning of the first empty line.
21722 Returns the number of empty lines passed."
21723 (let ((pos (point)))
21724 (if (cdr (assq 'heading org-blank-before-new-entry))
21725 (skip-chars-backward " \t\n\r")
21726 (unless (eobp)
21727 (forward-line -1)))
21728 (beginning-of-line 2)
21729 (goto-char (min (point) pos))
21730 (count-lines (point) pos)))
21732 (defun org-switch-to-buffer-other-window (&rest args)
21733 "Switch to buffer in a second window on the current frame.
21734 In particular, do not allow pop-up frames.
21735 Returns the newly created buffer."
21736 (org-no-popups
21737 (apply 'switch-to-buffer-other-window args)))
21739 (defun org-replace-escapes (string table)
21740 "Replace %-escapes in STRING with values in TABLE.
21741 TABLE is an association list with keys like \"%a\" and string values.
21742 The sequences in STRING may contain normal field width and padding information,
21743 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21744 so values can contain further %-escapes if they are define later in TABLE."
21745 (let ((tbl (copy-alist table))
21746 (case-fold-search nil)
21747 (pchg 0)
21748 re rpl)
21749 (dolist (e tbl)
21750 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21751 (when (and (cdr e) (string-match re (cdr e)))
21752 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21753 (safe "SREF"))
21754 (add-text-properties 0 3 (list 'sref sref) safe)
21755 (setcdr e (replace-match safe t t (cdr e)))))
21756 (while (string-match re string)
21757 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21758 (cdr e)))
21759 (setq string (replace-match rpl t t string))))
21760 (while (setq pchg (next-property-change pchg string))
21761 (let ((sref (get-text-property pchg 'sref string)))
21762 (when (and sref (string-match "SREF" string pchg))
21763 (setq string (replace-match sref t t string)))))
21764 string))
21766 ;;; TODO: Only called once, from ox-odt which should probably use
21767 ;;; org-export-inline-image-p or something.
21768 (defun org-file-image-p (file)
21769 "Return non-nil if FILE is an image."
21770 (save-match-data
21771 (string-match (image-file-name-regexp) file)))
21773 (defun org-get-cursor-date (&optional with-time)
21774 "Return the date at cursor in as a time.
21775 This works in the calendar and in the agenda, anywhere else it just
21776 returns the current time.
21777 If WITH-TIME is non-nil, returns the time of the event at point (in
21778 the agenda) or the current time of the day."
21779 (let (date day defd tp hod mod)
21780 (when with-time
21781 (setq tp (get-text-property (point) 'time))
21782 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21783 (setq hod (string-to-number (match-string 1 tp))
21784 mod (string-to-number (match-string 2 tp))))
21785 (or tp (let ((now (decode-time)))
21786 (setq hod (nth 2 now)
21787 mod (nth 1 now)))))
21788 (cond
21789 ((eq major-mode 'calendar-mode)
21790 (setq date (calendar-cursor-to-date)
21791 defd (encode-time 0 (or mod 0) (or hod 0)
21792 (nth 1 date) (nth 0 date) (nth 2 date))))
21793 ((eq major-mode 'org-agenda-mode)
21794 (setq day (get-text-property (point) 'day))
21795 (when day
21796 (setq date (calendar-gregorian-from-absolute day)
21797 defd (encode-time 0 (or mod 0) (or hod 0)
21798 (nth 1 date) (nth 0 date) (nth 2 date))))))
21799 (or defd (current-time))))
21801 (defun org-mark-subtree (&optional up)
21802 "Mark the current subtree.
21803 This puts point at the start of the current subtree, and mark at
21804 the end. If a numeric prefix UP is given, move up into the
21805 hierarchy of headlines by UP levels before marking the subtree."
21806 (interactive "P")
21807 (org-with-limited-levels
21808 (cond ((org-at-heading-p) (beginning-of-line))
21809 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21810 (t (outline-previous-visible-heading 1))))
21811 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21812 (if (called-interactively-p 'any)
21813 (call-interactively 'org-mark-element)
21814 (org-mark-element)))
21816 (defun org-file-newer-than-p (file time)
21817 "Non-nil if FILE is newer than TIME.
21818 FILE is a filename, as a string, TIME is a list of integers, as
21819 returned by, e.g., `current-time'."
21820 (and (file-exists-p file)
21821 ;; Only compare times up to whole seconds as some file-systems
21822 ;; (e.g. HFS+) do not retain any finer granularity. As
21823 ;; a consequence, make sure we return non-nil when the two
21824 ;; times are equal.
21825 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21826 (cl-subseq time 0 2)))))
21828 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21829 "Compile a SOURCE file using PROCESS.
21831 PROCESS is either a function or a list of shell commands, as
21832 strings. EXT is a file extension, without the leading dot, as
21833 a string. It is used to check if the process actually succeeded.
21835 PROCESS must create a file with the same base name and directory
21836 as SOURCE, but ending with EXT. The function then returns its
21837 filename. Otherwise, it raises an error. The error message can
21838 then be refined by providing string ERR-MSG, which is appended to
21839 the standard message.
21841 If PROCESS is a function, it is called with a single argument:
21842 the SOURCE file.
21844 If it is a list of commands, each of them is called using
21845 `shell-command'. By default, in each command, %b, %f, %F, %o and
21846 %O are replaced with, respectively, SOURCE base name, name, full
21847 name, directory and absolute output file name. It is possible,
21848 however, to use more place-holders by specifying them in optional
21849 argument SPEC, as an alist following the pattern
21851 (CHARACTER . REPLACEMENT-STRING).
21853 When PROCESS is a list of commands, optional argument LOG-BUF can
21854 be set to a buffer or a buffer name. `shell-command' then uses
21855 it for output."
21856 (let* ((base-name (file-name-base source))
21857 (full-name (file-truename source))
21858 (out-dir (or (file-name-directory source) "./"))
21859 (output (expand-file-name (concat base-name "." ext) out-dir))
21860 (time (current-time))
21861 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21862 (save-window-excursion
21863 (pcase process
21864 ((pred functionp) (funcall process (shell-quote-argument source)))
21865 ((pred consp)
21866 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21867 (spec (append spec
21868 `((?b . ,(shell-quote-argument base-name))
21869 (?f . ,(shell-quote-argument source))
21870 (?F . ,(shell-quote-argument full-name))
21871 (?o . ,(shell-quote-argument out-dir))
21872 (?O . ,(shell-quote-argument output))))))
21873 (dolist (command process)
21874 (shell-command (format-spec command spec) log-buf))
21875 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21876 (_ (error "No valid command to process %S%s" source err-msg))))
21877 ;; Check for process failure. Output file is expected to be
21878 ;; located in the same directory as SOURCE.
21879 (unless (org-file-newer-than-p output time)
21880 (error (format "File %S wasn't produced%s" output err-msg)))
21881 output))
21883 ;;; Indentation
21885 (defvar org-element-greater-elements)
21886 (defun org--get-expected-indentation (element contentsp)
21887 "Expected indentation column for current line, according to ELEMENT.
21888 ELEMENT is an element containing point. CONTENTSP is non-nil
21889 when indentation is to be computed according to contents of
21890 ELEMENT."
21891 (let ((type (org-element-type element))
21892 (start (org-element-property :begin element))
21893 (post-affiliated (org-element-property :post-affiliated element)))
21894 (org-with-wide-buffer
21895 (cond
21896 (contentsp
21897 (cl-case type
21898 ((diary-sexp footnote-definition) 0)
21899 ((headline inlinetask nil)
21900 (if (not org-adapt-indentation) 0
21901 (let ((level (org-current-level)))
21902 (if level (1+ level) 0))))
21903 ((item plain-list) (org-list-item-body-column post-affiliated))
21905 (goto-char start)
21906 (org-get-indentation))))
21907 ((memq type '(headline inlinetask nil))
21908 (if (org-match-line "[ \t]*$")
21909 (org--get-expected-indentation element t)
21911 ((memq type '(diary-sexp footnote-definition)) 0)
21912 ;; First paragraph of a footnote definition or an item.
21913 ;; Indent like parent.
21914 ((< (line-beginning-position) start)
21915 (org--get-expected-indentation
21916 (org-element-property :parent element) t))
21917 ;; At first line: indent according to previous sibling, if any,
21918 ;; ignoring footnote definitions and inline tasks, or parent's
21919 ;; contents.
21920 ((= (line-beginning-position) start)
21921 (catch 'exit
21922 (while t
21923 (if (= (point-min) start) (throw 'exit 0)
21924 (goto-char (1- start))
21925 (let* ((previous (org-element-at-point))
21926 (parent previous))
21927 (while (and parent (<= (org-element-property :end parent) start))
21928 (setq previous parent
21929 parent (org-element-property :parent parent)))
21930 (cond
21931 ((not previous) (throw 'exit 0))
21932 ((> (org-element-property :end previous) start)
21933 (throw 'exit (org--get-expected-indentation previous t)))
21934 ((memq (org-element-type previous)
21935 '(footnote-definition inlinetask))
21936 (setq start (org-element-property :begin previous)))
21937 (t (goto-char (org-element-property :begin previous))
21938 (throw 'exit
21939 (if (bolp) (org-get-indentation)
21940 ;; At first paragraph in an item or
21941 ;; a footnote definition.
21942 (org--get-expected-indentation
21943 (org-element-property :parent previous) t))))))))))
21944 ;; Otherwise, move to the first non-blank line above.
21946 (beginning-of-line)
21947 (let ((pos (point)))
21948 (skip-chars-backward " \r\t\n")
21949 (cond
21950 ;; Two blank lines end a footnote definition or a plain
21951 ;; list. When we indent an empty line after them, the
21952 ;; containing list or footnote definition is over, so it
21953 ;; qualifies as a previous sibling. Therefore, we indent
21954 ;; like its first line.
21955 ((and (memq type '(footnote-definition plain-list))
21956 (> (count-lines (point) pos) 2))
21957 (goto-char start)
21958 (org-get-indentation))
21959 ;; Line above is the first one of a paragraph at the
21960 ;; beginning of an item or a footnote definition. Indent
21961 ;; like parent.
21962 ((< (line-beginning-position) start)
21963 (org--get-expected-indentation
21964 (org-element-property :parent element) t))
21965 ;; Line above is the beginning of an element, i.e., point
21966 ;; was originally on the blank lines between element's start
21967 ;; and contents.
21968 ((= (line-beginning-position) post-affiliated)
21969 (org--get-expected-indentation element t))
21970 ;; POS is after contents in a greater element. Indent like
21971 ;; the beginning of the element.
21972 ((and (memq type org-element-greater-elements)
21973 (let ((cend (org-element-property :contents-end element)))
21974 (and cend (<= cend pos))))
21975 ;; As a special case, if point is at the end of a footnote
21976 ;; definition or an item, indent like the very last element
21977 ;; within. If that last element is an item, indent like
21978 ;; its contents.
21979 (if (memq type '(footnote-definition item plain-list))
21980 (let ((last (org-element-at-point)))
21981 (goto-char pos)
21982 (org--get-expected-indentation
21983 last (eq (org-element-type last) 'item)))
21984 (goto-char start)
21985 (org-get-indentation)))
21986 ;; In any other case, indent like the current line.
21987 (t (org-get-indentation)))))))))
21989 (defun org--align-node-property ()
21990 "Align node property at point.
21991 Alignment is done according to `org-property-format', which see."
21992 (when (save-excursion
21993 (beginning-of-line)
21994 (looking-at org-property-re))
21995 (replace-match
21996 (concat (match-string 4)
21997 (org-trim
21998 (format org-property-format (match-string 1) (match-string 3))))
21999 t t)))
22001 (defun org-indent-line ()
22002 "Indent line depending on context.
22004 Indentation is done according to the following rules:
22006 - Footnote definitions, diary sexps, headlines and inline tasks
22007 have to start at column 0.
22009 - On the very first line of an element, consider, in order, the
22010 next rules until one matches:
22012 1. If there's a sibling element before, ignoring footnote
22013 definitions and inline tasks, indent like its first line.
22015 2. If element has a parent, indent like its contents. More
22016 precisely, if parent is an item, indent after the
22017 description part, if any, or the bullet (see
22018 `org-list-description-max-indent'). Else, indent like
22019 parent's first line.
22021 3. Otherwise, indent relatively to current level, if
22022 `org-adapt-indentation' is non-nil, or to left margin.
22024 - On a blank line at the end of an element, indent according to
22025 the type of the element. More precisely
22027 1. If element is a plain list, an item, or a footnote
22028 definition, indent like the very last element within.
22030 2. If element is a paragraph, indent like its last non blank
22031 line.
22033 3. Otherwise, indent like its very first line.
22035 - In the code part of a source block, use language major mode
22036 to indent current line if `org-src-tab-acts-natively' is
22037 non-nil. If it is nil, do nothing.
22039 - Otherwise, indent like the first non-blank line above.
22041 The function doesn't indent an item as it could break the whole
22042 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22043 `\\[org-shiftmetaright]'.
22045 Also align node properties according to `org-property-format'."
22046 (interactive)
22047 (cond
22048 (orgstruct-is-++
22049 (let ((indent-line-function
22050 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22051 (indent-according-to-mode)))
22052 ((org-at-heading-p) 'noindent)
22054 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22055 (type (org-element-type element)))
22056 (cond ((and (memq type '(plain-list item))
22057 (= (line-beginning-position)
22058 (org-element-property :post-affiliated element)))
22059 'noindent)
22060 ((and (eq type 'latex-environment)
22061 (>= (point) (org-element-property :post-affiliated element))
22062 (< (point) (org-with-wide-buffer
22063 (goto-char (org-element-property :end element))
22064 (skip-chars-backward " \r\t\n")
22065 (line-beginning-position 2))))
22066 'noindent)
22067 ((and (eq type 'src-block)
22068 org-src-tab-acts-natively
22069 (> (line-beginning-position)
22070 (org-element-property :post-affiliated element))
22071 (< (line-beginning-position)
22072 (org-with-wide-buffer
22073 (goto-char (org-element-property :end element))
22074 (skip-chars-backward " \r\t\n")
22075 (line-beginning-position))))
22076 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22078 (let ((column (org--get-expected-indentation element nil)))
22079 ;; Preserve current column.
22080 (if (<= (current-column) (current-indentation))
22081 (indent-line-to column)
22082 (save-excursion (indent-line-to column))))
22083 ;; Align node property. Also preserve current column.
22084 (when (eq type 'node-property)
22085 (let ((column (current-column)))
22086 (org--align-node-property)
22087 (org-move-to-column column)))))))))
22089 (defun org-indent-region (start end)
22090 "Indent each non-blank line in the region.
22091 Called from a program, START and END specify the region to
22092 indent. The function will not indent contents of example blocks,
22093 verse blocks and export blocks as leading white spaces are
22094 assumed to be significant there."
22095 (interactive "r")
22096 (save-excursion
22097 (goto-char start)
22098 (skip-chars-forward " \r\t\n")
22099 (unless (eobp) (beginning-of-line))
22100 (let ((indent-to
22101 (lambda (ind pos)
22102 ;; Set IND as indentation for all lines between point and
22103 ;; POS. Blank lines are ignored. Leave point after POS
22104 ;; once done.
22105 (let ((limit (copy-marker pos)))
22106 (while (< (point) limit)
22107 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22108 (forward-line))
22109 (set-marker limit nil))))
22110 (end (copy-marker end)))
22111 (while (< (point) end)
22112 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22113 (let* ((element (org-element-at-point))
22114 (type (org-element-type element))
22115 (element-end (copy-marker (org-element-property :end element)))
22116 (ind (org--get-expected-indentation element nil)))
22117 (cond
22118 ;; Element indented as a single block. Example blocks
22119 ;; preserving indentation are a special case since the
22120 ;; "contents" must not be indented whereas the block
22121 ;; boundaries can.
22122 ((or (memq type '(export-block latex-environment))
22123 (and (eq type 'example-block)
22124 (not
22125 (or org-src-preserve-indentation
22126 (org-element-property :preserve-indent element)))))
22127 (let ((offset (- ind (org-get-indentation))))
22128 (unless (zerop offset)
22129 (indent-rigidly (org-element-property :begin element)
22130 (org-element-property :end element)
22131 offset)))
22132 (goto-char element-end))
22133 ;; Elements indented line wise. Be sure to exclude
22134 ;; example blocks (preserving indentation) and source
22135 ;; blocks from this category as they are treated
22136 ;; specially later.
22137 ((or (memq type '(paragraph table table-row))
22138 (not (or (org-element-property :contents-begin element)
22139 (memq type '(example-block src-block)))))
22140 (when (eq type 'node-property)
22141 (org--align-node-property)
22142 (beginning-of-line))
22143 (funcall indent-to ind (min element-end end)))
22144 ;; Elements consisting of three parts: before the
22145 ;; contents, the contents, and after the contents. The
22146 ;; contents are treated specially, according to the
22147 ;; element type, or not indented at all. Other parts are
22148 ;; indented as a single block.
22150 (let* ((post (copy-marker
22151 (org-element-property :post-affiliated element)))
22152 (cbeg
22153 (copy-marker
22154 (cond
22155 ((not (org-element-property :contents-begin element))
22156 ;; Fake contents for source blocks.
22157 (org-with-wide-buffer
22158 (goto-char post)
22159 (line-beginning-position 2)))
22160 ((memq type '(footnote-definition item plain-list))
22161 ;; Contents in these elements could start on
22162 ;; the same line as the beginning of the
22163 ;; element. Make sure we start indenting
22164 ;; from the second line.
22165 (org-with-wide-buffer
22166 (goto-char post)
22167 (end-of-line)
22168 (skip-chars-forward " \r\t\n")
22169 (if (eobp) (point) (line-beginning-position))))
22170 (t (org-element-property :contents-begin element)))))
22171 (cend (copy-marker
22172 (or (org-element-property :contents-end element)
22173 ;; Fake contents for source blocks.
22174 (org-with-wide-buffer
22175 (goto-char element-end)
22176 (skip-chars-backward " \r\t\n")
22177 (line-beginning-position)))
22178 t)))
22179 ;; Do not change items indentation individually as it
22180 ;; might break the list as a whole. On the other
22181 ;; hand, when at a plain list, indent it as a whole.
22182 (cond ((eq type 'plain-list)
22183 (let ((offset (- ind (org-get-indentation))))
22184 (unless (zerop offset)
22185 (indent-rigidly (org-element-property :begin element)
22186 (org-element-property :end element)
22187 offset))
22188 (goto-char cbeg)))
22189 ((eq type 'item) (goto-char cbeg))
22190 (t (funcall indent-to ind (min cbeg end))))
22191 (when (< (point) end)
22192 (cl-case type
22193 ((example-block verse-block))
22194 (src-block
22195 ;; In a source block, indent source code
22196 ;; according to language major mode, but only if
22197 ;; `org-src-tab-acts-natively' is non-nil.
22198 (when (and (< (point) end) org-src-tab-acts-natively)
22199 (ignore-errors
22200 (org-babel-do-in-edit-buffer
22201 (indent-region (point-min) (point-max))))))
22202 (t (org-indent-region (point) (min cend end))))
22203 (goto-char (min cend end))
22204 (when (< (point) end)
22205 (funcall indent-to ind (min element-end end))))
22206 (set-marker post nil)
22207 (set-marker cbeg nil)
22208 (set-marker cend nil))))
22209 (set-marker element-end nil))))
22210 (set-marker end nil))))
22212 (defun org-indent-drawer ()
22213 "Indent the drawer at point."
22214 (interactive)
22215 (unless (save-excursion
22216 (beginning-of-line)
22217 (looking-at-p org-drawer-regexp))
22218 (user-error "Not at a drawer"))
22219 (let ((element (org-element-at-point)))
22220 (unless (memq (org-element-type element) '(drawer property-drawer))
22221 (user-error "Not at a drawer"))
22222 (org-with-wide-buffer
22223 (org-indent-region (org-element-property :begin element)
22224 (org-element-property :end element))))
22225 (message "Drawer at point indented"))
22227 (defun org-indent-block ()
22228 "Indent the block at point."
22229 (interactive)
22230 (unless (save-excursion
22231 (beginning-of-line)
22232 (let ((case-fold-search t))
22233 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22234 (user-error "Not at a block"))
22235 (let ((element (org-element-at-point)))
22236 (unless (memq (org-element-type element)
22237 '(comment-block center-block dynamic-block example-block
22238 export-block quote-block special-block
22239 src-block verse-block))
22240 (user-error "Not at a block"))
22241 (org-with-wide-buffer
22242 (org-indent-region (org-element-property :begin element)
22243 (org-element-property :end element))))
22244 (message "Block at point indented"))
22247 ;;; Filling
22249 ;; We use our own fill-paragraph and auto-fill functions.
22251 ;; `org-fill-paragraph' relies on adaptive filling and context
22252 ;; checking. Appropriate `fill-prefix' is computed with
22253 ;; `org-adaptive-fill-function'.
22255 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22256 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22257 ;; `org-adaptive-fill-function' value. Internally,
22258 ;; `org-comment-line-break-function' breaks the line.
22260 ;; `org-setup-filling' installs filling and auto-filling related
22261 ;; variables during `org-mode' initialization.
22263 (defvar org-element-paragraph-separate) ; org-element.el
22264 (defun org-setup-filling ()
22265 (require 'org-element)
22266 ;; Prevent auto-fill from inserting unwanted new items.
22267 (when (boundp 'fill-nobreak-predicate)
22268 (setq-local
22269 fill-nobreak-predicate
22270 (org-uniquify
22271 (append fill-nobreak-predicate
22272 '(org-fill-line-break-nobreak-p
22273 org-fill-n-macro-as-item-nobreak-p
22274 org-fill-paragraph-with-timestamp-nobreak-p)))))
22275 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22276 (setq-local paragraph-start paragraph-ending)
22277 (setq-local paragraph-separate paragraph-ending))
22278 (setq-local fill-paragraph-function 'org-fill-paragraph)
22279 (setq-local auto-fill-inhibit-regexp nil)
22280 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22281 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22282 (setq-local comment-line-break-function 'org-comment-line-break-function))
22284 (defun org-fill-line-break-nobreak-p ()
22285 "Non-nil when a new line at point would create an Org line break."
22286 (save-excursion
22287 (skip-chars-backward "[ \t]")
22288 (skip-chars-backward "\\\\")
22289 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22291 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22292 "Non-nil when a new line at point would split a timestamp."
22293 (and (org-at-timestamp-p 'lax)
22294 (not (looking-at org-ts-regexp-both))))
22296 (defun org-fill-n-macro-as-item-nobreak-p ()
22297 "Non-nil when a new line at point would create a new list."
22298 ;; During export, a "n" macro followed by a dot or a closing
22299 ;; parenthesis can end up being parsed as a new list item.
22300 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22302 (declare-function message-in-body-p "message" ())
22303 (defvar orgtbl-line-start-regexp) ; From org-table.el
22304 (defun org-adaptive-fill-function ()
22305 "Compute a fill prefix for the current line.
22306 Return fill prefix, as a string, or nil if current line isn't
22307 meant to be filled. For convenience, if `adaptive-fill-regexp'
22308 matches in paragraphs or comments, use it."
22309 (catch 'exit
22310 (when (derived-mode-p 'message-mode)
22311 (save-excursion
22312 (beginning-of-line)
22313 (cond ((not (message-in-body-p)) (throw 'exit nil))
22314 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22315 ((looking-at message-cite-prefix-regexp)
22316 (throw 'exit (match-string-no-properties 0)))
22317 ((looking-at org-outline-regexp)
22318 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22319 (org-with-wide-buffer
22320 (unless (org-at-heading-p)
22321 (let* ((p (line-beginning-position))
22322 (element (save-excursion
22323 (beginning-of-line)
22324 (org-element-at-point)))
22325 (type (org-element-type element))
22326 (post-affiliated (org-element-property :post-affiliated element)))
22327 (unless (< p post-affiliated)
22328 (cl-case type
22329 (comment
22330 (save-excursion
22331 (beginning-of-line)
22332 (looking-at "[ \t]*")
22333 (concat (match-string 0) "# ")))
22334 (footnote-definition "")
22335 ((item plain-list)
22336 (make-string (org-list-item-body-column post-affiliated) ?\s))
22337 (paragraph
22338 ;; Fill prefix is usually the same as the current line,
22339 ;; unless the paragraph is at the beginning of an item.
22340 (let ((parent (org-element-property :parent element)))
22341 (save-excursion
22342 (beginning-of-line)
22343 (cond ((eq (org-element-type parent) 'item)
22344 (make-string (org-list-item-body-column
22345 (org-element-property :begin parent))
22346 ?\s))
22347 ((and adaptive-fill-regexp
22348 ;; Locally disable
22349 ;; `adaptive-fill-function' to let
22350 ;; `fill-context-prefix' handle
22351 ;; `adaptive-fill-regexp' variable.
22352 (let (adaptive-fill-function)
22353 (fill-context-prefix
22354 post-affiliated
22355 (org-element-property :end element)))))
22356 ((looking-at "[ \t]+") (match-string 0))
22357 (t "")))))
22358 (comment-block
22359 ;; Only fill contents if P is within block boundaries.
22360 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22361 (forward-line)
22362 (point)))
22363 (cend (save-excursion
22364 (goto-char (org-element-property :end element))
22365 (skip-chars-backward " \r\t\n")
22366 (line-beginning-position))))
22367 (when (and (>= p cbeg) (< p cend))
22368 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22369 (match-string 0)
22370 "")))))))))))
22372 (declare-function message-goto-body "message" ())
22373 (defvar message-cite-prefix-regexp) ; From message.el
22375 (defun org-fill-element (&optional justify)
22376 "Fill element at point, when applicable.
22378 This function only applies to comment blocks, comments, example
22379 blocks and paragraphs. Also, as a special case, re-align table
22380 when point is at one.
22382 If JUSTIFY is non-nil (interactively, with prefix argument),
22383 justify as well. If `sentence-end-double-space' is non-nil, then
22384 period followed by one space does not end a sentence, so don't
22385 break a line there. The variable `fill-column' controls the
22386 width for filling.
22388 For convenience, when point is at a plain list, an item or
22389 a footnote definition, try to fill the first paragraph within."
22390 (with-syntax-table org-mode-transpose-word-syntax-table
22391 ;; Move to end of line in order to get the first paragraph within
22392 ;; a plain list or a footnote definition.
22393 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22394 ;; First check if point is in a blank line at the beginning of
22395 ;; the buffer. In that case, ignore filling.
22396 (cl-case (org-element-type element)
22397 ;; Use major mode filling function is src blocks.
22398 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22399 ;; Align Org tables, leave table.el tables as-is.
22400 (table-row (org-table-align) t)
22401 (table
22402 (when (eq (org-element-property :type element) 'org)
22403 (save-excursion
22404 (goto-char (org-element-property :post-affiliated element))
22405 (org-table-align)))
22407 (paragraph
22408 ;; Paragraphs may contain `line-break' type objects.
22409 (let ((beg (max (point-min)
22410 (org-element-property :contents-begin element)))
22411 (end (min (point-max)
22412 (org-element-property :contents-end element))))
22413 ;; Do nothing if point is at an affiliated keyword.
22414 (if (< (line-end-position) beg) t
22415 (when (derived-mode-p 'message-mode)
22416 ;; In `message-mode', do not fill following citation
22417 ;; in current paragraph nor text before message body.
22418 (let ((body-start (save-excursion (message-goto-body))))
22419 (when body-start (setq beg (max body-start beg))))
22420 (when (save-excursion
22421 (re-search-forward
22422 (concat "^" message-cite-prefix-regexp) end t))
22423 (setq end (match-beginning 0))))
22424 ;; Fill paragraph, taking line breaks into account.
22425 (save-excursion
22426 (goto-char beg)
22427 (let ((cuts (list beg)))
22428 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22429 (when (eq 'line-break
22430 (org-element-type
22431 (save-excursion (backward-char)
22432 (org-element-context))))
22433 (push (point) cuts)))
22434 (dolist (c (delq end cuts))
22435 (fill-region-as-paragraph c end justify)
22436 (setq end c))))
22437 t)))
22438 ;; Contents of `comment-block' type elements should be
22439 ;; filled as plain text, but only if point is within block
22440 ;; markers.
22441 (comment-block
22442 (let* ((case-fold-search t)
22443 (beg (save-excursion
22444 (goto-char (org-element-property :begin element))
22445 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22446 (forward-line)
22447 (point)))
22448 (end (save-excursion
22449 (goto-char (org-element-property :end element))
22450 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22451 (line-beginning-position))))
22452 (if (or (< (point) beg) (> (point) end)) t
22453 (fill-region-as-paragraph
22454 (save-excursion (end-of-line)
22455 (re-search-backward "^[ \t]*$" beg 'move)
22456 (line-beginning-position))
22457 (save-excursion (beginning-of-line)
22458 (re-search-forward "^[ \t]*$" end 'move)
22459 (line-beginning-position))
22460 justify))))
22461 ;; Fill comments.
22462 (comment
22463 (let ((begin (org-element-property :post-affiliated element))
22464 (end (org-element-property :end element)))
22465 (when (and (>= (point) begin) (<= (point) end))
22466 (let ((begin (save-excursion
22467 (end-of-line)
22468 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22469 (progn (forward-line) (point))
22470 begin)))
22471 (end (save-excursion
22472 (end-of-line)
22473 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22474 (1- (line-beginning-position))
22475 (skip-chars-backward " \r\t\n")
22476 (line-end-position)))))
22477 ;; Do not fill comments when at a blank line.
22478 (when (> end begin)
22479 (let ((fill-prefix
22480 (save-excursion
22481 (beginning-of-line)
22482 (looking-at "[ \t]*#")
22483 (let ((comment-prefix (match-string 0)))
22484 (goto-char (match-end 0))
22485 (if (looking-at adaptive-fill-regexp)
22486 (concat comment-prefix (match-string 0))
22487 (concat comment-prefix " "))))))
22488 (save-excursion
22489 (fill-region-as-paragraph begin end justify))))))
22491 ;; Ignore every other element.
22492 (otherwise t)))))
22494 (defun org-fill-paragraph (&optional justify region)
22495 "Fill element at point, when applicable.
22497 This function only applies to comment blocks, comments, example
22498 blocks and paragraphs. Also, as a special case, re-align table
22499 when point is at one.
22501 For convenience, when point is at a plain list, an item or
22502 a footnote definition, try to fill the first paragraph within.
22504 If JUSTIFY is non-nil (interactively, with prefix argument),
22505 justify as well. If `sentence-end-double-space' is non-nil, then
22506 period followed by one space does not end a sentence, so don't
22507 break a line there. The variable `fill-column' controls the
22508 width for filling.
22510 The REGION argument is non-nil if called interactively; in that
22511 case, if Transient Mark mode is enabled and the mark is active,
22512 fill each of the elements in the active region, instead of just
22513 filling the current element."
22514 (interactive (progn
22515 (barf-if-buffer-read-only)
22516 (list (if current-prefix-arg 'full) t)))
22517 (cond
22518 ((and (derived-mode-p 'message-mode)
22519 (or (not (message-in-body-p))
22520 (save-excursion (move-beginning-of-line 1)
22521 (looking-at message-cite-prefix-regexp))))
22522 ;; First ensure filling is correct in message-mode.
22523 (let ((fill-paragraph-function
22524 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22525 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22526 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22527 (paragraph-separate
22528 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22529 (fill-paragraph nil)))
22530 ((and region transient-mark-mode mark-active
22531 (not (eq (region-beginning) (region-end))))
22532 (let ((origin (point-marker))
22533 (start (region-beginning)))
22534 (unwind-protect
22535 (progn
22536 (goto-char (region-end))
22537 (while (> (point) start)
22538 (org-backward-paragraph)
22539 (org-fill-element justify)))
22540 (goto-char origin)
22541 (set-marker origin nil))))
22542 (t (org-fill-element justify))))
22543 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22545 (defun org-auto-fill-function ()
22546 "Auto-fill function."
22547 ;; Check if auto-filling is meaningful.
22548 (let ((fc (current-fill-column)))
22549 (when (and fc (> (current-column) fc))
22550 (let* ((fill-prefix (org-adaptive-fill-function))
22551 ;; Enforce empty fill prefix, if required. Otherwise, it
22552 ;; will be computed again.
22553 (adaptive-fill-mode (not (equal fill-prefix ""))))
22554 (when fill-prefix (do-auto-fill))))))
22556 (defun org-comment-line-break-function (&optional soft)
22557 "Break line at point and indent, continuing comment if within one.
22558 The inserted newline is marked hard if variable
22559 `use-hard-newlines' is true, unless optional argument SOFT is
22560 non-nil."
22561 (if soft (insert-and-inherit ?\n) (newline 1))
22562 (save-excursion (forward-char -1) (delete-horizontal-space))
22563 (delete-horizontal-space)
22564 (indent-to-left-margin)
22565 (insert-before-markers-and-inherit fill-prefix))
22568 ;;; Fixed Width Areas
22570 (defun org-toggle-fixed-width ()
22571 "Toggle fixed-width markup.
22573 Add or remove fixed-width markup on current line, whenever it
22574 makes sense. Return an error otherwise.
22576 If a region is active and if it contains only fixed-width areas
22577 or blank lines, remove all fixed-width markup in it. If the
22578 region contains anything else, convert all non-fixed-width lines
22579 to fixed-width ones.
22581 Blank lines at the end of the region are ignored unless the
22582 region only contains such lines."
22583 (interactive)
22584 (if (not (org-region-active-p))
22585 ;; No region:
22587 ;; Remove fixed width marker only in a fixed-with element.
22589 ;; Add fixed width maker in paragraphs, in blank lines after
22590 ;; elements or at the beginning of a headline or an inlinetask,
22591 ;; and before any one-line elements (e.g., a clock).
22592 (progn
22593 (beginning-of-line)
22594 (let* ((element (org-element-at-point))
22595 (type (org-element-type element)))
22596 (cond
22597 ((and (eq type 'fixed-width)
22598 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22599 (replace-match
22600 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22601 ((and (memq type '(babel-call clock comment diary-sexp headline
22602 horizontal-rule keyword paragraph
22603 planning))
22604 (<= (org-element-property :post-affiliated element) (point)))
22605 (skip-chars-forward " \t")
22606 (insert ": "))
22607 ((and (looking-at-p "[ \t]*$")
22608 (or (eq type 'inlinetask)
22609 (save-excursion
22610 (skip-chars-forward " \r\t\n")
22611 (<= (org-element-property :end element) (point)))))
22612 (delete-region (point) (line-end-position))
22613 (org-indent-line)
22614 (insert ": "))
22615 (t (user-error "Cannot insert a fixed-width line here")))))
22616 ;; Region active.
22617 (let* ((begin (save-excursion
22618 (goto-char (region-beginning))
22619 (line-beginning-position)))
22620 (end (copy-marker
22621 (save-excursion
22622 (goto-char (region-end))
22623 (unless (eolp) (beginning-of-line))
22624 (if (save-excursion (re-search-backward "\\S-" begin t))
22625 (progn (skip-chars-backward " \r\t\n") (point))
22626 (point)))))
22627 (all-fixed-width-p
22628 (catch 'not-all-p
22629 (save-excursion
22630 (goto-char begin)
22631 (skip-chars-forward " \r\t\n")
22632 (when (eobp) (throw 'not-all-p nil))
22633 (while (< (point) end)
22634 (let ((element (org-element-at-point)))
22635 (if (eq (org-element-type element) 'fixed-width)
22636 (goto-char (org-element-property :end element))
22637 (throw 'not-all-p nil))))
22638 t))))
22639 (if all-fixed-width-p
22640 (save-excursion
22641 (goto-char begin)
22642 (while (< (point) end)
22643 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22644 (replace-match
22645 "" nil nil nil
22646 (if (= (line-end-position) (match-end 0)) 0 1)))
22647 (forward-line)))
22648 (let ((min-ind (point-max)))
22649 ;; Find minimum indentation across all lines.
22650 (save-excursion
22651 (goto-char begin)
22652 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22653 (setq min-ind 0)
22654 (catch 'zerop
22655 (while (< (point) end)
22656 (unless (looking-at-p "[ \t]*$")
22657 (let ((ind (org-get-indentation)))
22658 (setq min-ind (min min-ind ind))
22659 (when (zerop ind) (throw 'zerop t))))
22660 (forward-line)))))
22661 ;; Loop over all lines and add fixed-width markup everywhere
22662 ;; but in fixed-width lines.
22663 (save-excursion
22664 (goto-char begin)
22665 (while (< (point) end)
22666 (cond
22667 ((org-at-heading-p)
22668 (insert ": ")
22669 (forward-line)
22670 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22671 (insert ":")
22672 (forward-line)))
22673 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22674 (let* ((element (org-element-at-point))
22675 (element-end (org-element-property :end element)))
22676 (if (eq (org-element-type element) 'fixed-width)
22677 (progn (goto-char element-end)
22678 (skip-chars-backward " \r\t\n")
22679 (forward-line))
22680 (let ((limit (min end element-end)))
22681 (while (< (point) limit)
22682 (org-move-to-column min-ind t)
22683 (insert ": ")
22684 (forward-line))))))
22686 (org-move-to-column min-ind t)
22687 (insert ": ")
22688 (forward-line)))))))
22689 (set-marker end nil))))
22692 ;;; Comments
22694 ;; Org comments syntax is quite complex. It requires the entire line
22695 ;; to be just a comment. Also, even with the right syntax at the
22696 ;; beginning of line, some elements (e.g., verse-block or
22697 ;; example-block) don't accept comments. Usual Emacs comment commands
22698 ;; cannot cope with those requirements. Therefore, Org replaces them.
22700 ;; Org still relies on `comment-dwim', but cannot trust
22701 ;; `comment-only-p'. So, `comment-region-function' and
22702 ;; `uncomment-region-function' both point
22703 ;; to`org-comment-or-uncomment-region'. Eventually,
22704 ;; `org-insert-comment' takes care of insertion of comments at the
22705 ;; beginning of line.
22707 ;; `org-setup-comments-handling' install comments related variables
22708 ;; during `org-mode' initialization.
22710 (defun org-setup-comments-handling ()
22711 (interactive)
22712 (setq-local comment-use-syntax nil)
22713 (setq-local comment-start "# ")
22714 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22715 (setq-local comment-insert-comment-function 'org-insert-comment)
22716 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22717 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22719 (defun org-insert-comment ()
22720 "Insert an empty comment above current line.
22721 If the line is empty, insert comment at its beginning. When
22722 point is within a source block, comment according to the related
22723 major mode."
22724 (if (let ((element (org-element-at-point)))
22725 (and (eq (org-element-type element) 'src-block)
22726 (< (save-excursion
22727 (goto-char (org-element-property :post-affiliated element))
22728 (line-end-position))
22729 (point))
22730 (> (save-excursion
22731 (goto-char (org-element-property :end element))
22732 (skip-chars-backward " \r\t\n")
22733 (line-beginning-position))
22734 (point))))
22735 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22736 (beginning-of-line)
22737 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22738 (open-line 1))
22739 (org-indent-line)
22740 (insert "# ")))
22742 (defvar comment-empty-lines) ; From newcomment.el.
22743 (defun org-comment-or-uncomment-region (beg end &rest _)
22744 "Comment or uncomment each non-blank line in the region.
22745 Uncomment each non-blank line between BEG and END if it only
22746 contains commented lines. Otherwise, comment them. If region is
22747 strictly within a source block, use appropriate comment syntax."
22748 (if (let ((element (org-element-at-point)))
22749 (and (eq (org-element-type element) 'src-block)
22750 (< (save-excursion
22751 (goto-char (org-element-property :post-affiliated element))
22752 (line-end-position))
22753 beg)
22754 (>= (save-excursion
22755 (goto-char (org-element-property :end element))
22756 (skip-chars-backward " \r\t\n")
22757 (line-beginning-position))
22758 end)))
22759 ;; Translate region boundaries for the Org buffer to the source
22760 ;; buffer.
22761 (let ((offset (- end beg)))
22762 (save-excursion
22763 (goto-char beg)
22764 (org-babel-do-in-edit-buffer
22765 (comment-or-uncomment-region (point) (+ offset (point))))))
22766 (save-restriction
22767 ;; Restrict region
22768 (narrow-to-region (save-excursion (goto-char beg)
22769 (skip-chars-forward " \r\t\n" end)
22770 (line-beginning-position))
22771 (save-excursion (goto-char end)
22772 (skip-chars-backward " \r\t\n" beg)
22773 (line-end-position)))
22774 (let ((uncommentp
22775 ;; UNCOMMENTP is non-nil when every non blank line between
22776 ;; BEG and END is a comment.
22777 (save-excursion
22778 (goto-char (point-min))
22779 (while (and (not (eobp))
22780 (let ((element (org-element-at-point)))
22781 (and (eq (org-element-type element) 'comment)
22782 (goto-char (min (point-max)
22783 (org-element-property
22784 :end element)))))))
22785 (eobp))))
22786 (if uncommentp
22787 ;; Only blank lines and comments in region: uncomment it.
22788 (save-excursion
22789 (goto-char (point-min))
22790 (while (not (eobp))
22791 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22792 (replace-match "" nil nil nil 1))
22793 (forward-line)))
22794 ;; Comment each line in region.
22795 (let ((min-indent (point-max)))
22796 ;; First find the minimum indentation across all lines.
22797 (save-excursion
22798 (goto-char (point-min))
22799 (while (and (not (eobp)) (not (zerop min-indent)))
22800 (unless (looking-at "[ \t]*$")
22801 (setq min-indent (min min-indent (current-indentation))))
22802 (forward-line)))
22803 ;; Then loop over all lines.
22804 (save-excursion
22805 (goto-char (point-min))
22806 (while (not (eobp))
22807 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22808 ;; Don't get fooled by invisible text (e.g. link path)
22809 ;; when moving to column MIN-INDENT.
22810 (let ((buffer-invisibility-spec nil))
22811 (org-move-to-column min-indent t))
22812 (insert comment-start))
22813 (forward-line)))))))))
22815 (defun org-comment-dwim (_arg)
22816 "Call `comment-dwim' within a source edit buffer if needed."
22817 (interactive "*P")
22818 (if (org-in-src-block-p)
22819 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22820 (call-interactively 'comment-dwim)))
22823 ;;; Timestamps API
22825 ;; This section contains tools to operate on timestamp objects, as
22826 ;; returned by, e.g. `org-element-context'.
22828 (defun org-timestamp--to-internal-time (timestamp &optional end)
22829 "Encode TIMESTAMP object into Emacs internal time.
22830 Use end of date range or time range when END is non-nil."
22831 (apply #'encode-time
22832 (cons 0
22833 (mapcar
22834 (lambda (prop) (or (org-element-property prop timestamp) 0))
22835 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22836 '(:minute-start :hour-start :day-start :month-start
22837 :year-start))))))
22839 (defun org-timestamp-has-time-p (timestamp)
22840 "Non-nil when TIMESTAMP has a time specified."
22841 (org-element-property :hour-start timestamp))
22843 (defun org-timestamp-format (timestamp format &optional end utc)
22844 "Format a TIMESTAMP object into a string.
22846 FORMAT is a format specifier to be passed to
22847 `format-time-string'.
22849 When optional argument END is non-nil, use end of date-range or
22850 time-range, if possible.
22852 When optional argument UTC is non-nil, time will be expressed as
22853 Universal Time."
22854 (format-time-string
22855 format (org-timestamp--to-internal-time timestamp end)
22856 (and utc t)))
22858 (defun org-timestamp-split-range (timestamp &optional end)
22859 "Extract a TIMESTAMP object from a date or time range.
22861 END, when non-nil, means extract the end of the range.
22862 Otherwise, extract its start.
22864 Return a new timestamp object."
22865 (let ((type (org-element-property :type timestamp)))
22866 (if (memq type '(active inactive diary)) timestamp
22867 (let ((split-ts (org-element-copy timestamp)))
22868 ;; Set new type.
22869 (org-element-put-property
22870 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22871 ;; Copy start properties over end properties if END is
22872 ;; non-nil. Otherwise, copy end properties over `start' ones.
22873 (let ((p-alist '((:minute-start . :minute-end)
22874 (:hour-start . :hour-end)
22875 (:day-start . :day-end)
22876 (:month-start . :month-end)
22877 (:year-start . :year-end))))
22878 (dolist (p-cell p-alist)
22879 (org-element-put-property
22880 split-ts
22881 (funcall (if end #'car #'cdr) p-cell)
22882 (org-element-property
22883 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22884 ;; Eventually refresh `:raw-value'.
22885 (org-element-put-property split-ts :raw-value nil)
22886 (org-element-put-property
22887 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22889 (defun org-timestamp-translate (timestamp &optional boundary)
22890 "Translate TIMESTAMP object to custom format.
22892 Format string is defined in `org-time-stamp-custom-formats',
22893 which see.
22895 When optional argument BOUNDARY is non-nil, it is either the
22896 symbol `start' or `end'. In this case, only translate the
22897 starting or ending part of TIMESTAMP if it is a date or time
22898 range. Otherwise, translate both parts.
22900 Return timestamp as-is if `org-display-custom-times' is nil or if
22901 it has a `diary' type."
22902 (let ((type (org-element-property :type timestamp)))
22903 (if (or (not org-display-custom-times) (eq type 'diary))
22904 (org-element-interpret-data timestamp)
22905 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22906 org-time-stamp-custom-formats)))
22907 (if (and (not boundary) (memq type '(active-range inactive-range)))
22908 (concat (org-timestamp-format timestamp fmt)
22909 "--"
22910 (org-timestamp-format timestamp fmt t))
22911 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22915 ;;; Other stuff.
22917 (defvar reftex-docstruct-symbol)
22918 (defvar org--rds)
22920 (defun org-reftex-citation ()
22921 "Use reftex-citation to insert a citation into the buffer.
22922 This looks for a line like
22924 #+BIBLIOGRAPHY: foo plain option:-d
22926 and derives from it that foo.bib is the bibliography file relevant
22927 for this document. It then installs the necessary environment for RefTeX
22928 to work in this buffer and calls `reftex-citation' to insert a citation
22929 into the buffer.
22931 Export of such citations to both LaTeX and HTML is handled by the contributed
22932 package ox-bibtex by Taru Karttunen."
22933 (interactive)
22934 (let ((reftex-docstruct-symbol 'org--rds)
22935 org--rds bib)
22936 (org-with-wide-buffer
22937 (let ((case-fold-search t)
22938 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22939 (if (not (save-excursion
22940 (or (re-search-forward re nil t)
22941 (re-search-backward re nil t))))
22942 (user-error "No bibliography defined in file")
22943 (setq bib (concat (match-string 1) ".bib")
22944 org--rds (list (list 'bib bib))))))
22945 (call-interactively 'reftex-citation)))
22947 ;;;; Functions extending outline functionality
22949 (defun org-beginning-of-line (&optional n)
22950 "Go to the beginning of the current visible line.
22952 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22953 tags on the first attempt, and only move to after the tags when
22954 the cursor is already beyond the end of the headline.
22956 With argument N not nil or 1, move forward N - 1 lines first."
22957 (interactive "^p")
22958 (let ((origin (point))
22959 (special (pcase org-special-ctrl-a/e
22960 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22961 deactivate-mark)
22962 ;; First move to a visible line.
22963 (if (bound-and-true-p visual-line-mode)
22964 (beginning-of-visual-line n)
22965 (move-beginning-of-line n)
22966 ;; `move-beginning-of-line' may leave point after invisible
22967 ;; characters if line starts with such of these (e.g., with
22968 ;; a link at column 0). Really move to the beginning of the
22969 ;; current visible line.
22970 (beginning-of-line))
22971 (cond
22972 ;; No special behavior. Point is already at the beginning of
22973 ;; a line, logical or visual.
22974 ((not special))
22975 ;; `beginning-of-visual-line' left point before logical beginning
22976 ;; of line: point is at the beginning of a visual line. Bail
22977 ;; out.
22978 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22979 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22980 ;; At a headline, special position is before the title, but
22981 ;; after any TODO keyword or priority cookie.
22982 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22983 (line-end-position)))
22984 (bol (point)))
22985 (if (eq special 'reversed)
22986 (when (and (= origin bol) (eq last-command this-command))
22987 (goto-char refpos))
22988 (when (or (> origin refpos) (= origin bol))
22989 (goto-char refpos)))))
22990 ((and (looking-at org-list-full-item-re)
22991 (memq (org-element-type (save-match-data (org-element-at-point)))
22992 '(item plain-list)))
22993 ;; Set special position at first white space character after
22994 ;; bullet, and check-box, if any.
22995 (let ((after-bullet
22996 (let ((box (match-end 3)))
22997 (cond ((not box) (match-end 1))
22998 ((eq (char-after box) ?\s) (1+ box))
22999 (t box)))))
23000 (if (eq special 'reversed)
23001 (when (and (= (point) origin) (eq last-command this-command))
23002 (goto-char after-bullet))
23003 (when (or (> origin after-bullet) (= (point) origin))
23004 (goto-char after-bullet)))))
23005 ;; No special context. Point is already at beginning of line.
23006 (t nil))))
23008 (defun org-end-of-line (&optional n)
23009 "Go to the end of the line, but before ellipsis, if any.
23011 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23012 tags on the first attempt, and only move to after the tags when
23013 the cursor is already beyond the end of the headline.
23015 With argument N not nil or 1, move forward N - 1 lines first."
23016 (interactive "^p")
23017 (let ((origin (point))
23018 (special (pcase org-special-ctrl-a/e
23019 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23020 deactivate-mark)
23021 ;; First move to a visible line.
23022 (if (bound-and-true-p visual-line-mode)
23023 (beginning-of-visual-line n)
23024 (move-beginning-of-line n))
23025 (cond
23026 ;; At a headline, with tags.
23027 ((and special
23028 (save-excursion
23029 (beginning-of-line)
23030 (let ((case-fold-search nil))
23031 (looking-at org-complex-heading-regexp)))
23032 (match-end 5))
23033 (let ((tags (save-excursion
23034 (goto-char (match-beginning 5))
23035 (skip-chars-backward " \t")
23036 (point)))
23037 (visual-end (and (bound-and-true-p visual-line-mode)
23038 (save-excursion
23039 (end-of-visual-line)
23040 (point)))))
23041 ;; If `end-of-visual-line' brings us before end of line or
23042 ;; even tags, i.e., the headline spans over multiple visual
23043 ;; lines, move there.
23044 (cond ((and visual-end
23045 (< visual-end tags)
23046 (<= origin visual-end))
23047 (goto-char visual-end))
23048 ((eq special 'reversed)
23049 (if (and (= origin (line-end-position))
23050 (eq this-command last-command))
23051 (goto-char tags)
23052 (end-of-line)))
23054 (if (or (< origin tags) (= origin (line-end-position)))
23055 (goto-char tags)
23056 (end-of-line))))))
23057 ((bound-and-true-p visual-line-mode)
23058 (let ((bol (line-beginning-position)))
23059 (end-of-visual-line)
23060 ;; If `end-of-visual-line' gets us past the ellipsis at the
23061 ;; end of a line, backtrack and use `end-of-line' instead.
23062 (when (/= bol (line-beginning-position))
23063 (goto-char bol)
23064 (end-of-line))))
23065 (t (end-of-line)))))
23067 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23068 (define-key org-mode-map "\C-e" 'org-end-of-line)
23070 (defun org-backward-sentence (&optional _arg)
23071 "Go to beginning of sentence, or beginning of table field.
23072 This will call `backward-sentence' or `org-table-beginning-of-field',
23073 depending on context."
23074 (interactive)
23075 (let* ((element (org-element-at-point))
23076 (contents-begin (org-element-property :contents-begin element))
23077 (table (org-element-lineage element '(table) t)))
23078 (if (and table
23079 (> (point) contents-begin)
23080 (<= (point) (org-element-property :contents-end table)))
23081 (call-interactively #'org-table-beginning-of-field)
23082 (save-restriction
23083 (when (and contents-begin
23084 (< (point-min) contents-begin)
23085 (> (point) contents-begin))
23086 (narrow-to-region contents-begin
23087 (org-element-property :contents-end element)))
23088 (call-interactively #'backward-sentence)))))
23090 (defun org-forward-sentence (&optional _arg)
23091 "Go to end of sentence, or end of table field.
23092 This will call `forward-sentence' or `org-table-end-of-field',
23093 depending on context."
23094 (interactive)
23095 (if (and (org-at-heading-p)
23096 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23097 (save-restriction
23098 (narrow-to-region (line-beginning-position) (line-end-position))
23099 (call-interactively #'forward-sentence))
23100 (let* ((element (org-element-at-point))
23101 (contents-end (org-element-property :contents-end element))
23102 (table (org-element-lineage element '(table) t)))
23103 (if (and table
23104 (>= (point) (org-element-property :contents-begin table))
23105 (< (point) contents-end))
23106 (call-interactively #'org-table-end-of-field)
23107 (save-restriction
23108 (when (and contents-end
23109 (> (point-max) contents-end)
23110 ;; Skip blank lines between elements.
23111 (< (org-element-property :end element)
23112 (save-excursion (goto-char contents-end)
23113 (skip-chars-forward " \r\t\n"))))
23114 (narrow-to-region (org-element-property :contents-begin element)
23115 contents-end))
23116 ;; End of heading is considered as the end of a sentence.
23117 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23118 (call-interactively #'forward-sentence)))))))
23120 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23121 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23123 (defun org-kill-line (&optional _arg)
23124 "Kill line, to tags or end of line."
23125 (interactive)
23126 (cond
23127 ((or (not org-special-ctrl-k)
23128 (bolp)
23129 (not (org-at-heading-p)))
23130 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23131 org-ctrl-k-protect-subtree
23132 (or (eq org-ctrl-k-protect-subtree 'error)
23133 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23134 (user-error "C-k aborted as it would kill a hidden subtree"))
23135 (call-interactively
23136 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23137 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23138 (kill-region (point) (match-beginning 1))
23139 (org-set-tags nil t))
23140 (t (kill-region (point) (point-at-eol)))))
23142 (define-key org-mode-map "\C-k" 'org-kill-line)
23144 (defun org-yank (&optional arg)
23145 "Yank. If the kill is a subtree, treat it specially.
23146 This command will look at the current kill and check if is a single
23147 subtree, or a series of subtrees[1]. If it passes the test, and if the
23148 cursor is at the beginning of a line or after the stars of a currently
23149 empty headline, then the yank is handled specially. How exactly depends
23150 on the value of the following variables.
23152 `org-yank-folded-subtrees'
23153 By default, this variable is non-nil, which results in
23154 subtree(s) being folded after insertion, except if doing so
23155 would swallow text after the yanked text.
23157 `org-yank-adjusted-subtrees'
23158 When non-nil (the default value is nil), the subtree will be
23159 promoted or demoted in order to fit into the local outline tree
23160 structure, which means that the level will be adjusted so that it
23161 becomes the smaller one of the two *visible* surrounding headings.
23163 Any prefix to this command will cause `yank' to be called directly with
23164 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23165 will just
23166 plainly yank the text as it is.
23168 \[1] The test checks if the first non-white line is a heading
23169 and if there are no other headings with fewer stars."
23170 (interactive "P")
23171 (org-yank-generic 'yank arg))
23173 (defun org-yank-generic (command arg)
23174 "Perform some yank-like command.
23176 This function implements the behavior described in the `org-yank'
23177 documentation. However, it has been generalized to work for any
23178 interactive command with similar behavior."
23180 ;; pretend to be command COMMAND
23181 (setq this-command command)
23183 (if arg
23184 (call-interactively command)
23186 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23187 (and (org-kill-is-subtree-p)
23188 (or (bolp)
23189 (and (looking-at "[ \t]*$")
23190 (string-match
23191 "\\`\\*+\\'"
23192 (buffer-substring (point-at-bol) (point)))))))
23193 swallowp)
23194 (cond
23195 ((and subtreep org-yank-folded-subtrees)
23196 (let ((beg (point))
23197 end)
23198 (if (and subtreep org-yank-adjusted-subtrees)
23199 (org-paste-subtree nil nil 'for-yank)
23200 (call-interactively command))
23202 (setq end (point))
23203 (goto-char beg)
23204 (when (and (bolp) subtreep
23205 (not (setq swallowp
23206 (org-yank-folding-would-swallow-text beg end))))
23207 (org-with-limited-levels
23208 (or (looking-at org-outline-regexp)
23209 (re-search-forward org-outline-regexp-bol end t))
23210 (while (and (< (point) end) (looking-at org-outline-regexp))
23211 (outline-hide-subtree)
23212 (org-cycle-show-empty-lines 'folded)
23213 (condition-case nil
23214 (outline-forward-same-level 1)
23215 (error (goto-char end))))))
23216 (when swallowp
23217 (message
23218 "Inserted text not folded because that would swallow text"))
23220 (goto-char end)
23221 (skip-chars-forward " \t\n\r")
23222 (beginning-of-line 1)
23223 (push-mark beg 'nomsg)))
23224 ((and subtreep org-yank-adjusted-subtrees)
23225 (let ((beg (point-at-bol)))
23226 (org-paste-subtree nil nil 'for-yank)
23227 (push-mark beg 'nomsg)))
23229 (call-interactively command))))))
23231 (defun org-yank-folding-would-swallow-text (beg end)
23232 "Would hide-subtree at BEG swallow any text after END?"
23233 (let (level)
23234 (org-with-limited-levels
23235 (save-excursion
23236 (goto-char beg)
23237 (when (or (looking-at org-outline-regexp)
23238 (re-search-forward org-outline-regexp-bol end t))
23239 (setq level (org-outline-level)))
23240 (goto-char end)
23241 (skip-chars-forward " \t\r\n\v\f")
23242 (not (or (eobp)
23243 (and (bolp) (looking-at-p org-outline-regexp)
23244 (<= (org-outline-level) level))))))))
23246 (define-key org-mode-map "\C-y" 'org-yank)
23248 (defun org-back-to-heading (&optional invisible-ok)
23249 "Call `outline-back-to-heading', but provide a better error message."
23250 (condition-case nil
23251 (outline-back-to-heading invisible-ok)
23252 (error (error "Before first headline at position %d in buffer %s"
23253 (point) (current-buffer)))))
23255 (defun org-before-first-heading-p ()
23256 "Before first heading?"
23257 (save-excursion
23258 (end-of-line)
23259 (null (re-search-backward org-outline-regexp-bol nil t))))
23261 (defun org-at-heading-p (&optional ignored)
23262 (outline-on-heading-p t))
23264 (defun org-in-commented-heading-p (&optional no-inheritance)
23265 "Non-nil if point is under a commented heading.
23266 This function also checks ancestors of the current headline,
23267 unless optional argument NO-INHERITANCE is non-nil."
23268 (cond
23269 ((org-before-first-heading-p) nil)
23270 ((let ((headline (nth 4 (org-heading-components))))
23271 (and headline
23272 (let ((case-fold-search nil))
23273 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23274 headline)))))
23275 (no-inheritance nil)
23277 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23279 (defun org-at-comment-p nil
23280 "Is cursor in a commented line?"
23281 (save-excursion
23282 (save-match-data
23283 (beginning-of-line)
23284 (looking-at "^[ \t]*# "))))
23286 (defun org-at-drawer-p nil
23287 "Is cursor at a drawer keyword?"
23288 (save-excursion
23289 (move-beginning-of-line 1)
23290 (looking-at org-drawer-regexp)))
23292 (defun org-at-block-p nil
23293 "Is cursor at a block keyword?"
23294 (save-excursion
23295 (move-beginning-of-line 1)
23296 (looking-at org-block-regexp)))
23298 (defun org-point-at-end-of-empty-headline ()
23299 "If point is at the end of an empty headline, return t, else nil.
23300 If the heading only contains a TODO keyword, it is still still considered
23301 empty."
23302 (let ((case-fold-search nil))
23303 (and (looking-at "[ \t]*$")
23304 org-todo-line-regexp
23305 (save-excursion
23306 (beginning-of-line)
23307 (looking-at org-todo-line-regexp)
23308 (string= (match-string 3) "")))))
23310 (defun org-at-heading-or-item-p ()
23311 (or (org-at-heading-p) (org-at-item-p)))
23313 (defun org-at-target-p ()
23314 (or (org-in-regexp org-radio-target-regexp)
23315 (org-in-regexp org-target-regexp)))
23316 ;; Compatibility alias with Org versions < 7.8.03
23317 (defalias 'org-on-target-p 'org-at-target-p)
23319 (defun org-up-heading-all (arg)
23320 "Move to the heading line of which the present line is a subheading.
23321 This function considers both visible and invisible heading lines.
23322 With argument, move up ARG levels."
23323 (outline-up-heading arg t))
23325 (defun org-up-heading-safe ()
23326 "Move to the heading line of which the present line is a subheading.
23327 This version will not throw an error. It will return the level of the
23328 headline found, or nil if no higher level is found.
23330 Also, this function will be a lot faster than `outline-up-heading',
23331 because it relies on stars being the outline starters. This can really
23332 make a significant difference in outlines with very many siblings."
23333 (when (ignore-errors (org-back-to-heading t))
23334 (let ((level-up (1- (funcall outline-level))))
23335 (and (> level-up 0)
23336 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23337 (funcall outline-level)))))
23339 (defun org-first-sibling-p ()
23340 "Is this heading the first child of its parents?"
23341 (interactive)
23342 (let ((re org-outline-regexp-bol)
23343 level l)
23344 (unless (org-at-heading-p t)
23345 (user-error "Not at a heading"))
23346 (setq level (funcall outline-level))
23347 (save-excursion
23348 (if (not (re-search-backward re nil t))
23350 (setq l (funcall outline-level))
23351 (< l level)))))
23353 (defun org-goto-sibling (&optional previous)
23354 "Goto the next sibling, even if it is invisible.
23355 When PREVIOUS is set, go to the previous sibling instead. Returns t
23356 when a sibling was found. When none is found, return nil and don't
23357 move point."
23358 (let ((fun (if previous 're-search-backward 're-search-forward))
23359 (pos (point))
23360 (re org-outline-regexp-bol)
23361 level l)
23362 (when (ignore-errors (org-back-to-heading t))
23363 (setq level (funcall outline-level))
23364 (catch 'exit
23365 (or previous (forward-char 1))
23366 (while (funcall fun re nil t)
23367 (setq l (funcall outline-level))
23368 (when (< l level) (goto-char pos) (throw 'exit nil))
23369 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23370 (goto-char pos)
23371 nil))))
23373 (defun org-show-siblings ()
23374 "Show all siblings of the current headline."
23375 (save-excursion
23376 (while (org-goto-sibling) (org-flag-heading nil)))
23377 (save-excursion
23378 (while (org-goto-sibling 'previous)
23379 (org-flag-heading nil))))
23381 (defun org-goto-first-child ()
23382 "Goto the first child, even if it is invisible.
23383 Return t when a child was found. Otherwise don't move point and
23384 return nil."
23385 (let (level (pos (point)) (re org-outline-regexp-bol))
23386 (when (ignore-errors (org-back-to-heading t))
23387 (setq level (outline-level))
23388 (forward-char 1)
23389 (if (and (re-search-forward re nil t) (> (outline-level) level))
23390 (progn (goto-char (match-beginning 0)) t)
23391 (goto-char pos) nil))))
23393 (defun org-show-hidden-entry ()
23394 "Show an entry where even the heading is hidden."
23395 (save-excursion
23396 (org-show-entry)))
23398 (defun org-flag-heading (flag &optional entry)
23399 "Flag the current heading. FLAG non-nil means make invisible.
23400 When ENTRY is non-nil, show the entire entry."
23401 (save-excursion
23402 (org-back-to-heading t)
23403 ;; Check if we should show the entire entry
23404 (if entry
23405 (progn
23406 (org-show-entry)
23407 (save-excursion
23408 (and (outline-next-heading)
23409 (org-flag-heading nil))))
23410 (outline-flag-region (max (point-min) (1- (point)))
23411 (save-excursion (outline-end-of-heading) (point))
23412 flag))))
23414 (defun org-get-next-sibling ()
23415 "Move to next heading of the same level, and return point.
23416 If there is no such heading, return nil.
23417 This is like outline-next-sibling, but invisible headings are ok."
23418 (let ((level (funcall outline-level)))
23419 (outline-next-heading)
23420 (while (and (not (eobp)) (> (funcall outline-level) level))
23421 (outline-next-heading))
23422 (unless (or (eobp) (< (funcall outline-level) level))
23423 (point))))
23425 (defun org-get-last-sibling ()
23426 "Move to previous heading of the same level, and return point.
23427 If there is no such heading, return nil."
23428 (let ((opoint (point))
23429 (level (funcall outline-level)))
23430 (outline-previous-heading)
23431 (when (and (/= (point) opoint) (outline-on-heading-p t))
23432 (while (and (> (funcall outline-level) level)
23433 (not (bobp)))
23434 (outline-previous-heading))
23435 (unless (< (funcall outline-level) level)
23436 (point)))))
23438 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23439 "Goto to the end of a subtree."
23440 ;; This contains an exact copy of the original function, but it uses
23441 ;; `org-back-to-heading', to make it work also in invisible
23442 ;; trees. And is uses an invisible-ok argument.
23443 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23444 ;; Furthermore, when used inside Org, finding the end of a large subtree
23445 ;; with many children and grandchildren etc, this can be much faster
23446 ;; than the outline version.
23447 (org-back-to-heading invisible-ok)
23448 (let ((first t)
23449 (level (funcall outline-level)))
23450 (if (and (derived-mode-p 'org-mode) (< level 1000))
23451 ;; A true heading (not a plain list item), in Org
23452 ;; This means we can easily find the end by looking
23453 ;; only for the right number of stars. Using a regexp to do
23454 ;; this is so much faster than using a Lisp loop.
23455 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23456 (forward-char 1)
23457 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23458 ;; something else, do it the slow way
23459 (while (and (not (eobp))
23460 (or first (> (funcall outline-level) level)))
23461 (setq first nil)
23462 (outline-next-heading)))
23463 (unless to-heading
23464 (when (memq (preceding-char) '(?\n ?\^M))
23465 ;; Go to end of line before heading
23466 (forward-char -1)
23467 (when (memq (preceding-char) '(?\n ?\^M))
23468 ;; leave blank line before heading
23469 (forward-char -1)))))
23470 (point))
23472 (defun org-end-of-meta-data (&optional full)
23473 "Skip planning line and properties drawer in current entry.
23474 When optional argument FULL is non-nil, also skip empty lines,
23475 clocking lines and regular drawers at the beginning of the
23476 entry."
23477 (org-back-to-heading t)
23478 (forward-line)
23479 (when (looking-at-p org-planning-line-re) (forward-line))
23480 (when (looking-at org-property-drawer-re)
23481 (goto-char (match-end 0))
23482 (forward-line))
23483 (when (and full (not (org-at-heading-p)))
23484 (catch 'exit
23485 (let ((end (save-excursion (outline-next-heading) (point)))
23486 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23487 (while (not (eobp))
23488 (cond ((looking-at-p org-drawer-regexp)
23489 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23490 (forward-line)
23491 (throw 'exit t)))
23492 ((looking-at-p re) (forward-line))
23493 (t (throw 'exit t))))))))
23495 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23496 "Move forward to the ARG'th subheading at same level as this one.
23497 Stop at the first and last subheadings of a superior heading.
23498 Normally this only looks at visible headings, but when INVISIBLE-OK is
23499 non-nil it will also look at invisible ones."
23500 (interactive "p")
23501 (let ((backward? (and arg (< arg 0))))
23502 (if (org-before-first-heading-p)
23503 (if backward? (goto-char (point-min)) (outline-next-heading))
23504 (org-back-to-heading invisible-ok)
23505 (unless backward? (end-of-line)) ;do not match current headline
23506 (let ((level (- (match-end 0) (match-beginning 0) 1))
23507 (f (if backward? #'re-search-backward #'re-search-forward))
23508 (count (if arg (abs arg) 1))
23509 (result (point)))
23510 (while (and (> count 0)
23511 (funcall f org-outline-regexp-bol nil 'move))
23512 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23513 (cond ((< l level) (setq count 0))
23514 ((and (= l level)
23515 (or invisible-ok
23516 (not (org-invisible-p
23517 (line-beginning-position)))))
23518 (cl-decf count)
23519 (when (= l level) (setq result (point)))))))
23520 (goto-char result))
23521 (beginning-of-line))))
23523 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23524 "Move backward to the ARG'th subheading at same level as this one.
23525 Stop at the first and last subheadings of a superior heading."
23526 (interactive "p")
23527 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23529 (defun org-next-visible-heading (arg)
23530 "Move to the next visible heading.
23532 This function wraps `outline-next-visible-heading' with
23533 `org-with-limited-levels' in order to skip over inline tasks and
23534 respect customization of `org-odd-levels-only'."
23535 (interactive "p")
23536 (org-with-limited-levels
23537 (outline-next-visible-heading arg)))
23539 (defun org-previous-visible-heading (arg)
23540 "Move to the previous visible heading.
23542 This function wraps `outline-previous-visible-heading' with
23543 `org-with-limited-levels' in order to skip over inline tasks and
23544 respect customization of `org-odd-levels-only'."
23545 (interactive "p")
23546 (org-with-limited-levels
23547 (outline-previous-visible-heading arg)))
23549 (defun org-next-block (arg &optional backward block-regexp)
23550 "Jump to the next block.
23552 With a prefix argument ARG, jump forward ARG many blocks.
23554 When BACKWARD is non-nil, jump to the previous block.
23556 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23557 Match data is set according to this regexp when the function
23558 returns.
23560 Return point at beginning of the opening line of found block.
23561 Throw an error if no block is found."
23562 (interactive "p")
23563 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23564 (case-fold-search t)
23565 (search-fn (if backward #'re-search-backward #'re-search-forward))
23566 (count (or arg 1))
23567 (origin (point))
23568 last-element)
23569 (if backward (beginning-of-line) (end-of-line))
23570 (while (and (> count 0) (funcall search-fn re nil t))
23571 (let ((element (save-excursion
23572 (goto-char (match-beginning 0))
23573 (save-match-data (org-element-at-point)))))
23574 (when (and (memq (org-element-type element)
23575 '(center-block comment-block dynamic-block
23576 example-block export-block quote-block
23577 special-block src-block verse-block))
23578 (<= (match-beginning 0)
23579 (org-element-property :post-affiliated element)))
23580 (setq last-element element)
23581 (cl-decf count))))
23582 (if (= count 0)
23583 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23584 (save-match-data (org-show-context)))
23585 (goto-char origin)
23586 (user-error "No %s code blocks" (if backward "previous" "further")))))
23588 (defun org-previous-block (arg &optional block-regexp)
23589 "Jump to the previous block.
23590 With a prefix argument ARG, jump backward ARG many source blocks.
23591 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23592 (interactive "p")
23593 (org-next-block arg t block-regexp))
23595 (defun org-forward-paragraph ()
23596 "Move forward to beginning of next paragraph or equivalent.
23598 The function moves point to the beginning of the next visible
23599 structural element, which can be a paragraph, a table, a list
23600 item, etc. It also provides some special moves for convenience:
23602 - On an affiliated keyword, jump to the beginning of the
23603 relative element.
23604 - On an item or a footnote definition, move to the second
23605 element inside, if any.
23606 - On a table or a property drawer, jump after it.
23607 - On a verse or source block, stop after blank lines."
23608 (interactive)
23609 (unless (eobp)
23610 (let* ((deactivate-mark nil)
23611 (element (org-element-at-point))
23612 (type (org-element-type element))
23613 (post-affiliated (org-element-property :post-affiliated element))
23614 (contents-begin (org-element-property :contents-begin element))
23615 (contents-end (org-element-property :contents-end element))
23616 (end (let ((end (org-element-property :end element)) (parent element))
23617 (while (and (setq parent (org-element-property :parent parent))
23618 (= (org-element-property :contents-end parent) end))
23619 (setq end (org-element-property :end parent)))
23620 end)))
23621 (cond ((not element)
23622 (skip-chars-forward " \r\t\n")
23623 (or (eobp) (beginning-of-line)))
23624 ;; On affiliated keywords, move to element's beginning.
23625 ((< (point) post-affiliated)
23626 (goto-char post-affiliated))
23627 ;; At a table row, move to the end of the table. Similarly,
23628 ;; at a node property, move to the end of the property
23629 ;; drawer.
23630 ((memq type '(node-property table-row))
23631 (goto-char (org-element-property
23632 :end (org-element-property :parent element))))
23633 ((memq type '(property-drawer table)) (goto-char end))
23634 ;; Consider blank lines as separators in verse and source
23635 ;; blocks to ease editing.
23636 ((memq type '(src-block verse-block))
23637 (when (eq type 'src-block)
23638 (setq contents-end
23639 (save-excursion (goto-char end)
23640 (skip-chars-backward " \r\t\n")
23641 (line-beginning-position))))
23642 (beginning-of-line)
23643 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23644 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23645 (goto-char end)
23646 (skip-chars-forward " \r\t\n")
23647 (if (= (point) contents-end) (goto-char end)
23648 (beginning-of-line))))
23649 ;; With no contents, just skip element.
23650 ((not contents-begin) (goto-char end))
23651 ;; If contents are invisible, skip the element altogether.
23652 ((org-invisible-p (line-end-position))
23653 (cl-case type
23654 (headline
23655 (org-with-limited-levels (outline-next-visible-heading 1)))
23656 ;; At a plain list, make sure we move to the next item
23657 ;; instead of skipping the whole list.
23658 (plain-list (forward-char)
23659 (org-forward-paragraph))
23660 (otherwise (goto-char end))))
23661 ((>= (point) contents-end) (goto-char end))
23662 ((>= (point) contents-begin)
23663 ;; This can only happen on paragraphs and plain lists.
23664 (cl-case type
23665 (paragraph (goto-char end))
23666 ;; At a plain list, try to move to second element in
23667 ;; first item, if possible.
23668 (plain-list (end-of-line)
23669 (org-forward-paragraph))))
23670 ;; When contents start on the middle of a line (e.g. in
23671 ;; items and footnote definitions), try to reach first
23672 ;; element starting after current line.
23673 ((> (line-end-position) contents-begin)
23674 (end-of-line)
23675 (org-forward-paragraph))
23676 (t (goto-char contents-begin))))))
23678 (defun org-backward-paragraph ()
23679 "Move backward to start of previous paragraph or equivalent.
23681 The function moves point to the beginning of the current
23682 structural element, which can be a paragraph, a table, a list
23683 item, etc., or to the beginning of the previous visible one if
23684 point is already there. It also provides some special moves for
23685 convenience:
23687 - On an affiliated keyword, jump to the first one.
23688 - On a table or a property drawer, move to its beginning.
23689 - On comment, example, export, src and verse blocks, stop
23690 before blank lines."
23691 (interactive)
23692 (unless (bobp)
23693 (let* ((deactivate-mark nil)
23694 (element (org-element-at-point))
23695 (type (org-element-type element))
23696 (contents-end (org-element-property :contents-end element))
23697 (post-affiliated (org-element-property :post-affiliated element))
23698 (begin (org-element-property :begin element))
23699 (special? ;blocks handled specially
23700 (memq type '(comment-block example-block export-block src-block
23701 verse-block)))
23702 (contents-begin
23703 (if special?
23704 ;; These types have no proper contents. Fake line
23705 ;; below the block opening line as contents beginning.
23706 (save-excursion (goto-char begin) (line-beginning-position 2))
23707 (org-element-property :contents-begin element))))
23708 (cond
23709 ((not element) (goto-char (point-min)))
23710 ((= (point) begin)
23711 (backward-char)
23712 (org-backward-paragraph))
23713 ((<= (point) post-affiliated) (goto-char begin))
23714 ;; Special behavior: on a table or a property drawer, move to
23715 ;; its beginning.
23716 ((memq type '(node-property table-row))
23717 (goto-char (org-element-property
23718 :post-affiliated (org-element-property :parent element))))
23719 (special?
23720 (if (<= (point) contents-begin) (goto-char post-affiliated)
23721 ;; Inside a verse block, see blank lines as paragraph
23722 ;; separators.
23723 (let ((origin (point)))
23724 (skip-chars-backward " \r\t\n" contents-begin)
23725 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23726 (skip-chars-forward " \r\t\n" origin)
23727 (if (= (point) origin) (goto-char contents-begin)
23728 (beginning-of-line))))))
23729 ((eq type 'paragraph) (goto-char contents-begin)
23730 ;; When at first paragraph in an item or a footnote definition,
23731 ;; move directly to beginning of line.
23732 (let ((parent-contents
23733 (org-element-property
23734 :contents-begin (org-element-property :parent element))))
23735 (when (and parent-contents (= parent-contents contents-begin))
23736 (beginning-of-line))))
23737 ;; At the end of a greater element, move to the beginning of
23738 ;; the last element within.
23739 ((and contents-end (>= (point) contents-end))
23740 (goto-char (1- contents-end))
23741 (org-backward-paragraph))
23742 (t (goto-char (or post-affiliated begin))))
23743 ;; Ensure we never leave point invisible.
23744 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23746 (defun org-forward-element ()
23747 "Move forward by one element.
23748 Move to the next element at the same level, when possible."
23749 (interactive)
23750 (cond ((eobp) (user-error "Cannot move further down"))
23751 ((org-with-limited-levels (org-at-heading-p))
23752 (let ((origin (point)))
23753 (goto-char (org-end-of-subtree nil t))
23754 (unless (org-with-limited-levels (org-at-heading-p))
23755 (goto-char origin)
23756 (user-error "Cannot move further down"))))
23758 (let* ((elem (org-element-at-point))
23759 (end (org-element-property :end elem))
23760 (parent (org-element-property :parent elem)))
23761 (cond ((and parent (= (org-element-property :contents-end parent) end))
23762 (goto-char (org-element-property :end parent)))
23763 ((integer-or-marker-p end) (goto-char end))
23764 (t (message "No element at point")))))))
23766 (defun org-backward-element ()
23767 "Move backward by one element.
23768 Move to the previous element at the same level, when possible."
23769 (interactive)
23770 (cond ((bobp) (user-error "Cannot move further up"))
23771 ((org-with-limited-levels (org-at-heading-p))
23772 ;; At a headline, move to the previous one, if any, or stay
23773 ;; here.
23774 (let ((origin (point)))
23775 (org-with-limited-levels (org-backward-heading-same-level 1))
23776 ;; When current headline has no sibling above, move to its
23777 ;; parent.
23778 (when (= (point) origin)
23779 (or (org-with-limited-levels (org-up-heading-safe))
23780 (progn (goto-char origin)
23781 (user-error "Cannot move further up"))))))
23783 (let* ((elem (org-element-at-point))
23784 (beg (org-element-property :begin elem)))
23785 (cond
23786 ;; Move to beginning of current element if point isn't
23787 ;; there already.
23788 ((null beg) (message "No element at point"))
23789 ((/= (point) beg) (goto-char beg))
23790 (t (goto-char beg)
23791 (skip-chars-backward " \r\t\n")
23792 (unless (bobp)
23793 (let ((prev (org-element-at-point)))
23794 (goto-char (org-element-property :begin prev))
23795 (while (and (setq prev (org-element-property :parent prev))
23796 (<= (org-element-property :end prev) beg))
23797 (goto-char (org-element-property :begin prev)))))))))))
23799 (defun org-up-element ()
23800 "Move to upper element."
23801 (interactive)
23802 (if (org-with-limited-levels (org-at-heading-p))
23803 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23804 (let* ((elem (org-element-at-point))
23805 (parent (org-element-property :parent elem)))
23806 (if parent (goto-char (org-element-property :begin parent))
23807 (if (org-with-limited-levels (org-before-first-heading-p))
23808 (user-error "No surrounding element")
23809 (org-with-limited-levels (org-back-to-heading)))))))
23811 (defun org-down-element ()
23812 "Move to inner element."
23813 (interactive)
23814 (let ((element (org-element-at-point)))
23815 (cond
23816 ((memq (org-element-type element) '(plain-list table))
23817 (goto-char (org-element-property :contents-begin element))
23818 (forward-char))
23819 ((memq (org-element-type element) org-element-greater-elements)
23820 ;; If contents are hidden, first disclose them.
23821 (when (org-invisible-p (line-end-position)) (org-cycle))
23822 (goto-char (or (org-element-property :contents-begin element)
23823 (user-error "No content for this element"))))
23824 (t (user-error "No inner element")))))
23826 (defun org-drag-element-backward ()
23827 "Move backward element at point."
23828 (interactive)
23829 (let ((elem (or (org-element-at-point)
23830 (user-error "No element at point"))))
23831 (if (eq (org-element-type elem) 'headline)
23832 ;; Preserve point when moving a whole tree, even if point was
23833 ;; on blank lines below the headline.
23834 (let ((offset (skip-chars-backward " \t\n")))
23835 (unwind-protect (org-move-subtree-up)
23836 (forward-char (- offset))))
23837 (let ((prev-elem
23838 (save-excursion
23839 (goto-char (org-element-property :begin elem))
23840 (skip-chars-backward " \r\t\n")
23841 (unless (bobp)
23842 (let* ((beg (org-element-property :begin elem))
23843 (prev (org-element-at-point))
23844 (up prev))
23845 (while (and (setq up (org-element-property :parent up))
23846 (<= (org-element-property :end up) beg))
23847 (setq prev up))
23848 prev)))))
23849 ;; Error out if no previous element or previous element is
23850 ;; a parent of the current one.
23851 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23852 (user-error "Cannot drag element backward")
23853 (let ((pos (point)))
23854 (org-element-swap-A-B prev-elem elem)
23855 (goto-char (+ (org-element-property :begin prev-elem)
23856 (- pos (org-element-property :begin elem))))))))))
23858 (defun org-drag-element-forward ()
23859 "Move forward element at point."
23860 (interactive)
23861 (let* ((pos (point))
23862 (elem (or (org-element-at-point)
23863 (user-error "No element at point"))))
23864 (when (= (point-max) (org-element-property :end elem))
23865 (user-error "Cannot drag element forward"))
23866 (goto-char (org-element-property :end elem))
23867 (let ((next-elem (org-element-at-point)))
23868 (when (or (org-element-nested-p elem next-elem)
23869 (and (eq (org-element-type next-elem) 'headline)
23870 (not (eq (org-element-type elem) 'headline))))
23871 (goto-char pos)
23872 (user-error "Cannot drag element forward"))
23873 ;; Compute new position of point: it's shifted by NEXT-ELEM
23874 ;; body's length (without final blanks) and by the length of
23875 ;; blanks between ELEM and NEXT-ELEM.
23876 (let ((size-next (- (save-excursion
23877 (goto-char (org-element-property :end next-elem))
23878 (skip-chars-backward " \r\t\n")
23879 (forward-line)
23880 ;; Small correction if buffer doesn't end
23881 ;; with a newline character.
23882 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23883 (org-element-property :begin next-elem)))
23884 (size-blank (- (org-element-property :end elem)
23885 (save-excursion
23886 (goto-char (org-element-property :end elem))
23887 (skip-chars-backward " \r\t\n")
23888 (forward-line)
23889 (point)))))
23890 (org-element-swap-A-B elem next-elem)
23891 (goto-char (+ pos size-next size-blank))))))
23893 (defun org-drag-line-forward (arg)
23894 "Drag the line at point ARG lines forward."
23895 (interactive "p")
23896 (dotimes (_ (abs arg))
23897 (let ((c (current-column)))
23898 (if (< 0 arg)
23899 (progn
23900 (beginning-of-line 2)
23901 (transpose-lines 1)
23902 (beginning-of-line 0))
23903 (transpose-lines 1)
23904 (beginning-of-line -1))
23905 (org-move-to-column c))))
23907 (defun org-drag-line-backward (arg)
23908 "Drag the line at point ARG lines backward."
23909 (interactive "p")
23910 (org-drag-line-forward (- arg)))
23912 (defun org-mark-element ()
23913 "Put point at beginning of this element, mark at end.
23915 Interactively, if this command is repeated or (in Transient Mark
23916 mode) if the mark is active, it marks the next element after the
23917 ones already marked."
23918 (interactive)
23919 (let (deactivate-mark)
23920 (if (and (called-interactively-p 'any)
23921 (or (and (eq last-command this-command) (mark t))
23922 (and transient-mark-mode mark-active)))
23923 (set-mark
23924 (save-excursion
23925 (goto-char (mark))
23926 (goto-char (org-element-property :end (org-element-at-point)))))
23927 (let ((element (org-element-at-point)))
23928 (end-of-line)
23929 (push-mark (org-element-property :end element) t t)
23930 (goto-char (org-element-property :begin element))))))
23932 (defun org-narrow-to-element ()
23933 "Narrow buffer to current element."
23934 (interactive)
23935 (let ((elem (org-element-at-point)))
23936 (cond
23937 ((eq (car elem) 'headline)
23938 (narrow-to-region
23939 (org-element-property :begin elem)
23940 (org-element-property :end elem)))
23941 ((memq (car elem) org-element-greater-elements)
23942 (narrow-to-region
23943 (org-element-property :contents-begin elem)
23944 (org-element-property :contents-end elem)))
23946 (narrow-to-region
23947 (org-element-property :begin elem)
23948 (org-element-property :end elem))))))
23950 (defun org-transpose-element ()
23951 "Transpose current and previous elements, keeping blank lines between.
23952 Point is moved after both elements."
23953 (interactive)
23954 (org-skip-whitespace)
23955 (let ((end (org-element-property :end (org-element-at-point))))
23956 (org-drag-element-backward)
23957 (goto-char end)))
23959 (defun org-unindent-buffer ()
23960 "Un-indent the visible part of the buffer.
23961 Relative indentation (between items, inside blocks, etc.) isn't
23962 modified."
23963 (interactive)
23964 (unless (eq major-mode 'org-mode)
23965 (user-error "Cannot un-indent a buffer not in Org mode"))
23966 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23967 (unindent-tree
23968 (lambda (contents)
23969 (dolist (element (reverse contents))
23970 (if (memq (org-element-type element) '(headline section))
23971 (funcall unindent-tree (org-element-contents element))
23972 (save-excursion
23973 (save-restriction
23974 (narrow-to-region
23975 (org-element-property :begin element)
23976 (org-element-property :end element))
23977 (org-do-remove-indentation))))))))
23978 (funcall unindent-tree (org-element-contents parse-tree))))
23980 (defun org-show-children (&optional level)
23981 "Show all direct subheadings of this heading.
23982 Prefix arg LEVEL is how many levels below the current level
23983 should be shown. Default is enough to cause the following
23984 heading to appear."
23985 (interactive "p")
23986 ;; If `orgstruct-mode' is active, use the slower version.
23987 (if orgstruct-mode (call-interactively #'outline-show-children)
23988 (save-excursion
23989 (org-back-to-heading t)
23990 (let* ((current-level (funcall outline-level))
23991 (max-level (org-get-valid-level
23992 current-level
23993 (if level (prefix-numeric-value level) 1)))
23994 (end (save-excursion (org-end-of-subtree t t)))
23995 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
23996 (past-first-child nil)
23997 ;; Make sure to skip inlinetasks.
23998 (re (format regexp-fmt
23999 current-level
24000 (cond
24001 ((not (featurep 'org-inlinetask)) "")
24002 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24004 (t (1- org-inlinetask-min-level))))))
24005 ;; Display parent heading.
24006 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24007 (forward-line)
24008 ;; Display children. First child may be deeper than expected
24009 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24010 ;; MAX-LEVEL accordingly.
24011 (while (re-search-forward re end t)
24012 (unless past-first-child
24013 (setq re (format regexp-fmt
24014 current-level
24015 (max (funcall outline-level) max-level)))
24016 (setq past-first-child t))
24017 (outline-flag-region
24018 (line-end-position 0) (line-end-position) nil))))))
24020 (defun org-show-subtree ()
24021 "Show everything after this heading at deeper levels."
24022 (interactive)
24023 (outline-flag-region
24024 (point)
24025 (save-excursion
24026 (org-end-of-subtree t t))
24027 nil))
24029 (defun org-show-entry ()
24030 "Show the body directly following this heading.
24031 Show the heading too, if it is currently invisible."
24032 (interactive)
24033 (save-excursion
24034 (ignore-errors
24035 (org-back-to-heading t)
24036 (outline-flag-region
24037 (max (point-min) (1- (point)))
24038 (save-excursion
24039 (if (re-search-forward
24040 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24041 (match-beginning 1)
24042 (point-max)))
24043 nil)
24044 (org-cycle-hide-drawers 'children))))
24046 (defun org-make-options-regexp (kwds &optional extra)
24047 "Make a regular expression for keyword lines.
24048 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24049 when non-nil, is a regexp matching keywords names."
24050 (concat "^[ \t]*#\\+\\("
24051 (regexp-opt kwds)
24052 (and extra (concat (and kwds "\\|") extra))
24053 "\\):[ \t]*\\(.*\\)"))
24055 ;;;; Finish up
24057 (provide 'org)
24059 (run-hooks 'org-load-hook)
24061 ;;; org.el ends here