Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blobe93000418761b104ccc81f3ff65e2ae2c5eeea47
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 <http://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-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
159 (declare-function org-table-cut-region "org-table" (beg end))
160 (declare-function org-table-edit-field "org-table" (arg))
161 (declare-function org-table-end "org-table" (&optional table-type))
162 (declare-function org-table-end-of-field "org-table" (&optional n))
163 (declare-function org-table-insert-row "org-table" (&optional arg))
164 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
165 (declare-function org-table-maybe-eval-formula "org-table" ())
166 (declare-function org-table-maybe-recalculate-line "org-table" ())
167 (declare-function org-table-next-row "org-table" ())
168 (declare-function org-table-paste-rectangle "org-table" ())
169 (declare-function org-table-recalculate "org-table" (&optional all noalign))
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
174 (declare-function org-export-get-backend "ox" (name))
175 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
176 (declare-function org-latex-make-preamble "ox-latex" (info &optional template))
178 (defsubst org-uniquify (list)
179 "Non-destructively remove duplicate elements from LIST."
180 (let ((res (copy-sequence list))) (delete-dups res)))
182 (defsubst org-get-at-bol (property)
183 "Get text property PROPERTY at the beginning of line."
184 (get-text-property (point-at-bol) property))
186 (defsubst org-trim (s &optional keep-lead)
187 "Remove whitespace at the beginning and the end of string S.
188 When optional argument KEEP-LEAD is non-nil, removing blank lines
189 at the beginning of the string does not affect leading indentation."
190 (replace-regexp-in-string
191 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
192 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
194 ;; load languages based on value of `org-babel-load-languages'
195 (defvar org-babel-load-languages)
197 ;;;###autoload
198 (defun org-babel-do-load-languages (sym value)
199 "Load the languages defined in `org-babel-load-languages'."
200 (set-default sym value)
201 (dolist (pair org-babel-load-languages)
202 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
203 (if active
204 (require (intern (concat "ob-" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-execute:" lang)))
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-expand-body:" lang)))))))
210 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
211 ;;;###autoload
212 (defun org-babel-load-file (file &optional compile)
213 "Load Emacs Lisp source code blocks in the Org FILE.
214 This function exports the source code using `org-babel-tangle'
215 and then loads the resulting file using `load-file'. With prefix
216 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
217 file to byte-code before it is loaded."
218 (interactive "fFile to load: \nP")
219 (let* ((age (lambda (file)
220 (float-time
221 (time-subtract (current-time)
222 (nth 5 (or (file-attributes (file-truename file))
223 (file-attributes file)))))))
224 (base-name (file-name-sans-extension file))
225 (exported-file (concat base-name ".el")))
226 ;; tangle if the Org file is newer than the elisp file
227 (unless (and (file-exists-p exported-file)
228 (> (funcall age file) (funcall age exported-file)))
229 ;; Tangle-file traversal returns reversed list of tangled files
230 ;; and we want to evaluate the first target.
231 (setq exported-file
232 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
233 (message "%s %s"
234 (if compile
235 (progn (byte-compile-file exported-file 'load)
236 "Compiled and loaded")
237 (progn (load-file exported-file) "Loaded"))
238 exported-file)))
240 (defcustom org-babel-load-languages '((emacs-lisp . t))
241 "Languages which can be evaluated in Org buffers.
242 This list can be used to load support for any of the languages
243 below, note that each language will depend on a different set of
244 system executables and/or Emacs modes. When a language is
245 \"loaded\", then code blocks in that language can be evaluated
246 with `org-babel-execute-src-block' bound by default to C-c
247 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
248 be set to remove code block evaluation from the C-c C-c
249 keybinding. By default only Emacs Lisp (which has no
250 requirements) is loaded."
251 :group 'org-babel
252 :set 'org-babel-do-load-languages
253 :version "24.1"
254 :type '(alist :tag "Babel Languages"
255 :key-type
256 (choice
257 (const :tag "Awk" awk)
258 (const :tag "C" C)
259 (const :tag "R" R)
260 (const :tag "Asymptote" asymptote)
261 (const :tag "Calc" calc)
262 (const :tag "Clojure" clojure)
263 (const :tag "CSS" css)
264 (const :tag "Ditaa" ditaa)
265 (const :tag "Dot" dot)
266 (const :tag "Emacs Lisp" emacs-lisp)
267 (const :tag "Forth" forth)
268 (const :tag "Fortran" fortran)
269 (const :tag "Gnuplot" gnuplot)
270 (const :tag "Haskell" haskell)
271 (const :tag "IO" io)
272 (const :tag "J" J)
273 (const :tag "Java" java)
274 (const :tag "Javascript" js)
275 (const :tag "LaTeX" latex)
276 (const :tag "Ledger" ledger)
277 (const :tag "Lilypond" lilypond)
278 (const :tag "Lisp" lisp)
279 (const :tag "Makefile" makefile)
280 (const :tag "Maxima" maxima)
281 (const :tag "Matlab" matlab)
282 (const :tag "Mscgen" mscgen)
283 (const :tag "Ocaml" ocaml)
284 (const :tag "Octave" octave)
285 (const :tag "Org" org)
286 (const :tag "Perl" perl)
287 (const :tag "Pico Lisp" picolisp)
288 (const :tag "PlantUML" plantuml)
289 (const :tag "Python" python)
290 (const :tag "Ruby" ruby)
291 (const :tag "Sass" sass)
292 (const :tag "Scala" scala)
293 (const :tag "Scheme" scheme)
294 (const :tag "Screen" screen)
295 (const :tag "Shell Script" shell)
296 (const :tag "Shen" shen)
297 (const :tag "Sql" sql)
298 (const :tag "Sqlite" sqlite)
299 (const :tag "Stan" stan)
300 (const :tag "ebnf2ps" ebnf2ps))
301 :value-type (boolean :tag "Activate" :value t)))
303 ;;;; Customization variables
304 (defcustom org-clone-delete-id nil
305 "Remove ID property of clones of a subtree.
306 When non-nil, clones of a subtree don't inherit the ID property.
307 Otherwise they inherit the ID property with a new unique
308 identifier."
309 :type 'boolean
310 :version "24.1"
311 :group 'org-id)
313 ;;; Version
314 (org-check-version)
316 ;;;###autoload
317 (defun org-version (&optional here full message)
318 "Show the Org version.
319 Interactively, or when MESSAGE is non-nil, show it in echo area.
320 With prefix argument, or when HERE is non-nil, insert it at point.
321 In non-interactive uses, a reduced version string is output unless
322 FULL is given."
323 (interactive (list current-prefix-arg t (not current-prefix-arg)))
324 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
325 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
326 (load-suffixes (list ".el"))
327 (org-install-dir
328 (ignore-errors (org-find-library-dir "org-loaddefs"))))
329 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
330 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
331 (let* ((load-suffixes save-load-suffixes)
332 (release (org-release))
333 (git-version (org-git-version))
334 (version (format "Org mode version %s (%s @ %s)"
335 release
336 git-version
337 (if org-install-dir
338 (if (string= org-dir org-install-dir)
339 org-install-dir
340 (concat "mixed installation! "
341 org-install-dir
342 " and "
343 org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version release)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1)))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 \\<org-mode-map>
379 A deadline is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-deadline]'.")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 \\<org-mode-map>
386 A schedule is this string, followed by a time stamp. It must be
387 a word, terminated by a colon. You can insert a schedule keyword
388 and a timestamp with `\\[org-schedule]'.")
390 (defconst org-ds-keyword-length
391 (+ 2
392 (apply #'max
393 (mapcar #'length
394 (list org-deadline-string org-scheduled-string
395 org-clock-string org-closed-string))))
396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
398 (defconst org-planning-line-re
399 (concat "^[ \t]*"
400 (regexp-opt
401 (list org-closed-string org-deadline-string org-scheduled-string)
403 "Matches a line with planning info.
404 Matched keyword is in group 1.")
406 (defconst org-clock-line-re
407 (concat "^[ \t]*" org-clock-string)
408 "Matches a line with clock info.")
410 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
411 "Matches the DEADLINE keyword.")
413 (defconst org-deadline-time-regexp
414 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
415 "Matches the DEADLINE keyword together with a time stamp.")
417 (defconst org-deadline-time-hour-regexp
418 (concat "\\<" org-deadline-string
419 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
420 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
422 (defconst org-deadline-line-regexp
423 (concat "\\<\\(" org-deadline-string "\\).*")
424 "Matches the DEADLINE keyword and the rest of the line.")
426 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
427 "Matches the SCHEDULED keyword.")
429 (defconst org-scheduled-time-regexp
430 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
431 "Matches the SCHEDULED keyword together with a time stamp.")
433 (defconst org-scheduled-time-hour-regexp
434 (concat "\\<" org-scheduled-string
435 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
436 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
438 (defconst org-closed-time-regexp
439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
440 "Matches the CLOSED keyword together with a time stamp.")
442 (defconst org-keyword-time-regexp
443 (concat "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string
446 org-clock-string)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 4 keywords, together with the time stamp.")
451 (defconst org-keyword-time-not-clock-regexp
452 (concat
453 "\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string) t)
456 " *[[<]\\([^]>]+\\)[]>]")
457 "Matches any of the 3 keywords, together with the time stamp.")
459 (defconst org-maybe-keyword-time-regexp
460 (concat "\\(\\<"
461 (regexp-opt
462 (list org-scheduled-string org-deadline-string org-closed-string
463 org-clock-string)
465 "\\)?"
466 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "\\|"
468 "<%%([^\r\n>]*>\\)")
469 "Matches a timestamp, possibly preceded by a keyword.")
471 (defconst org-all-time-keywords
472 (mapcar (lambda (w) (substring w 0 -1))
473 (list org-scheduled-string org-deadline-string
474 org-clock-string org-closed-string))
475 "List of time keywords.")
477 ;;;; Drawer
479 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
480 "Matches first or last line of a hidden block.
481 Group 1 contains drawer's name or \"END\".")
483 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
484 "Regular expression matching the first line of a property drawer.")
486 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a property drawer.")
489 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
490 "Regular expression matching the first line of a clock drawer.")
492 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
493 "Regular expression matching the last line of a clock drawer.")
495 (defconst org-property-drawer-re
496 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
497 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
498 "[ \t]*:END:[ \t]*$")
499 "Matches an entire property drawer.")
501 (defconst org-clock-drawer-re
502 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
503 org-clock-drawer-end-re "\\)\n?")
504 "Matches an entire clock drawer.")
506 ;;;; Headline
508 (defconst org-heading-keyword-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline with some keyword.
511 This regexp will match the headline of any node which has the
512 exact keyword that is put into the format. The keyword isn't in
513 any group by default, but the stars and the body are.")
515 (defconst org-heading-keyword-maybe-regexp-format
516 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
517 "Printf format for a regexp matching a headline, possibly with some keyword.
518 This regexp can match any headline with the specified keyword, or
519 without a keyword. The keyword isn't in any group by default,
520 but the stars and the body are.")
522 (defconst org-archive-tag "ARCHIVE"
523 "The tag that marks a subtree as archived.
524 An archived subtree does not open during visibility cycling, and does
525 not contribute to the agenda listings.")
527 (defconst org-comment-string "COMMENT"
528 "Entries starting with this keyword will never be exported.
529 \\<org-mode-map>
530 An entry can be toggled between COMMENT and normal with
531 `\\[org-toggle-comment]'.")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (dolist (ext org-modules)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 (setq org-modules-loaded t)))
666 (defun org-set-modules (var value)
667 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
668 (set var value)
669 (when (featurep 'org)
670 (org-load-modules-maybe 'force)
671 (org-element-cache-reset 'all)))
673 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
674 "Modules that should always be loaded together with org.el.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 You can also use this system to load external packages (i.e. neither Org
681 core modules, nor modules from the CONTRIB directory). Just add symbols
682 to the end of the list. If the package is called org-xyz.el, then you need
683 to add the symbol `xyz', and the package must have a call to:
685 (provide \\='org-xyz)
687 For export specific modules, see also `org-export-backends'."
688 :group 'org
689 :set 'org-set-modules
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type
693 '(set :greedy t
694 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
695 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
696 (const :tag " crypt: Encryption of subtrees" org-crypt)
697 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
698 (const :tag " docview: Links to doc-view buffers" org-docview)
699 (const :tag " eww: Store link to url of eww" org-eww)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defgroup org-startup nil
921 "Options concerning startup of Org mode."
922 :tag "Org Startup"
923 :group 'org)
925 (defcustom org-startup-folded t
926 "Non-nil means entering Org mode will switch to OVERVIEW.
928 This can also be configured on a per-file basis by adding one of
929 the following lines anywhere in the buffer:
931 #+STARTUP: fold (or `overview', this is equivalent)
932 #+STARTUP: nofold (or `showall', this is equivalent)
933 #+STARTUP: content
934 #+STARTUP: showeverything
936 Set `org-agenda-inhibit-startup' to a non-nil value if you want
937 to ignore this option when Org opens agenda files for the first
938 time."
939 :group 'org-startup
940 :type '(choice
941 (const :tag "nofold: show all" nil)
942 (const :tag "fold: overview" t)
943 (const :tag "content: all headlines" content)
944 (const :tag "show everything, even drawers" showeverything)))
946 (defcustom org-startup-truncated t
947 "Non-nil means entering Org mode will set `truncate-lines'.
948 This is useful since some lines containing links can be very long and
949 uninteresting. Also tables look terrible when wrapped.
951 The variable `org-startup-truncated' allows to configure
952 truncation for Org mode different to the other modes that use the
953 variable `truncate-lines' and as a shortcut instead of putting
954 the variable `truncate-lines' into the `org-mode-hook'. If one
955 wants to configure truncation for Org mode not statically but
956 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
957 the variable `truncate-lines' has to be used because in such a
958 case it is too late to set the variable `org-startup-truncated'."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-startup-indented nil
963 "Non-nil means turn on `org-indent-mode' on startup.
964 This can also be configured on a per-file basis by adding one of
965 the following lines anywhere in the buffer:
967 #+STARTUP: indent
968 #+STARTUP: noindent"
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Not" nil)
972 (const :tag "Globally (slow on startup in large files)" t)))
974 (defcustom org-use-sub-superscripts t
975 "Non-nil means interpret \"_\" and \"^\" for display.
977 If you want to control how Org exports those characters, see
978 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
979 used to be an alias for `org-export-with-sub-superscripts' in
980 Org <8.0, it is not anymore.
982 When this option is turned on, you can use TeX-like syntax for
983 sub- and superscripts within the buffer. Several characters after
984 \"_\" or \"^\" will be considered as a single item - so grouping
985 with {} is normally not needed. For example, the following things
986 will be parsed as single sub- or superscripts:
988 10^24 or 10^tau several digits will be considered 1 item.
989 10^-12 or 10^-tau a leading sign with digits or a word
990 x^2-y^3 will be read as x^2 - y^3, because items are
991 terminated by almost any nonword/nondigit char.
992 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
994 Still, ambiguity is possible. So when in doubt, use {} to enclose
995 the sub/superscript. If you set this variable to the symbol `{}',
996 the braces are *required* in order to trigger interpretations as
997 sub/superscript. This can be helpful in documents that need \"_\"
998 frequently in plain text."
999 :group 'org-startup
1000 :version "24.4"
1001 :package-version '(Org . "8.0")
1002 :type '(choice
1003 (const :tag "Always interpret" t)
1004 (const :tag "Only with braces" {})
1005 (const :tag "Never interpret" nil)))
1007 (defcustom org-startup-with-beamer-mode nil
1008 "Non-nil means turn on `org-beamer-mode' on startup.
1009 This can also be configured on a per-file basis by adding one of
1010 the following lines anywhere in the buffer:
1012 #+STARTUP: beamer"
1013 :group 'org-startup
1014 :version "24.1"
1015 :type 'boolean)
1017 (defcustom org-startup-align-all-tables nil
1018 "Non-nil means align all tables when visiting a file.
1019 This is useful when the column width in tables is forced with <N> cookies
1020 in table fields. Such tables will look correct only after the first re-align.
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: align
1024 #+STARTUP: noalign"
1025 :group 'org-startup
1026 :type 'boolean)
1028 (defcustom org-startup-with-inline-images nil
1029 "Non-nil means show inline images when loading a new Org file.
1030 This can also be configured on a per-file basis by adding one of
1031 the following lines anywhere in the buffer:
1032 #+STARTUP: inlineimages
1033 #+STARTUP: noinlineimages"
1034 :group 'org-startup
1035 :version "24.1"
1036 :type 'boolean)
1038 (defcustom org-startup-with-latex-preview nil
1039 "Non-nil means preview LaTeX fragments when loading a new Org file.
1041 This can also be configured on a per-file basis by adding one of
1042 the following lines anywhere in the buffer:
1043 #+STARTUP: latexpreview
1044 #+STARTUP: nolatexpreview"
1045 :group 'org-startup
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defcustom org-insert-mode-line-in-empty-file nil
1051 "Non-nil means insert the first line setting Org mode in empty files.
1052 When the function `org-mode' is called interactively in an empty file, this
1053 normally means that the file name does not automatically trigger Org mode.
1054 To ensure that the file will always be in Org mode in the future, a
1055 line enforcing Org mode will be inserted into the buffer, if this option
1056 has been set."
1057 :group 'org-startup
1058 :type 'boolean)
1060 (defcustom org-replace-disputed-keys nil
1061 "Non-nil means use alternative key bindings for some keys.
1062 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1063 These keys are also used by other packages like shift-selection-mode'
1064 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1065 If you want to use Org mode together with one of these other modes,
1066 or more generally if you would like to move some Org mode commands to
1067 other keys, set this variable and configure the keys with the variable
1068 `org-disputed-keys'.
1070 This option is only relevant at load-time of Org mode, and must be set
1071 *before* org.el is loaded. Changing it requires a restart of Emacs to
1072 become effective."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-use-extra-keys nil
1077 "Non-nil means use extra key sequence definitions for certain commands.
1078 This happens automatically if `window-system' is nil. This
1079 variable lets you do the same manually. You must set it before
1080 loading Org."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org mode startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1109 org-disputed-keys)))
1110 (setq key (if x (cdr x) key))))
1111 key)
1113 (defun org-defkey (keymap key def)
1114 "Define a key, possibly translated, as returned by `org-key'."
1115 (define-key keymap (org-key key) def))
1117 (defcustom org-ellipsis nil
1118 "The ellipsis to use in the Org mode outline.
1120 When nil, just use the standard three dots.
1121 When a string, use that string instead.
1123 The change affects only Org mode (which will then use its own display table).
1124 Changing this requires executing `\\[org-mode]' in a buffer to become
1125 effective."
1126 :group 'org-startup
1127 :type '(choice (const :tag "Default" nil)
1128 (string :tag "String" :value "...#"))
1129 :safe #'string-or-null-p)
1131 (defvar org-display-table nil
1132 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1134 (defgroup org-keywords nil
1135 "Keywords in Org mode."
1136 :tag "Org Keywords"
1137 :group 'org)
1139 (defcustom org-closed-keep-when-no-todo nil
1140 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1141 :group 'org-todo
1142 :group 'org-keywords
1143 :version "24.4"
1144 :package-version '(Org . "8.0")
1145 :type 'boolean)
1147 (defgroup org-structure nil
1148 "Options concerning the general structure of Org files."
1149 :tag "Org Structure"
1150 :group 'org)
1152 (defgroup org-reveal-location nil
1153 "Options about how to make context of a location visible."
1154 :tag "Org Reveal Location"
1155 :group 'org-structure)
1157 (defcustom org-show-context-detail '((agenda . local)
1158 (bookmark-jump . lineage)
1159 (isearch . lineage)
1160 (default . ancestors))
1161 "Alist between context and visibility span when revealing a location.
1163 \\<org-mode-map>Some actions may move point into invisible
1164 locations. As a consequence, Org always expose a neighborhood
1165 around point. How much is shown depends on the initial action,
1166 or context. Valid contexts are
1168 agenda when exposing an entry from the agenda
1169 org-goto when using the command `org-goto' (`\\[org-goto]')
1170 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1171 tags-tree when constructing a sparse tree based on tags matches
1172 link-search when exposing search matches associated with a link
1173 mark-goto when exposing the jump goal of a mark
1174 bookmark-jump when exposing a bookmark location
1175 isearch when exiting from an incremental search
1176 default default for all contexts not set explicitly
1178 Allowed visibility spans are
1180 minimal show current headline; if point is not on headline,
1181 also show entry
1183 local show current headline, entry and next headline
1185 ancestors show current headline and its direct ancestors; if
1186 point is not on headline, also show entry
1188 lineage show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and first child
1192 tree show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and all children
1196 canonical show current headline, its direct ancestors along with
1197 their entries and children; if point is not located on
1198 the headline, also show current entry and all children
1200 As special cases, a nil or t value means show all contexts in
1201 `minimal' or `canonical' view, respectively.
1203 Some views can make displayed information very compact, but also
1204 make it harder to edit the location of the match. In such
1205 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1206 more context."
1207 :group 'org-reveal-location
1208 :version "26.1"
1209 :package-version '(Org . "9.0")
1210 :type '(choice
1211 (const :tag "Canonical" t)
1212 (const :tag "Minimal" nil)
1213 (repeat :greedy t :tag "Individual contexts"
1214 (cons
1215 (choice :tag "Context"
1216 (const agenda)
1217 (const org-goto)
1218 (const occur-tree)
1219 (const tags-tree)
1220 (const link-search)
1221 (const mark-goto)
1222 (const bookmark-jump)
1223 (const isearch)
1224 (const default))
1225 (choice :tag "Detail level"
1226 (const minimal)
1227 (const local)
1228 (const ancestors)
1229 (const lineage)
1230 (const tree)
1231 (const canonical))))))
1233 (defcustom org-indirect-buffer-display 'other-window
1234 "How should indirect tree buffers be displayed?
1236 This applies to indirect buffers created with the commands
1237 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1239 Valid values are:
1240 current-window Display in the current window
1241 other-window Just display in another window.
1242 dedicated-frame Create one new frame, and re-use it each time.
1243 new-frame Make a new frame each time. Note that in this case
1244 previously-made indirect buffers are kept, and you need to
1245 kill these buffers yourself."
1246 :group 'org-structure
1247 :group 'org-agenda-windows
1248 :type '(choice
1249 (const :tag "In current window" current-window)
1250 (const :tag "In current frame, other window" other-window)
1251 (const :tag "Each time a new frame" new-frame)
1252 (const :tag "One dedicated frame" dedicated-frame)))
1254 (defcustom org-use-speed-commands nil
1255 "Non-nil means activate single letter commands at beginning of a headline.
1256 This may also be a function to test for appropriate locations where speed
1257 commands should be active.
1259 For example, to activate speed commands when the point is on any
1260 star at the beginning of the headline, you can do this:
1262 (setq org-use-speed-commands
1263 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1264 :group 'org-structure
1265 :type '(choice
1266 (const :tag "Never" nil)
1267 (const :tag "At beginning of headline stars" t)
1268 (function)))
1270 (defcustom org-speed-commands-user nil
1271 "Alist of additional speed commands.
1272 This list will be checked before `org-speed-commands-default'
1273 when the variable `org-use-speed-commands' is non-nil
1274 and when the cursor is at the beginning of a headline.
1275 The car if each entry is a string with a single letter, which must
1276 be assigned to `self-insert-command' in the global map.
1277 The cdr is either a command to be called interactively, a function
1278 to be called, or a form to be evaluated.
1279 An entry that is just a list with a single string will be interpreted
1280 as a descriptive headline that will be added when listing the speed
1281 commands in the Help buffer using the `?' speed command."
1282 :group 'org-structure
1283 :type '(repeat :value ("k" . ignore)
1284 (choice :value ("k" . ignore)
1285 (list :tag "Descriptive Headline" (string :tag "Headline"))
1286 (cons :tag "Letter and Command"
1287 (string :tag "Command letter")
1288 (choice
1289 (function)
1290 (sexp))))))
1292 (defcustom org-bookmark-names-plist
1293 '(:last-capture "org-capture-last-stored"
1294 :last-refile "org-refile-last-stored"
1295 :last-capture-marker "org-capture-last-stored-marker")
1296 "Names for bookmarks automatically set by some Org commands.
1297 This can provide strings as names for a number of bookmarks Org sets
1298 automatically. The following keys are currently implemented:
1299 :last-capture
1300 :last-capture-marker
1301 :last-refile
1302 When a key does not show up in the property list, the corresponding bookmark
1303 is not set."
1304 :group 'org-structure
1305 :type 'plist)
1307 (defgroup org-cycle nil
1308 "Options concerning visibility cycling in Org mode."
1309 :tag "Org Cycle"
1310 :group 'org-structure)
1312 (defcustom org-cycle-skip-children-state-if-no-children t
1313 "Non-nil means skip CHILDREN state in entries that don't have any."
1314 :group 'org-cycle
1315 :type 'boolean)
1317 (defcustom org-cycle-max-level nil
1318 "Maximum level which should still be subject to visibility cycling.
1319 Levels higher than this will, for cycling, be treated as text, not a headline.
1320 When `org-odd-levels-only' is set, a value of N in this variable actually
1321 means 2N-1 stars as the limiting headline.
1322 When nil, cycle all levels.
1323 Note that the limiting level of cycling is also influenced by
1324 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1325 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1326 than its value."
1327 :group 'org-cycle
1328 :type '(choice
1329 (const :tag "No limit" nil)
1330 (integer :tag "Maximum level")))
1332 (defcustom org-hide-block-startup nil
1333 "Non-nil means entering Org mode will fold all blocks.
1334 This can also be set in on a per-file basis with
1336 #+STARTUP: hideblocks
1337 #+STARTUP: showblocks"
1338 :group 'org-startup
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-global-at-bob nil
1343 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1345 This makes it possible to do global cycling without having to use `S-TAB'
1346 or `\\[universal-argument] TAB'. For this special case to work, the first \
1347 line of the buffer
1348 must not be a headline -- it may be empty or some other text.
1350 When used in this way, `org-cycle-hook' is disabled temporarily to make
1351 sure the cursor stays at the beginning of the buffer.
1353 When this option is nil, don't do anything special at the beginning of
1354 the buffer."
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-level-after-item/entry-creation t
1359 "Non-nil means cycle entry level or item indentation in new empty entries.
1361 When the cursor is at the end of an empty headline, i.e., with only stars
1362 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1363 and then all possible ancestor states, before returning to the original state.
1364 This makes data entry extremely fast: M-RET to create a new headline,
1365 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1367 When the cursor is at the end of an empty plain list item, one TAB will
1368 make it a subitem, two or more tabs will back up to make this an item
1369 higher up in the item hierarchy."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-emulate-tab t
1374 "Where should `org-cycle' emulate TAB.
1375 nil Never
1376 white Only in completely white lines
1377 whitestart Only at the beginning of lines, before the first non-white char
1378 t Everywhere except in headlines
1379 exc-hl-bol Everywhere except at the start of a headline
1380 If TAB is used in a place where it does not emulate TAB, the current subtree
1381 visibility is cycled."
1382 :group 'org-cycle
1383 :type '(choice (const :tag "Never" nil)
1384 (const :tag "Only in completely white lines" white)
1385 (const :tag "Before first char in a line" whitestart)
1386 (const :tag "Everywhere except in headlines" t)
1387 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1389 (defcustom org-cycle-separator-lines 2
1390 "Number of empty lines needed to keep an empty line between collapsed trees.
1391 If you leave an empty line between the end of a subtree and the following
1392 headline, this empty line is hidden when the subtree is folded.
1393 Org mode will leave (exactly) one empty line visible if the number of
1394 empty lines is equal or larger to the number given in this variable.
1395 So the default 2 means at least 2 empty lines after the end of a subtree
1396 are needed to produce free space between a collapsed subtree and the
1397 following headline.
1399 If the number is negative, and the number of empty lines is at least -N,
1400 all empty lines are shown.
1402 Special case: when 0, never leave empty lines in collapsed view."
1403 :group 'org-cycle
1404 :type 'integer)
1405 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1407 (defcustom org-pre-cycle-hook nil
1408 "Hook that is run before visibility cycling is happening.
1409 The function(s) in this hook must accept a single argument which indicates
1410 the new state that will be set right after running this hook. The
1411 argument is a symbol. Before a global state change, it can have the values
1412 `overview', `content', or `all'. Before a local state change, it can have
1413 the values `folded', `children', or `subtree'."
1414 :group 'org-cycle
1415 :type 'hook)
1417 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1418 org-cycle-hide-drawers
1419 org-cycle-show-empty-lines
1420 org-optimize-window-after-visibility-change)
1421 "Hook that is run after `org-cycle' has changed the buffer visibility.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that was set by the most recent `org-cycle' command. The
1424 argument is a symbol. After a global state change, it can have the values
1425 `overview', `contents', or `all'. After a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1427 :group 'org-cycle
1428 :type 'hook
1429 :version "26.1"
1430 :package-version '(Org . "8.3"))
1432 (defgroup org-edit-structure nil
1433 "Options concerning structure editing in Org mode."
1434 :tag "Org Edit Structure"
1435 :group 'org-structure)
1437 (defcustom org-odd-levels-only nil
1438 "Non-nil means skip even levels and only use odd levels for the outline.
1439 This has the effect that two stars are being added/taken away in
1440 promotion/demotion commands. It also influences how levels are
1441 handled by the exporters.
1442 Changing it requires restart of `font-lock-mode' to become effective
1443 for fontification also in regions already fontified.
1444 You may also set this on a per-file basis by adding one of the following
1445 lines to the buffer:
1447 #+STARTUP: odd
1448 #+STARTUP: oddeven"
1449 :group 'org-edit-structure
1450 :group 'org-appearance
1451 :type 'boolean)
1453 (defcustom org-adapt-indentation t
1454 "Non-nil means adapt indentation to outline node level.
1456 When this variable is set, Org assumes that you write outlines by
1457 indenting text in each node to align with the headline (after the
1458 stars). The following issues are influenced by this variable:
1460 - The indentation is increased by one space in a demotion
1461 command, and decreased by one in a promotion command. However,
1462 in the latter case, if shifting some line in the entry body
1463 would alter document structure (e.g., insert a new headline),
1464 indentation is not changed at all.
1466 - Property drawers and planning information is inserted indented
1467 when this variable is set. When nil, they will not be indented.
1469 - TAB indents a line relative to current level. The lines below
1470 a headline will be indented when this variable is set.
1472 Note that this is all about true indentation, by adding and
1473 removing space characters. See also `org-indent.el' which does
1474 level-dependent indentation in a virtual way, i.e. at display
1475 time in Emacs."
1476 :group 'org-edit-structure
1477 :type 'boolean)
1479 (defcustom org-special-ctrl-a/e nil
1480 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1482 When t, `C-a' will bring back the cursor to the beginning of the
1483 headline text, i.e. after the stars and after a possible TODO
1484 keyword. In an item, this will be the position after bullet and
1485 check-box, if any. When the cursor is already at that position,
1486 another `C-a' will bring it to the beginning of the line.
1488 `C-e' will jump to the end of the headline, ignoring the presence
1489 of tags in the headline. A second `C-e' will then jump to the
1490 true end of the line, after any tags. This also means that, when
1491 this variable is non-nil, `C-e' also will never jump beyond the
1492 end of the heading of a folded section, i.e. not after the
1493 ellipses.
1495 When set to the symbol `reversed', the first `C-a' or `C-e' works
1496 normally, going to the true line boundary first. Only a directly
1497 following, identical keypress will bring the cursor to the
1498 special positions.
1500 This may also be a cons cell where the behavior for `C-a' and
1501 `C-e' is set separately."
1502 :group 'org-edit-structure
1503 :type '(choice
1504 (const :tag "off" nil)
1505 (const :tag "on: after stars/bullet and before tags first" t)
1506 (const :tag "reversed: true line boundary first" reversed)
1507 (cons :tag "Set C-a and C-e separately"
1508 (choice :tag "Special C-a"
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet first" t)
1511 (const :tag "reversed: before stars/bullet first" reversed))
1512 (choice :tag "Special C-e"
1513 (const :tag "off" nil)
1514 (const :tag "on: before tags first" t)
1515 (const :tag "reversed: after tags first" reversed)))))
1516 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1518 (defcustom org-special-ctrl-k nil
1519 "Non-nil means `C-k' will behave specially in headlines.
1520 When nil, `C-k' will call the default `kill-line' command.
1521 When t, the following will happen while the cursor is in the headline:
1523 - When the cursor is at the beginning of a headline, kill the entire
1524 line and possible the folded subtree below the line.
1525 - When in the middle of the headline text, kill the headline up to the tags.
1526 - When after the headline text, kill the tags."
1527 :group 'org-edit-structure
1528 :type 'boolean)
1530 (defcustom org-ctrl-k-protect-subtree nil
1531 "Non-nil means, do not delete a hidden subtree with C-k.
1532 When set to the symbol `error', simply throw an error when C-k is
1533 used to kill (part-of) a headline that has hidden text behind it.
1534 Any other non-nil value will result in a query to the user, if it is
1535 OK to kill that hidden subtree. When nil, kill without remorse."
1536 :group 'org-edit-structure
1537 :version "24.1"
1538 :type '(choice
1539 (const :tag "Do not protect hidden subtrees" nil)
1540 (const :tag "Protect hidden subtrees with a security query" t)
1541 (const :tag "Never kill a hidden subtree with C-k" error)))
1543 (defcustom org-special-ctrl-o t
1544 "Non-nil means, make `C-o' insert a row in tables."
1545 :group 'org-edit-structure
1546 :type 'boolean)
1548 (defcustom org-catch-invisible-edits nil
1549 "Check if in invisible region before inserting or deleting a character.
1550 Valid values are:
1552 nil Do not check, so just do invisible edits.
1553 error Throw an error and do nothing.
1554 show Make point visible, and do the requested edit.
1555 show-and-error Make point visible, then throw an error and abort the edit.
1556 smart Make point visible, and do insertion/deletion if it is
1557 adjacent to visible text and the change feels predictable.
1558 Never delete a previously invisible character or add in the
1559 middle or right after an invisible region. Basically, this
1560 allows insertion and backward-delete right before ellipses.
1561 FIXME: maybe in this case we should not even show?"
1562 :group 'org-edit-structure
1563 :version "24.1"
1564 :type '(choice
1565 (const :tag "Do not check" nil)
1566 (const :tag "Throw error when trying to edit" error)
1567 (const :tag "Unhide, but do not do the edit" show-and-error)
1568 (const :tag "Show invisible part and do the edit" show)
1569 (const :tag "Be smart and do the right thing" smart)))
1571 (defcustom org-yank-folded-subtrees t
1572 "Non-nil means when yanking subtrees, fold them.
1573 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1574 it starts with a heading and all other headings in it are either children
1575 or siblings, then fold all the subtrees. However, do this only if no
1576 text after the yank would be swallowed into a folded tree by this action."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-yank-adjusted-subtrees nil
1581 "Non-nil means when yanking subtrees, adjust the level.
1582 With this setting, `org-paste-subtree' is used to insert the subtree, see
1583 this function for details."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-M-RET-may-split-line '((default . t))
1588 "Non-nil means M-RET will split the line at the cursor position.
1589 When nil, it will go to the end of the line before making a
1590 new line.
1591 You may also set this option in a different way for different
1592 contexts. Valid contexts are:
1594 headline when creating a new headline
1595 item when creating a new item
1596 table in a table field
1597 default the value to be used for all contexts not explicitly
1598 customized"
1599 :group 'org-structure
1600 :group 'org-table
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Never" nil)
1604 (repeat :greedy t :tag "Individual contexts"
1605 (cons
1606 (choice :tag "Context"
1607 (const headline)
1608 (const item)
1609 (const table)
1610 (const default))
1611 (boolean)))))
1614 (defcustom org-insert-heading-respect-content nil
1615 "Non-nil means insert new headings after the current subtree.
1616 \\<org-mode-map>
1617 When nil, the new heading is created directly after the current line.
1618 The commands `\\[org-insert-heading-respect-content]' and \
1619 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1620 for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defcustom org-goto-auto-isearch t
1655 "Non-nil means typing characters in `org-goto' starts incremental search.
1656 When nil, you can use these keybindings to navigate the buffer:
1658 q Quit the org-goto interface
1659 n Go to the next visible heading
1660 p Go to the previous visible heading
1661 f Go one heading forward on same level
1662 b Go one heading backward on same level
1663 u Go one heading up"
1664 :group 'org-edit-structure
1665 :type 'boolean)
1667 (defgroup org-sparse-trees nil
1668 "Options concerning sparse trees in Org mode."
1669 :tag "Org Sparse Trees"
1670 :group 'org-structure)
1672 (defcustom org-highlight-sparse-tree-matches t
1673 "Non-nil means highlight all matches that define a sparse tree.
1674 The highlights will automatically disappear the next time the buffer is
1675 changed by an edit command."
1676 :group 'org-sparse-trees
1677 :type 'boolean)
1679 (defcustom org-remove-highlights-with-change t
1680 "Non-nil means any change to the buffer will remove temporary highlights.
1681 \\<org-mode-map>\
1682 Such highlights are created by `org-occur' and `org-clock-display'.
1683 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1684 to get rid of the highlights.
1685 The highlights created by `org-toggle-latex-fragment' always need
1686 `\\[org-toggle-latex-fragment]' to be removed."
1687 :group 'org-sparse-trees
1688 :group 'org-time
1689 :type 'boolean)
1691 (defcustom org-occur-case-fold-search t
1692 "Non-nil means `org-occur' should be case-insensitive.
1693 If set to `smart' the search will be case-insensitive only if it
1694 doesn't specify any upper case character."
1695 :group 'org-sparse-trees
1696 :version "26.1"
1697 :type '(choice
1698 (const :tag "Case-sensitive" nil)
1699 (const :tag "Case-insensitive" t)
1700 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1702 (defcustom org-occur-hook '(org-first-headline-recenter)
1703 "Hook that is run after `org-occur' has constructed a sparse tree.
1704 This can be used to recenter the window to show as much of the structure
1705 as possible."
1706 :group 'org-sparse-trees
1707 :type 'hook)
1709 (defgroup org-imenu-and-speedbar nil
1710 "Options concerning imenu and speedbar in Org mode."
1711 :tag "Org Imenu and Speedbar"
1712 :group 'org-structure)
1714 (defcustom org-imenu-depth 2
1715 "The maximum level for Imenu access to Org headlines.
1716 This also applied for speedbar access."
1717 :group 'org-imenu-and-speedbar
1718 :type 'integer)
1720 (defgroup org-table nil
1721 "Options concerning tables in Org mode."
1722 :tag "Org Table"
1723 :group 'org)
1725 (defcustom org-enable-table-editor 'optimized
1726 "Non-nil means lines starting with \"|\" are handled by the table editor.
1727 When nil, such lines will be treated like ordinary lines.
1729 When equal to the symbol `optimized', the table editor will be optimized to
1730 do the following:
1731 - Automatic overwrite mode in front of whitespace in table fields.
1732 This makes the structure of the table stay in tact as long as the edited
1733 field does not exceed the column width.
1734 - Minimize the number of realigns. Normally, the table is aligned each time
1735 TAB or RET are pressed to move to another field. With optimization this
1736 happens only if changes to a field might have changed the column width.
1737 Optimization requires replacing the functions `self-insert-command',
1738 `delete-char', and `backward-delete-char' in Org buffers, with a
1739 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1740 good at guessing when a re-align will be necessary, but you can always
1741 force one with `\\[org-ctrl-c-ctrl-c]'.
1743 If you would like to use the optimized version in Org mode, but the
1744 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1746 This variable can be used to turn on and off the table editor during a session,
1747 but in order to toggle optimization, a restart is required.
1749 See also the variable `org-table-auto-blank-field'."
1750 :group 'org-table
1751 :type '(choice
1752 (const :tag "off" nil)
1753 (const :tag "on" t)
1754 (const :tag "on, optimized" optimized)))
1756 (defcustom org-self-insert-cluster-for-undo nil
1757 "Non-nil means cluster self-insert commands for undo when possible.
1758 If this is set, then, like in the Emacs command loop, 20 consecutive
1759 characters will be undone together.
1760 This is configurable, because there is some impact on typing performance."
1761 :group 'org-table
1762 :type 'boolean)
1764 (defcustom org-table-tab-recognizes-table.el t
1765 "Non-nil means TAB will automatically notice a table.el table.
1766 When it sees such a table, it moves point into it and - if necessary -
1767 calls `table-recognize-table'."
1768 :group 'org-table-editing
1769 :type 'boolean)
1771 (defgroup org-link nil
1772 "Options concerning links in Org mode."
1773 :tag "Org Link"
1774 :group 'org)
1776 (defvar-local org-link-abbrev-alist-local nil
1777 "Buffer-local version of `org-link-abbrev-alist', which see.
1778 The value of this is taken from the #+LINK lines.")
1780 (defcustom org-link-parameters
1781 '(("doi" :follow org--open-doi-link)
1782 ("elisp" :follow org--open-elisp-link)
1783 ("file" :complete org-file-complete-link)
1784 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1785 ("help" :follow org--open-help-link)
1786 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1787 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1788 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1789 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1790 ("shell" :follow org--open-shell-link))
1791 "An alist of properties that defines all the links in Org mode.
1792 The key in each association is a string of the link type.
1793 Subsequent optional elements make up a p-list of link properties.
1795 :follow - A function that takes the link path as an argument.
1797 :export - A function that takes the link path, description and
1798 export-backend as arguments.
1800 :store - A function responsible for storing the link. See the
1801 function `org-store-link-functions'.
1803 :complete - A function that inserts a link with completion. The
1804 function takes one optional prefix arg.
1806 :face - A face for the link, or a function that returns a face.
1807 The function takes one argument which is the link path. The
1808 default face is `org-link'.
1810 :mouse-face - The mouse-face. The default is `highlight'.
1812 :display - `full' will not fold the link in descriptive
1813 display. Default is `org-link'.
1815 :help-echo - A string or function that takes (window object position)
1816 as arguments and returns a string.
1818 :keymap - A keymap that is active on the link. The default is
1819 `org-mouse-map'.
1821 :htmlize-link - A function for the htmlize-link. Defaults
1822 to (list :uri \"type:path\")
1824 :activate-func - A function to run at the end of font-lock
1825 activation. The function must accept (link-start link-end path bracketp)
1826 as arguments."
1827 :group 'org-link
1828 :type '(alist :tag "Link display parameters"
1829 :value-type plist)
1830 :version "26.1"
1831 :package-version '(Org . "9.1"))
1833 (defun org-link-get-parameter (type key)
1834 "Get TYPE link property for KEY.
1835 TYPE is a string and KEY is a plist keyword."
1836 (plist-get
1837 (cdr (assoc type org-link-parameters))
1838 key))
1840 (defun org-link-set-parameters (type &rest parameters)
1841 "Set link TYPE properties to PARAMETERS.
1842 PARAMETERS should be :key val pairs."
1843 (let ((data (assoc type org-link-parameters)))
1844 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1845 (push (cons type parameters) org-link-parameters)
1846 (org-make-link-regexps)
1847 (org-element-update-syntax))))
1849 (defun org-link-types ()
1850 "Return a list of known link types."
1851 (mapcar #'car org-link-parameters))
1853 (defcustom org-link-abbrev-alist nil
1854 "Alist of link abbreviations.
1855 The car of each element is a string, to be replaced at the start of a link.
1856 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1857 links in Org buffers can have an optional tag after a double colon, e.g.,
1859 [[linkkey:tag][description]]
1861 The `linkkey' must be a single word, starting with a letter, followed
1862 by letters, numbers, `-' or `_'.
1864 If REPLACE is a string, the tag will simply be appended to create the link.
1865 If the string contains \"%s\", the tag will be inserted there. If the string
1866 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1867 at that point (see the function `url-hexify-string'). If the string contains
1868 the specifier \"%(my-function)\", then the custom function `my-function' will
1869 be invoked: this function takes the tag as its only argument and must return
1870 a string.
1872 REPLACE may also be a function that will be called with the tag as the
1873 only argument to create the link, which should be returned as a string.
1875 See the manual for examples."
1876 :group 'org-link
1877 :type '(repeat
1878 (cons
1879 (string :tag "Protocol")
1880 (choice
1881 (string :tag "Format")
1882 (function)))))
1884 (defcustom org-descriptive-links t
1885 "Non-nil means Org will display descriptive links.
1886 E.g. [[http://orgmode.org][Org website]] will be displayed as
1887 \"Org Website\", hiding the link itself and just displaying its
1888 description. When set to nil, Org will display the full links
1889 literally.
1891 You can interactively set the value of this variable by calling
1892 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1893 :group 'org-link
1894 :type 'boolean)
1896 (defcustom org-link-file-path-type 'adaptive
1897 "How the path name in file links should be stored.
1898 Valid values are:
1900 relative Relative to the current directory, i.e. the directory of the file
1901 into which the link is being inserted.
1902 absolute Absolute path, if possible with ~ for home directory.
1903 noabbrev Absolute path, no abbreviation of home directory.
1904 adaptive Use relative path for files in the current directory and sub-
1905 directories of it. For other files, use an absolute path."
1906 :group 'org-link
1907 :type '(choice
1908 (const relative)
1909 (const absolute)
1910 (const noabbrev)
1911 (const adaptive)))
1913 (defvaralias 'org-activate-links 'org-highlight-links)
1914 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1915 "Types of links that should be highlighted in Org files.
1917 This is a list of symbols, each one of them leading to the
1918 highlighting of a certain link type.
1920 You can still open links that are not highlighted.
1922 In principle, it does not hurt to turn on highlighting for all
1923 link types. There may be a small gain when turning off unused
1924 link types. The types are:
1926 bracket The recommended [[link][description]] or [[link]] links with hiding.
1927 angle Links in angular brackets that may contain whitespace like
1928 <bbdb:Carsten Dominik>.
1929 plain Plain links in normal text, no whitespace, like http://google.com.
1930 radio Text that is matched by a radio target, see manual for details.
1931 tag Tag settings in a headline (link to tag search).
1932 date Time stamps (link to calendar).
1933 footnote Footnote labels.
1935 If you set this variable during an Emacs session, use `org-mode-restart'
1936 in the Org buffer so that the change takes effect."
1937 :group 'org-link
1938 :group 'org-appearance
1939 :type '(set :greedy t
1940 (const :tag "Double bracket links" bracket)
1941 (const :tag "Angular bracket links" angle)
1942 (const :tag "Plain text links" plain)
1943 (const :tag "Radio target matches" radio)
1944 (const :tag "Tags" tag)
1945 (const :tag "Timestamps" date)
1946 (const :tag "Footnotes" footnote)))
1948 (defcustom org-make-link-description-function nil
1949 "Function to use for generating link descriptions from links.
1950 When nil, the link location will be used. This function must take
1951 two parameters: the first one is the link, the second one is the
1952 description generated by `org-insert-link'. The function should
1953 return the description to use."
1954 :group 'org-link
1955 :type '(choice (const nil) (function)))
1957 (defgroup org-link-store nil
1958 "Options concerning storing links in Org mode."
1959 :tag "Org Store Link"
1960 :group 'org-link)
1962 (defcustom org-url-hexify-p t
1963 "When non-nil, hexify URL when creating a link."
1964 :type 'boolean
1965 :version "24.3"
1966 :group 'org-link-store)
1968 (defcustom org-email-link-description-format "Email %c: %.30s"
1969 "Format of the description part of a link to an email or usenet message.
1970 The following %-escapes will be replaced by corresponding information:
1972 %F full \"From\" field
1973 %f name, taken from \"From\" field, address if no name
1974 %T full \"To\" field
1975 %t first name in \"To\" field, address if no name
1976 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1977 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1978 %s subject
1979 %d date
1980 %m message-id.
1982 You may use normal field width specification between the % and the letter.
1983 This is for example useful to limit the length of the subject.
1985 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1986 :group 'org-link-store
1987 :type 'string)
1989 (defcustom org-from-is-user-regexp
1990 (let (r1 r2)
1991 (when (and user-mail-address (not (string= user-mail-address "")))
1992 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1993 (when (and user-full-name (not (string= user-full-name "")))
1994 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1995 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1996 "Regexp matched against the \"From:\" header of an email or usenet message.
1997 It should match if the message is from the user him/herself."
1998 :group 'org-link-store
1999 :type 'regexp)
2001 (defcustom org-context-in-file-links t
2002 "Non-nil means file links from `org-store-link' contain context.
2003 \\<org-mode-map>
2004 A search string will be added to the file name with :: as separator
2005 and used to find the context when the link is activated by the command
2006 `org-open-at-point'. When this option is t, the entire active region
2007 will be placed in the search string of the file link. If set to a
2008 positive integer, only the first n lines of context will be stored.
2010 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2011 \\[org-store-link]')
2012 negates this setting for the duration of the command."
2013 :group 'org-link-store
2014 :type '(choice boolean integer))
2016 (defcustom org-keep-stored-link-after-insertion nil
2017 "Non-nil means keep link in list for entire session.
2018 \\<org-mode-map>
2019 The command `org-store-link' adds a link pointing to the current
2020 location to an internal list. These links accumulate during a session.
2021 The command `org-insert-link' can be used to insert links into any
2022 Org file (offering completion for all stored links).
2024 When this option is nil, every link which has been inserted once using
2025 `\\[org-insert-link]' will be removed from the list, to make completing the \
2026 unused
2027 links more efficient."
2028 :group 'org-link-store
2029 :type 'boolean)
2031 (defgroup org-link-follow nil
2032 "Options concerning following links in Org mode."
2033 :tag "Org Follow Link"
2034 :group 'org-link)
2036 (defcustom org-link-translation-function nil
2037 "Function to translate links with different syntax to Org syntax.
2038 This can be used to translate links created for example by the Planner
2039 or emacs-wiki packages to Org syntax.
2040 The function must accept two parameters, a TYPE containing the link
2041 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2042 which is everything after the link protocol. It should return a cons
2043 with possibly modified values of type and path.
2044 Org contains a function for this, so if you set this variable to
2045 `org-translate-link-from-planner', you should be able follow many
2046 links created by planner."
2047 :group 'org-link-follow
2048 :type '(choice (const nil) (function)))
2050 (defcustom org-follow-link-hook nil
2051 "Hook that is run after a link has been followed."
2052 :group 'org-link-follow
2053 :type 'hook)
2055 (defcustom org-tab-follows-link nil
2056 "Non-nil means on links TAB will follow the link.
2057 Needs to be set before org.el is loaded.
2058 This really should not be used, it does not make sense, and the
2059 implementation is bad."
2060 :group 'org-link-follow
2061 :type 'boolean)
2063 (defcustom org-return-follows-link nil
2064 "Non-nil means on links RET will follow the link.
2065 In tables, the special behavior of RET has precedence."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-mouse-1-follows-link
2070 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2071 "Non-nil means mouse-1 on a link will follow the link.
2072 A longer mouse click will still set point. Needs to be set
2073 before org.el is loaded."
2074 :group 'org-link-follow
2075 :version "24.4"
2076 :package-version '(Org . "8.3")
2077 :type '(choice
2078 (const :tag "A double click follows the link" double)
2079 (const :tag "Unconditionally follow the link with mouse-1" t)
2080 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2082 (defcustom org-mark-ring-length 4
2083 "Number of different positions to be recorded in the ring.
2084 Changing this requires a restart of Emacs to work correctly."
2085 :group 'org-link-follow
2086 :type 'integer)
2088 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2089 "Non-nil means internal fuzzy links can only match headlines.
2091 When nil, the a fuzzy link may point to a target or a named
2092 construct in the document. When set to the special value
2093 `query-to-create', offer to create a new headline when none
2094 matched.
2096 Spaces and statistics cookies are ignored during heading searches."
2097 :group 'org-link-follow
2098 :version "24.1"
2099 :type '(choice
2100 (const :tag "Use fuzzy text search" nil)
2101 (const :tag "Match only exact headline" t)
2102 (const :tag "Match exact headline or query to create it"
2103 query-to-create))
2104 :safe #'symbolp)
2106 (defcustom org-link-frame-setup
2107 '((vm . vm-visit-folder-other-frame)
2108 (vm-imap . vm-visit-imap-folder-other-frame)
2109 (gnus . org-gnus-no-new-news)
2110 (file . find-file-other-window)
2111 (wl . wl-other-frame))
2112 "Setup the frame configuration for following links.
2113 When following a link with Emacs, it may often be useful to display
2114 this link in another window or frame. This variable can be used to
2115 set this up for the different types of links.
2116 For VM, use any of
2117 `vm-visit-folder'
2118 `vm-visit-folder-other-window'
2119 `vm-visit-folder-other-frame'
2120 For Gnus, use any of
2121 `gnus'
2122 `gnus-other-frame'
2123 `org-gnus-no-new-news'
2124 For FILE, use any of
2125 `find-file'
2126 `find-file-other-window'
2127 `find-file-other-frame'
2128 For Wanderlust use any of
2129 `wl'
2130 `wl-other-frame'
2131 For the calendar, use the variable `calendar-setup'.
2132 For BBDB, it is currently only possible to display the matches in
2133 another window."
2134 :group 'org-link-follow
2135 :type '(list
2136 (cons (const vm)
2137 (choice
2138 (const vm-visit-folder)
2139 (const vm-visit-folder-other-window)
2140 (const vm-visit-folder-other-frame)))
2141 (cons (const vm-imap)
2142 (choice
2143 (const vm-visit-imap-folder)
2144 (const vm-visit-imap-folder-other-window)
2145 (const vm-visit-imap-folder-other-frame)))
2146 (cons (const gnus)
2147 (choice
2148 (const gnus)
2149 (const gnus-other-frame)
2150 (const org-gnus-no-new-news)))
2151 (cons (const file)
2152 (choice
2153 (const find-file)
2154 (const find-file-other-window)
2155 (const find-file-other-frame)))
2156 (cons (const wl)
2157 (choice
2158 (const wl)
2159 (const wl-other-frame)))))
2161 (defcustom org-display-internal-link-with-indirect-buffer nil
2162 "Non-nil means use indirect buffer to display infile links.
2163 Activating internal links (from one location in a file to another location
2164 in the same file) normally just jumps to the location. When the link is
2165 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2166 is displayed in
2167 another window. When this option is set, the other window actually displays
2168 an indirect buffer clone of the current buffer, to avoid any visibility
2169 changes to the current buffer."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-open-non-existing-files nil
2174 "Non-nil means `org-open-file' will open non-existing files.
2175 When nil, an error will be generated.
2176 This variable applies only to external applications because they
2177 might choke on non-existing files. If the link is to a file that
2178 will be opened in Emacs, the variable is ignored."
2179 :group 'org-link-follow
2180 :type 'boolean)
2182 (defcustom org-open-directory-means-index-dot-org nil
2183 "Non-nil means a link to a directory really means to index.org.
2184 When nil, following a directory link will run dired or open a finder/explorer
2185 window on that directory."
2186 :group 'org-link-follow
2187 :type 'boolean)
2189 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2190 "Non-nil means ask for confirmation before executing shell links.
2191 Shell links can be dangerous: just think about a link
2193 [[shell:rm -rf ~/*][Google Search]]
2195 This link would show up in your Org document as \"Google Search\",
2196 but really it would remove your entire home directory.
2197 Therefore we advise against setting this variable to nil.
2198 Just change it to `y-or-n-p' if you want to confirm with a
2199 single keystroke rather than having to type \"yes\"."
2200 :group 'org-link-follow
2201 :type '(choice
2202 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2203 (const :tag "with y-or-n (faster)" y-or-n-p)
2204 (const :tag "no confirmation (dangerous)" nil)))
2205 (put 'org-confirm-shell-link-function
2206 'safe-local-variable
2207 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2209 (defcustom org-confirm-shell-link-not-regexp ""
2210 "A regexp to skip confirmation for shell links."
2211 :group 'org-link-follow
2212 :version "24.1"
2213 :type 'regexp)
2215 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2216 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2217 Elisp links can be dangerous: just think about a link
2219 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2221 This link would show up in your Org document as \"Google Search\",
2222 but really it would remove your entire home directory.
2223 Therefore we advise against setting this variable to nil.
2224 Just change it to `y-or-n-p' if you want to confirm with a
2225 single keystroke rather than having to type \"yes\"."
2226 :group 'org-link-follow
2227 :type '(choice
2228 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2229 (const :tag "with y-or-n (faster)" y-or-n-p)
2230 (const :tag "no confirmation (dangerous)" nil)))
2231 (put 'org-confirm-shell-link-function
2232 'safe-local-variable
2233 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2235 (defcustom org-confirm-elisp-link-not-regexp ""
2236 "A regexp to skip confirmation for Elisp links."
2237 :group 'org-link-follow
2238 :version "24.1"
2239 :type 'regexp)
2241 (defconst org-file-apps-defaults-gnu
2242 '((remote . emacs)
2243 (system . mailcap)
2244 (t . mailcap))
2245 "Default file applications on a UNIX or GNU/Linux system.
2246 See `org-file-apps'.")
2248 (defconst org-file-apps-defaults-macosx
2249 '((remote . emacs)
2250 (system . "open %s")
2251 ("ps.gz" . "gv %s")
2252 ("eps.gz" . "gv %s")
2253 ("dvi" . "xdvi %s")
2254 ("fig" . "xfig %s")
2255 (t . "open %s"))
2256 "Default file applications on a macOS system.
2257 The system \"open\" is known as a default, but we use X11 applications
2258 for some files for which the OS does not have a good default.
2259 See `org-file-apps'.")
2261 (defconst org-file-apps-defaults-windowsnt
2262 (list '(remote . emacs)
2263 (cons 'system (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file))))
2265 (cons t (lambda (file _path)
2266 (with-no-warnings (w32-shell-execute "open" file)))))
2267 "Default file applications on a Windows NT system.
2268 The system \"open\" is used for most files.
2269 See `org-file-apps'.")
2271 (defcustom org-file-apps
2272 '((auto-mode . emacs)
2273 ("\\.mm\\'" . default)
2274 ("\\.x?html?\\'" . default)
2275 ("\\.pdf\\'" . default))
2276 "External applications for opening `file:path' items in a document.
2277 \\<org-mode-map>\
2279 Org mode uses system defaults for different file types, but
2280 you can use this variable to set the application for a given file
2281 extension. The entries in this list are cons cells where the car identifies
2282 files and the cdr the corresponding command.
2284 Possible values for the file identifier are:
2286 \"string\" A string as a file identifier can be interpreted in different
2287 ways, depending on its contents:
2289 - Alphanumeric characters only:
2290 Match links with this file extension.
2291 Example: (\"pdf\" . \"evince %s\")
2292 to open PDFs with evince.
2294 - Regular expression: Match links where the
2295 filename matches the regexp. If you want to
2296 use groups here, use shy groups.
2298 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2299 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2300 to open *.html and *.xhtml with firefox.
2302 - Regular expression which contains (non-shy) groups:
2303 Match links where the whole link, including \"::\", and
2304 anything after that, matches the regexp.
2305 In a custom command string, %1, %2, etc. are replaced with
2306 the parts of the link that were matched by the groups.
2307 For backwards compatibility, if a command string is given
2308 that does not use any of the group matches, this case is
2309 handled identically to the second one (i.e. match against
2310 file name only).
2311 In a custom function, you can access the group matches with
2312 (match-string n link).
2314 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2315 \"evince -p %1 %s\")
2316 to open [[file:document.pdf::5]] with evince at page 5.
2318 `directory' Matches a directory
2319 `remote' Matches a remote file, accessible through tramp or efs.
2320 Remote files most likely should be visited through Emacs
2321 because external applications cannot handle such paths.
2322 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2323 so all files Emacs knows how to handle. Using this with
2324 command `emacs' will open most files in Emacs. Beware that this
2325 will also open html files inside Emacs, unless you add
2326 (\"html\" . default) to the list as well.
2327 `system' The system command to open files, like `open' on Windows
2328 and macOS, and mailcap under GNU/Linux. This is the command
2329 that will be selected if you call `org-open-at-point' with a
2330 double prefix argument (`\\[universal-argument] \
2331 \\[universal-argument] \\[org-open-at-point]').
2332 t Default for files not matched by any of the other options.
2334 Possible values for the command are:
2336 `emacs' The file will be visited by the current Emacs process.
2337 `default' Use the default application for this file type, which is the
2338 association for t in the list, most likely in the system-specific
2339 part. This can be used to overrule an unwanted setting in the
2340 system-specific variable.
2341 `system' Use the system command for opening files, like \"open\".
2342 This command is specified by the entry whose car is `system'.
2343 Most likely, the system-specific version of this variable
2344 does define this command, but you can overrule/replace it
2345 here.
2346 `mailcap' Use command specified in the mailcaps.
2347 string A command to be executed by a shell; %s will be replaced
2348 by the path to the file.
2349 function A Lisp function, which will be called with two arguments:
2350 the file path and the original link string, without the
2351 \"file:\" prefix.
2353 For more examples, see the system specific constants
2354 `org-file-apps-defaults-macosx'
2355 `org-file-apps-defaults-windowsnt'
2356 `org-file-apps-defaults-gnu'."
2357 :group 'org-link-follow
2358 :type '(repeat
2359 (cons (choice :value ""
2360 (string :tag "Extension")
2361 (const :tag "System command to open files" system)
2362 (const :tag "Default for unrecognized files" t)
2363 (const :tag "Remote file" remote)
2364 (const :tag "Links to a directory" directory)
2365 (const :tag "Any files that have Emacs modes"
2366 auto-mode))
2367 (choice :value ""
2368 (const :tag "Visit with Emacs" emacs)
2369 (const :tag "Use default" default)
2370 (const :tag "Use the system command" system)
2371 (string :tag "Command")
2372 (function :tag "Function")))))
2374 (defcustom org-doi-server-url "http://dx.doi.org/"
2375 "The URL of the DOI server."
2376 :type 'string
2377 :version "24.3"
2378 :group 'org-link-follow)
2380 (defgroup org-refile nil
2381 "Options concerning refiling entries in Org mode."
2382 :tag "Org Refile"
2383 :group 'org)
2385 (defcustom org-directory "~/org"
2386 "Directory with Org files.
2387 This is just a default location to look for Org files. There is no need
2388 at all to put your files into this directory. It is used in the
2389 following situations:
2391 1. When a capture template specifies a target file that is not an
2392 absolute path. The path will then be interpreted relative to
2393 `org-directory'
2394 2. When the value of variable `org-agenda-files' is a single file, any
2395 relative paths in this file will be taken as relative to
2396 `org-directory'."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'directory)
2401 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2402 "Default target for storing notes.
2403 Used as a fall back file for org-capture.el, for templates that
2404 do not specify a target file."
2405 :group 'org-refile
2406 :group 'org-capture
2407 :type 'file)
2409 (defcustom org-goto-interface 'outline
2410 "The default interface to be used for `org-goto'.
2411 Allowed values are:
2412 outline The interface shows an outline of the relevant file
2413 and the correct heading is found by moving through
2414 the outline or by searching with incremental search.
2415 outline-path-completion Headlines in the current buffer are offered via
2416 completion. This is the interface also used by
2417 the refile command."
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Outline" outline)
2421 (const :tag "Outline-path-completion" outline-path-completion)))
2423 (defcustom org-goto-max-level 5
2424 "Maximum target level when running `org-goto' with refile interface."
2425 :group 'org-refile
2426 :type 'integer)
2428 (defcustom org-reverse-note-order nil
2429 "Non-nil means store new notes at the beginning of a file or entry.
2430 When nil, new notes will be filed to the end of a file or entry.
2431 This can also be a list with cons cells of regular expressions that
2432 are matched against file names, and values."
2433 :group 'org-capture
2434 :group 'org-refile
2435 :type '(choice
2436 (const :tag "Reverse always" t)
2437 (const :tag "Reverse never" nil)
2438 (repeat :tag "By file name regexp"
2439 (cons regexp boolean))))
2441 (defcustom org-log-refile nil
2442 "Information to record when a task is refiled.
2444 Possible values are:
2446 nil Don't add anything
2447 time Add a time stamp to the task
2448 note Prompt for a note and add it with template `org-log-note-headings'
2450 This option can also be set with on a per-file-basis with
2452 #+STARTUP: nologrefile
2453 #+STARTUP: logrefile
2454 #+STARTUP: lognoterefile
2456 You can have local logging settings for a subtree by setting the LOGGING
2457 property to one or more of these keywords.
2459 When bulk-refiling from the agenda, the value `note' is forbidden and
2460 will temporarily be changed to `time'."
2461 :group 'org-refile
2462 :group 'org-progress
2463 :version "24.1"
2464 :type '(choice
2465 (const :tag "No logging" nil)
2466 (const :tag "Record timestamp" time)
2467 (const :tag "Record timestamp with note." note)))
2469 (defcustom org-refile-targets nil
2470 "Targets for refiling entries with `\\[org-refile]'.
2471 This is a list of cons cells. Each cell contains:
2472 - a specification of the files to be considered, either a list of files,
2473 or a symbol whose function or variable value will be used to retrieve
2474 a file name or a list of file names. If you use `org-agenda-files' for
2475 that, all agenda files will be scanned for targets. Nil means consider
2476 headings in the current buffer.
2477 - A specification of how to find candidate refile targets. This may be
2478 any of:
2479 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2480 This tag has to be present in all target headlines, inheritance will
2481 not be considered.
2482 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2483 todo keyword.
2484 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2485 headlines that are refiling targets.
2486 - a cons cell (:level . N). Any headline of level N is considered a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2489 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2490 Note that, when `org-odd-levels-only' is set, level corresponds to
2491 order in hierarchy, not to the number of stars.
2493 Each element of this list generates a set of possible targets.
2494 The union of these sets is presented (with completion) to
2495 the user by `org-refile'.
2497 You can set the variable `org-refile-target-verify-function' to a function
2498 to verify each headline found by the simple criteria above.
2500 When this variable is nil, all top-level headlines in the current buffer
2501 are used, equivalent to the value `((nil . (:level . 1))'."
2502 :group 'org-refile
2503 :type '(repeat
2504 (cons
2505 (choice :value org-agenda-files
2506 (const :tag "All agenda files" org-agenda-files)
2507 (const :tag "Current buffer" nil)
2508 (function) (variable) (file))
2509 (choice :tag "Identify target headline by"
2510 (cons :tag "Specific tag" (const :value :tag) (string))
2511 (cons :tag "TODO keyword" (const :value :todo) (string))
2512 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2513 (cons :tag "Level number" (const :value :level) (integer))
2514 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2516 (defcustom org-refile-target-verify-function nil
2517 "Function to verify if the headline at point should be a refile target.
2518 The function will be called without arguments, with point at the
2519 beginning of the headline. It should return t and leave point
2520 where it is if the headline is a valid target for refiling.
2522 If the target should not be selected, the function must return nil.
2523 In addition to this, it may move point to a place from where the search
2524 should be continued. For example, the function may decide that the entire
2525 subtree of the current entry should be excluded and move point to the end
2526 of the subtree."
2527 :group 'org-refile
2528 :type '(choice
2529 (const nil)
2530 (function)))
2532 (defcustom org-refile-use-cache nil
2533 "Non-nil means cache refile targets to speed up the process.
2534 \\<org-mode-map>\
2535 The cache for a particular file will be updated automatically when
2536 the buffer has been killed, or when any of the marker used for flagging
2537 refile targets no longer points at a live buffer.
2538 If you have added new entries to a buffer that might themselves be targets,
2539 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2540 if you find that easier, \
2541 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2542 \\[org-refile]'."
2543 :group 'org-refile
2544 :version "24.1"
2545 :type 'boolean)
2547 (defcustom org-refile-use-outline-path nil
2548 "Non-nil means provide refile targets as paths.
2549 So a level 3 headline will be available as level1/level2/level3.
2551 When the value is `file', also include the file name (without directory)
2552 into the path. In this case, you can also stop the completion after
2553 the file name, to get entries inserted as top level in the file.
2555 When `full-file-path', include the full file path."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Not" nil)
2559 (const :tag "Yes" t)
2560 (const :tag "Start with file name" file)
2561 (const :tag "Start with full file path" full-file-path)))
2563 (defcustom org-outline-path-complete-in-steps t
2564 "Non-nil means complete the outline path in hierarchical steps.
2565 When Org uses the refile interface to select an outline path (see
2566 `org-refile-use-outline-path'), the completion of the path can be
2567 done in a single go, or it can be done in steps down the headline
2568 hierarchy. Going in steps is probably the best if you do not use
2569 a special completion package like `ido' or `icicles'. However,
2570 when using these packages, going in one step can be very fast,
2571 while still showing the whole path to the entry."
2572 :group 'org-refile
2573 :type 'boolean)
2575 (defcustom org-refile-allow-creating-parent-nodes nil
2576 "Non-nil means allow the creation of new nodes as refile targets.
2577 New nodes are then created by adding \"/new node name\" to the completion
2578 of an existing node. When the value of this variable is `confirm',
2579 new node creation must be confirmed by the user (recommended).
2580 When nil, the completion must match an existing entry.
2582 Note that, if the new heading is not seen by the criteria
2583 listed in `org-refile-targets', multiple instances of the same
2584 heading would be created by trying again to file under the new
2585 heading."
2586 :group 'org-refile
2587 :type '(choice
2588 (const :tag "Never" nil)
2589 (const :tag "Always" t)
2590 (const :tag "Prompt for confirmation" confirm)))
2592 (defcustom org-refile-active-region-within-subtree nil
2593 "Non-nil means also refile active region within a subtree.
2595 By default `org-refile' doesn't allow refiling regions if they
2596 don't contain a set of subtrees, but it might be convenient to
2597 do so sometimes: in that case, the first line of the region is
2598 converted to a headline before refiling."
2599 :group 'org-refile
2600 :version "24.1"
2601 :type 'boolean)
2603 (defgroup org-todo nil
2604 "Options concerning TODO items in Org mode."
2605 :tag "Org TODO"
2606 :group 'org)
2608 (defgroup org-progress nil
2609 "Options concerning Progress logging in Org mode."
2610 :tag "Org Progress"
2611 :group 'org-time)
2613 (defvar org-todo-interpretation-widgets
2614 '((:tag "Sequence (cycling hits every state)" sequence)
2615 (:tag "Type (cycling directly to DONE)" type))
2616 "The available interpretation symbols for customizing `org-todo-keywords'.
2617 Interested libraries should add to this list.")
2619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2620 "List of TODO entry keyword sequences and their interpretation.
2621 \\<org-mode-map>This is a list of sequences.
2623 Each sequence starts with a symbol, either `sequence' or `type',
2624 indicating if the keywords should be interpreted as a sequence of
2625 action steps, or as different types of TODO items. The first
2626 keywords are states requiring action - these states will select a headline
2627 for inclusion into the global TODO list Org produces. If one of the
2628 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2629 signify that no further action is necessary. If \"|\" is not found,
2630 the last keyword is treated as the only DONE state of the sequence.
2632 The command `\\[org-todo]' cycles an entry through these states, and one
2633 additional state where no keyword is present. For details about this
2634 cycling, see the manual.
2636 TODO keywords and interpretation can also be set on a per-file basis with
2637 the special #+SEQ_TODO and #+TYP_TODO lines.
2639 Each keyword can optionally specify a character for fast state selection
2640 \(in combination with the variable `org-use-fast-todo-selection')
2641 and specifiers for state change logging, using the same syntax that
2642 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2643 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2644 indicates to record a time stamp each time this state is selected.
2646 Each keyword may also specify if a timestamp or a note should be
2647 recorded when entering or leaving the state, by adding additional
2648 characters in the parenthesis after the keyword. This looks like this:
2649 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2650 record only the time of the state change. With X and Y being either
2651 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2652 Y when leaving the state if and only if the *target* state does not
2653 define X. You may omit any of the fast-selection key or X or /Y,
2654 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2656 For backward compatibility, this variable may also be just a list
2657 of keywords. In this case the interpretation (sequence or type) will be
2658 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice
2662 (repeat :tag "Old syntax, just keywords"
2663 (string :tag "Keyword"))
2664 (repeat :tag "New syntax"
2665 (cons
2666 (choice
2667 :tag "Interpretation"
2668 ;;Quick and dirty way to see
2669 ;;`org-todo-interpretations'. This takes the
2670 ;;place of item arguments
2671 :convert-widget
2672 (lambda (widget)
2673 (widget-put widget
2674 :args (mapcar
2675 (lambda (x)
2676 (widget-convert
2677 (cons 'const x)))
2678 org-todo-interpretation-widgets))
2679 widget))
2680 (repeat
2681 (string :tag "Keyword"))))))
2683 (defvar-local org-todo-keywords-1 nil
2684 "All TODO and DONE keywords active in a buffer.")
2685 (defvar org-todo-keywords-for-agenda nil)
2686 (defvar org-done-keywords-for-agenda nil)
2687 (defvar org-todo-keyword-alist-for-agenda nil)
2688 (defvar org-tag-alist-for-agenda nil
2689 "Alist of all tags from all agenda files.")
2690 (defvar org-tag-groups-alist-for-agenda nil
2691 "Alist of all groups tags from all current agenda files.")
2692 (defvar-local org-tag-groups-alist nil)
2693 (defvar org-agenda-contributing-files nil)
2694 (defvar-local org-current-tag-alist nil
2695 "Alist of all tag groups in current buffer.
2696 This variable takes into consideration `org-tag-alist',
2697 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2698 (defvar-local org-not-done-keywords nil)
2699 (defvar-local org-done-keywords nil)
2700 (defvar-local org-todo-heads nil)
2701 (defvar-local org-todo-sets nil)
2702 (defvar-local org-todo-log-states nil)
2703 (defvar-local org-todo-kwd-alist nil)
2704 (defvar-local org-todo-key-alist nil)
2705 (defvar-local org-todo-key-trigger nil)
2707 (defcustom org-todo-interpretation 'sequence
2708 "Controls how TODO keywords are interpreted.
2709 This variable is in principle obsolete and is only used for
2710 backward compatibility, if the interpretation of todo keywords is
2711 not given already in `org-todo-keywords'. See that variable for
2712 more information."
2713 :group 'org-todo
2714 :group 'org-keywords
2715 :type '(choice (const sequence)
2716 (const type)))
2718 (defcustom org-use-fast-todo-selection t
2719 "\\<org-mode-map>\
2720 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2721 This variable describes if and under what circumstances the cycling
2722 mechanism for TODO keywords will be replaced by a single-key, direct
2723 selection scheme.
2725 When nil, fast selection is never used.
2727 When the symbol `prefix', it will be used when `org-todo' is called
2728 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2729 in an Org buffer, and
2730 `\\[universal-argument] t' in an agenda buffer.
2732 When t, fast selection is used by default. In this case, the prefix
2733 argument forces cycling instead.
2735 In all cases, the special interface is only used if access keys have
2736 actually been assigned by the user, i.e. if keywords in the configuration
2737 are followed by a letter in parenthesis, like TODO(t)."
2738 :group 'org-todo
2739 :type '(choice
2740 (const :tag "Never" nil)
2741 (const :tag "By default" t)
2742 (const :tag "Only with C-u C-c C-t" prefix)))
2744 (defcustom org-provide-todo-statistics t
2745 "Non-nil means update todo statistics after insert and toggle.
2746 ALL-HEADLINES means update todo statistics by including headlines
2747 with no TODO keyword as well, counting them as not done.
2748 A list of TODO keywords means the same, but skip keywords that are
2749 not in this list.
2750 When set to a list of two lists, the first list contains keywords
2751 to consider as TODO keywords, the second list contains keywords
2752 to consider as DONE keywords.
2754 When this is set, todo statistics is updated in the parent of the
2755 current entry each time a todo state is changed."
2756 :group 'org-todo
2757 :type '(choice
2758 (const :tag "Yes, only for TODO entries" t)
2759 (const :tag "Yes, including all entries" all-headlines)
2760 (repeat :tag "Yes, for TODOs in this list"
2761 (string :tag "TODO keyword"))
2762 (list :tag "Yes, for TODOs and DONEs in these lists"
2763 (repeat (string :tag "TODO keyword"))
2764 (repeat (string :tag "DONE keyword")))
2765 (other :tag "No TODO statistics" nil)))
2767 (defcustom org-hierarchical-todo-statistics t
2768 "Non-nil means TODO statistics covers just direct children.
2769 When nil, all entries in the subtree are considered.
2770 This has only an effect if `org-provide-todo-statistics' is set.
2771 To set this to nil for only a single subtree, use a COOKIE_DATA
2772 property and include the word \"recursive\" into the value."
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-after-todo-state-change-hook nil
2777 "Hook which is run after the state of a TODO item was changed.
2778 The new state (a string with a TODO keyword, or nil) is available in the
2779 Lisp variable `org-state'."
2780 :group 'org-todo
2781 :type 'hook)
2783 (defvar org-blocker-hook nil
2784 "Hook for functions that are allowed to block a state change.
2786 Functions in this hook should not modify the buffer.
2787 Each function gets as its single argument a property list,
2788 see `org-trigger-hook' for more information about this list.
2790 If any of the functions in this hook returns nil, the state change
2791 is blocked.")
2793 (defvar org-trigger-hook nil
2794 "Hook for functions that are triggered by a state change.
2796 Each function gets as its single argument a property list with at
2797 least the following elements:
2799 (:type type-of-change :position pos-at-entry-start
2800 :from old-state :to new-state)
2802 Depending on the type, more properties may be present.
2804 This mechanism is currently implemented for:
2806 TODO state changes
2807 ------------------
2808 :type todo-state-change
2809 :from previous state (keyword as a string), or nil, or a symbol
2810 `todo' or `done', to indicate the general type of state.
2811 :to new state, like in :from")
2813 (defcustom org-enforce-todo-dependencies nil
2814 "Non-nil means undone TODO entries will block switching the parent to DONE.
2815 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2816 be blocked if any prior sibling is not yet done.
2817 Finally, if the parent is blocked because of ordered siblings of its own,
2818 the child will also be blocked."
2819 :set (lambda (var val)
2820 (set var val)
2821 (if val
2822 (add-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)
2824 (remove-hook 'org-blocker-hook
2825 'org-block-todo-from-children-or-siblings-or-parent)))
2826 :group 'org-todo
2827 :type 'boolean)
2829 (defcustom org-enforce-todo-checkbox-dependencies nil
2830 "Non-nil means unchecked boxes will block switching the parent to DONE.
2831 When this is nil, checkboxes have no influence on switching TODO states.
2832 When non-nil, you first need to check off all check boxes before the TODO
2833 entry can be switched to DONE.
2834 This variable needs to be set before org.el is loaded, and you need to
2835 restart Emacs after a change to make the change effective. The only way
2836 to change is while Emacs is running is through the customize interface."
2837 :set (lambda (var val)
2838 (set var val)
2839 (if val
2840 (add-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)
2842 (remove-hook 'org-blocker-hook
2843 'org-block-todo-from-checkboxes)))
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-treat-insert-todo-heading-as-state-change nil
2848 "Non-nil means inserting a TODO heading is treated as state change.
2849 So when the command `\\[org-insert-todo-heading]' is used, state change
2850 logging will apply if appropriate. When nil, the new TODO item will
2851 be inserted directly, and no logging will take place."
2852 :group 'org-todo
2853 :type 'boolean)
2855 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2856 "Non-nil means switching TODO states with S-cursor counts as state change.
2857 This is the default behavior. However, setting this to nil allows a
2858 convenient way to select a TODO state and bypass any logging associated
2859 with that."
2860 :group 'org-todo
2861 :type 'boolean)
2863 (defcustom org-todo-state-tags-triggers nil
2864 "Tag changes that should be triggered by TODO state changes.
2865 This is a list. Each entry is
2867 (state-change (tag . flag) .......)
2869 State-change can be a string with a state, and empty string to indicate the
2870 state that has no TODO keyword, or it can be one of the symbols `todo'
2871 or `done', meaning any not-done or done state, respectively."
2872 :group 'org-todo
2873 :group 'org-tags
2874 :type '(repeat
2875 (cons (choice :tag "When changing to"
2876 (const :tag "Not-done state" todo)
2877 (const :tag "Done state" done)
2878 (string :tag "State"))
2879 (repeat
2880 (cons :tag "Tag action"
2881 (string :tag "Tag")
2882 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2884 (defcustom org-log-done nil
2885 "Information to record when a task moves to the DONE state.
2887 Possible values are:
2889 nil Don't add anything, just change the keyword
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologdone
2896 #+STARTUP: logdone
2897 #+STARTUP: lognotedone
2899 You can have local logging settings for a subtree by setting the LOGGING
2900 property to one or more of these keywords."
2901 :group 'org-todo
2902 :group 'org-progress
2903 :type '(choice
2904 (const :tag "No logging" nil)
2905 (const :tag "Record CLOSED timestamp" time)
2906 (const :tag "Record CLOSED timestamp with note." note)))
2908 ;; Normalize old uses of org-log-done.
2909 (cond
2910 ((eq org-log-done t) (setq org-log-done 'time))
2911 ((and (listp org-log-done) (memq 'done org-log-done))
2912 (setq org-log-done 'note)))
2914 (defcustom org-log-reschedule nil
2915 "Information to record when the scheduling date of a tasks is modified.
2917 Possible values are:
2919 nil Don't add anything, just change the date
2920 time Add a time stamp to the task
2921 note Prompt for a note and add it with template `org-log-note-headings'
2923 This option can also be set with on a per-file-basis with
2925 #+STARTUP: nologreschedule
2926 #+STARTUP: logreschedule
2927 #+STARTUP: lognotereschedule"
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "No logging" nil)
2932 (const :tag "Record timestamp" time)
2933 (const :tag "Record timestamp with note." note)))
2935 (defcustom org-log-redeadline nil
2936 "Information to record when the deadline date of a tasks is modified.
2938 Possible values are:
2940 nil Don't add anything, just change the date
2941 time Add a time stamp to the task
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologredeadline
2947 #+STARTUP: logredeadline
2948 #+STARTUP: lognoteredeadline
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "No logging" nil)
2956 (const :tag "Record timestamp" time)
2957 (const :tag "Record timestamp with note." note)))
2959 (defcustom org-log-note-clock-out nil
2960 "Non-nil means record a note when clocking out of an item.
2961 This can also be configured on a per-file basis by adding one of
2962 the following lines anywhere in the buffer:
2964 #+STARTUP: lognoteclock-out
2965 #+STARTUP: nolognoteclock-out"
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-done-with-time t
2971 "Non-nil means the CLOSED time stamp will contain date and time.
2972 When nil, only the date will be recorded."
2973 :group 'org-progress
2974 :type 'boolean)
2976 (defcustom org-log-note-headings
2977 '((done . "CLOSING NOTE %t")
2978 (state . "State %-12s from %-12S %t")
2979 (note . "Note taken on %t")
2980 (reschedule . "Rescheduled from %S on %t")
2981 (delschedule . "Not scheduled, was %S on %t")
2982 (redeadline . "New deadline from %S on %t")
2983 (deldeadline . "Removed deadline, was %S on %t")
2984 (refile . "Refiled on %t")
2985 (clock-out . ""))
2986 "Headings for notes added to entries.
2988 The value is an alist, with the car being a symbol indicating the
2989 note context, and the cdr is the heading to be used. The heading
2990 may also be the empty string. The following placeholders can be
2991 used:
2993 %t a time stamp.
2994 %T an active time stamp instead the default inactive one
2995 %d a short-format time stamp.
2996 %D an active short-format time stamp.
2997 %s the new TODO state or time stamp (inactive), in double quotes.
2998 %S the old TODO state or time stamp (inactive), in double quotes.
2999 %u the user name.
3000 %U full user name.
3002 In fact, it is not a good idea to change the `state' entry,
3003 because Agenda Log mode depends on the format of these entries."
3004 :group 'org-todo
3005 :group 'org-progress
3006 :type '(list :greedy t
3007 (cons (const :tag "Heading when closing an item" done) string)
3008 (cons (const :tag
3009 "Heading when changing todo state (todo sequence only)"
3010 state) string)
3011 (cons (const :tag "Heading when just taking a note" note) string)
3012 (cons (const :tag "Heading when rescheduling" reschedule) string)
3013 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3014 (cons (const :tag "Heading when changing deadline" redeadline) string)
3015 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3016 (cons (const :tag "Heading when refiling" refile) string)
3017 (cons (const :tag "Heading when clocking out" clock-out) string)))
3019 (unless (assq 'note org-log-note-headings)
3020 (push '(note . "%t") org-log-note-headings))
3022 (defcustom org-log-into-drawer nil
3023 "Non-nil means insert state change notes and time stamps into a drawer.
3024 When nil, state changes notes will be inserted after the headline and
3025 any scheduling and clock lines, but not inside a drawer.
3027 The value of this variable should be the name of the drawer to use.
3028 LOGBOOK is proposed as the default drawer for this purpose, you can
3029 also set this to a string to define the drawer of your choice.
3031 A value of t is also allowed, representing \"LOGBOOK\".
3033 A value of t or nil can also be set with on a per-file-basis with
3035 #+STARTUP: logdrawer
3036 #+STARTUP: nologdrawer
3038 If this variable is set, `org-log-state-notes-insert-after-drawers'
3039 will be ignored.
3041 You can set the property LOG_INTO_DRAWER to overrule this setting for
3042 a subtree.
3044 Do not check directly this variable in a Lisp program. Call
3045 function `org-log-into-drawer' instead."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type '(choice
3049 (const :tag "Not into a drawer" nil)
3050 (const :tag "LOGBOOK" t)
3051 (string :tag "Other")))
3053 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3055 (defun org-log-into-drawer ()
3056 "Name of the log drawer, as a string, or nil.
3057 This is the value of `org-log-into-drawer'. However, if the
3058 current entry has or inherits a LOG_INTO_DRAWER property, it will
3059 be used instead of the default value."
3060 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3061 (cond ((equal p "nil") nil)
3062 ((equal p "t") "LOGBOOK")
3063 ((stringp p) p)
3064 (p "LOGBOOK")
3065 ((stringp org-log-into-drawer) org-log-into-drawer)
3066 (org-log-into-drawer "LOGBOOK"))))
3068 (defcustom org-log-state-notes-insert-after-drawers nil
3069 "Non-nil means insert state change notes after any drawers in entry.
3070 Only the drawers that *immediately* follow the headline and the
3071 deadline/scheduled line are skipped.
3072 When nil, insert notes right after the heading and perhaps the line
3073 with deadline/scheduling if present.
3075 This variable will have no effect if `org-log-into-drawer' is
3076 set."
3077 :group 'org-todo
3078 :group 'org-progress
3079 :type 'boolean)
3081 (defcustom org-log-states-order-reversed t
3082 "Non-nil means the latest state note will be directly after heading.
3083 When nil, the state change notes will be ordered according to time.
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: logstatesreversed
3088 #+STARTUP: nologstatesreversed"
3089 :group 'org-todo
3090 :group 'org-progress
3091 :type 'boolean)
3093 (defcustom org-todo-repeat-to-state nil
3094 "The TODO state to which a repeater should return the repeating task.
3095 By default this is the first task in a TODO sequence, or the previous state
3096 in a TODO_TYP set. But you can specify another task here.
3097 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3098 :group 'org-todo
3099 :version "24.1"
3100 :type '(choice (const :tag "Head of sequence" nil)
3101 (string :tag "Specific state")))
3103 (defcustom org-log-repeat 'time
3104 "Non-nil means record moving through the DONE state when triggering repeat.
3105 An auto-repeating task is immediately switched back to TODO when
3106 marked DONE. If you are not logging state changes (by adding \"@\"
3107 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3108 record a closing note, there will be no record of the task moving
3109 through DONE. This variable forces taking a note anyway.
3111 nil Don't force a record
3112 time Record a time stamp
3113 note Prompt for a note and add it with template `org-log-note-headings'
3115 This option can also be set with on a per-file-basis with
3117 #+STARTUP: nologrepeat
3118 #+STARTUP: logrepeat
3119 #+STARTUP: lognoterepeat
3121 You can have local logging settings for a subtree by setting the LOGGING
3122 property to one or more of these keywords."
3123 :group 'org-todo
3124 :group 'org-progress
3125 :type '(choice
3126 (const :tag "Don't force a record" nil)
3127 (const :tag "Force recording the DONE state" time)
3128 (const :tag "Force recording a note with the DONE state" note)))
3131 (defgroup org-priorities nil
3132 "Priorities in Org mode."
3133 :tag "Org Priorities"
3134 :group 'org-todo)
3136 (defcustom org-enable-priority-commands t
3137 "Non-nil means priority commands are active.
3138 When nil, these commands will be disabled, so that you never accidentally
3139 set a priority."
3140 :group 'org-priorities
3141 :type 'boolean)
3143 (defcustom org-highest-priority ?A
3144 "The highest priority of TODO items. A character like ?A, ?B etc.
3145 Must have a smaller ASCII number than `org-lowest-priority'."
3146 :group 'org-priorities
3147 :type 'character)
3149 (defcustom org-lowest-priority ?C
3150 "The lowest priority of TODO items. A character like ?A, ?B etc.
3151 Must have a larger ASCII number than `org-highest-priority'."
3152 :group 'org-priorities
3153 :type 'character)
3155 (defcustom org-default-priority ?B
3156 "The default priority of TODO items.
3157 This is the priority an item gets if no explicit priority is given.
3158 When starting to cycle on an empty priority the first step in the cycle
3159 depends on `org-priority-start-cycle-with-default'. The resulting first
3160 step priority must not exceed the range from `org-highest-priority' to
3161 `org-lowest-priority' which means that `org-default-priority' has to be
3162 in this range exclusive or inclusive the range boundaries. Else the
3163 first step refuses to set the default and the second will fall back
3164 to (depending on the command used) the highest or lowest priority."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-priority-start-cycle-with-default t
3169 "Non-nil means start with default priority when starting to cycle.
3170 When this is nil, the first step in the cycle will be (depending on the
3171 command used) one higher or lower than the default priority.
3172 See also `org-default-priority'."
3173 :group 'org-priorities
3174 :type 'boolean)
3176 (defcustom org-get-priority-function nil
3177 "Function to extract the priority from a string.
3178 The string is normally the headline. If this is nil Org computes the
3179 priority from the priority cookie like [#A] in the headline. It returns
3180 an integer, increasing by 1000 for each priority level.
3181 The user can set a different function here, which should take a string
3182 as an argument and return the numeric priority."
3183 :group 'org-priorities
3184 :version "24.1"
3185 :type '(choice
3186 (const nil)
3187 (function)))
3189 (defgroup org-time nil
3190 "Options concerning time stamps and deadlines in Org mode."
3191 :tag "Org Time"
3192 :group 'org)
3194 (defcustom org-time-stamp-rounding-minutes '(0 5)
3195 "Number of minutes to round time stamps to.
3196 \\<org-mode-map>\
3197 These are two values, the first applies when first creating a time stamp.
3198 The second applies when changing it with the commands `S-up' and `S-down'.
3199 When changing the time stamp, this means that it will change in steps
3200 of N minutes, as given by the second value.
3202 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3203 numbers should be factors of 60, so for example 5, 10, 15.
3205 When this is larger than 1, you can still force an exact time stamp by using
3206 a double prefix argument to a time stamp command like \
3207 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3208 and by using a prefix arg to `S-up/down' to specify the exact number
3209 of minutes to shift."
3210 :group 'org-time
3211 :get (lambda (var) ; Make sure both elements are there
3212 (if (integerp (default-value var))
3213 (list (default-value var) 5)
3214 (default-value var)))
3215 :type '(list
3216 (integer :tag "when inserting times")
3217 (integer :tag "when modifying times")))
3219 ;; Normalize old customizations of this variable.
3220 (when (integerp org-time-stamp-rounding-minutes)
3221 (setq org-time-stamp-rounding-minutes
3222 (list org-time-stamp-rounding-minutes
3223 org-time-stamp-rounding-minutes)))
3225 (defcustom org-display-custom-times nil
3226 "Non-nil means overlay custom formats over all time stamps.
3227 The formats are defined through the variable `org-time-stamp-custom-formats'.
3228 To turn this on on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: customtime"
3230 :group 'org-time
3231 :set 'set-default
3232 :type 'sexp)
3233 (make-variable-buffer-local 'org-display-custom-times)
3235 (defcustom org-time-stamp-custom-formats
3236 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3237 "Custom formats for time stamps. See `format-time-string' for the syntax.
3238 These are overlaid over the default ISO format if the variable
3239 `org-display-custom-times' is set. Time like %H:%M should be at the
3240 end of the second format. The custom formats are also honored by export
3241 commands, if custom time display is turned on at the time of export."
3242 :group 'org-time
3243 :type 'sexp)
3245 (defun org-time-stamp-format (&optional long inactive)
3246 "Get the right format for a time string."
3247 (let ((f (if long (cdr org-time-stamp-formats)
3248 (car org-time-stamp-formats))))
3249 (if inactive
3250 (concat "[" (substring f 1 -1) "]")
3251 f)))
3253 (defcustom org-time-clocksum-format
3254 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3255 "The format string used when creating CLOCKSUM lines.
3256 This is also used when Org mode generates a time duration.
3258 The value can be a single format string containing two
3259 %-sequences, which will be filled with the number of hours and
3260 minutes in that order.
3262 Alternatively, the value can be a plist associating any of the
3263 keys :years, :months, :weeks, :days, :hours or :minutes with
3264 format strings. The time duration is formatted using only the
3265 time components that are needed and concatenating the results.
3266 If a time unit in absent, it falls back to the next smallest
3267 unit.
3269 The keys :require-years, :require-months, :require-days,
3270 :require-weeks, :require-hours, :require-minutes are also
3271 meaningful. A non-nil value for these keys indicates that the
3272 corresponding time component should always be included, even if
3273 its value is 0.
3276 For example,
3278 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3279 :require-minutes t)
3281 means durations longer than a day will be expressed in days,
3282 hours and minutes, and durations less than a day will always be
3283 expressed in hours and minutes (even for durations less than an
3284 hour).
3286 The value
3288 (:days \"%dd\" :minutes \"%dm\")
3290 means durations longer than a day will be expressed in days and
3291 minutes, and durations less than a day will be expressed entirely
3292 in minutes (even for durations longer than an hour)."
3293 :group 'org-time
3294 :group 'org-clock
3295 :version "24.4"
3296 :package-version '(Org . "8.0")
3297 :type '(choice (string :tag "Format string")
3298 (set :tag "Plist"
3299 (group :inline t (const :tag "Years" :years)
3300 (string :tag "Format string"))
3301 (group :inline t
3302 (const :tag "Always show years" :require-years)
3303 (const t))
3304 (group :inline t (const :tag "Months" :months)
3305 (string :tag "Format string"))
3306 (group :inline t
3307 (const :tag "Always show months" :require-months)
3308 (const t))
3309 (group :inline t (const :tag "Weeks" :weeks)
3310 (string :tag "Format string"))
3311 (group :inline t
3312 (const :tag "Always show weeks" :require-weeks)
3313 (const t))
3314 (group :inline t (const :tag "Days" :days)
3315 (string :tag "Format string"))
3316 (group :inline t
3317 (const :tag "Always show days" :require-days)
3318 (const t))
3319 (group :inline t (const :tag "Hours" :hours)
3320 (string :tag "Format string"))
3321 (group :inline t
3322 (const :tag "Always show hours" :require-hours)
3323 (const t))
3324 (group :inline t (const :tag "Minutes" :minutes)
3325 (string :tag "Format string"))
3326 (group :inline t
3327 (const :tag "Always show minutes" :require-minutes)
3328 (const t)))))
3330 (defcustom org-time-clocksum-use-fractional nil
3331 "When non-nil, `\\[org-clock-display]' uses fractional times.
3332 See `org-time-clocksum-format' for more on time clock formats."
3333 :group 'org-time
3334 :group 'org-clock
3335 :version "24.3"
3336 :type 'boolean)
3338 (defcustom org-time-clocksum-use-effort-durations nil
3339 "When non-nil, `\\[org-clock-display]' uses effort durations.
3340 E.g. by default, one day is considered to be a 8 hours effort,
3341 so a task that has been clocked for 16 hours will be displayed
3342 as during 2 days in the clock display or in the clocktable.
3344 See `org-effort-durations' on how to set effort durations
3345 and `org-time-clocksum-format' for more on time clock formats."
3346 :group 'org-time
3347 :group 'org-clock
3348 :version "24.4"
3349 :package-version '(Org . "8.0")
3350 :type 'boolean)
3352 (defcustom org-time-clocksum-fractional-format "%.2f"
3353 "The format string used when creating CLOCKSUM lines,
3354 or when Org mode generates a time duration, if
3355 `org-time-clocksum-use-fractional' is enabled.
3357 The value can be a single format string containing one
3358 %-sequence, which will be filled with the number of hours as
3359 a float.
3361 Alternatively, the value can be a plist associating any of the
3362 keys :years, :months, :weeks, :days, :hours or :minutes with
3363 a format string. The time duration is formatted using the
3364 largest time unit which gives a non-zero integer part. If all
3365 specified formats have zero integer part, the smallest time unit
3366 is used."
3367 :group 'org-time
3368 :type '(choice (string :tag "Format string")
3369 (set (group :inline t (const :tag "Years" :years)
3370 (string :tag "Format string"))
3371 (group :inline t (const :tag "Months" :months)
3372 (string :tag "Format string"))
3373 (group :inline t (const :tag "Weeks" :weeks)
3374 (string :tag "Format string"))
3375 (group :inline t (const :tag "Days" :days)
3376 (string :tag "Format string"))
3377 (group :inline t (const :tag "Hours" :hours)
3378 (string :tag "Format string"))
3379 (group :inline t (const :tag "Minutes" :minutes)
3380 (string :tag "Format string")))))
3382 (defcustom org-deadline-warning-days 14
3383 "Number of days before expiration during which a deadline becomes active.
3384 This variable governs the display in sparse trees and in the agenda.
3385 When 0 or negative, it means use this number (the absolute value of it)
3386 even if a deadline has a different individual lead time specified.
3388 Custom commands can set this variable in the options section."
3389 :group 'org-time
3390 :group 'org-agenda-daily/weekly
3391 :type 'integer)
3393 (defcustom org-scheduled-delay-days 0
3394 "Number of days before a scheduled item becomes active.
3395 This variable governs the display in sparse trees and in the agenda.
3396 The default value (i.e. 0) means: don't delay scheduled item.
3397 When negative, it means use this number (the absolute value of it)
3398 even if a scheduled item has a different individual delay time
3399 specified.
3401 Custom commands can set this variable in the options section."
3402 :group 'org-time
3403 :group 'org-agenda-daily/weekly
3404 :version "24.4"
3405 :package-version '(Org . "8.0")
3406 :type 'integer)
3408 (defcustom org-read-date-prefer-future t
3409 "Non-nil means assume future for incomplete date input from user.
3410 This affects the following situations:
3411 1. The user gives a month but not a year.
3412 For example, if it is April and you enter \"feb 2\", this will be read
3413 as Feb 2, *next* year. \"May 5\", however, will be this year.
3414 2. The user gives a day, but no month.
3415 For example, if today is the 15th, and you enter \"3\", Org will read
3416 this as the third of *next* month. However, if you enter \"17\",
3417 it will be considered as *this* month.
3419 If you set this variable to the symbol `time', then also the following
3420 will work:
3422 3. If the user gives a time.
3423 If the time is before now, it will be interpreted as tomorrow.
3425 Currently none of this works for ISO week specifications.
3427 When this option is nil, the current day, month and year will always be
3428 used as defaults.
3430 See also `org-agenda-jump-prefer-future'."
3431 :group 'org-time
3432 :type '(choice
3433 (const :tag "Never" nil)
3434 (const :tag "Check month and day" t)
3435 (const :tag "Check month, day, and time" time)))
3437 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3438 "Should the agenda jump command prefer the future for incomplete dates?
3439 The default is to do the same as configured in `org-read-date-prefer-future'.
3440 But you can also set a deviating value here.
3441 This may t or nil, or the symbol `org-read-date-prefer-future'."
3442 :group 'org-agenda
3443 :group 'org-time
3444 :version "24.1"
3445 :type '(choice
3446 (const :tag "Use org-read-date-prefer-future"
3447 org-read-date-prefer-future)
3448 (const :tag "Never" nil)
3449 (const :tag "Always" t)))
3451 (defcustom org-read-date-force-compatible-dates t
3452 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3454 Depending on the system Emacs is running on, certain dates cannot
3455 be represented with the type used internally to represent time.
3456 Dates between 1970-1-1 and 2038-1-1 can always be represented
3457 correctly. Some systems allow for earlier dates, some for later,
3458 some for both. One way to find out it to insert any date into an
3459 Org buffer, putting the cursor on the year and hitting S-up and
3460 S-down to test the range.
3462 When this variable is set to t, the date/time prompt will not let
3463 you specify dates outside the 1970-2037 range, so it is certain that
3464 these dates will work in whatever version of Emacs you are
3465 running, and also that you can move a file from one Emacs implementation
3466 to another. WHenever Org is forcing the year for you, it will display
3467 a message and beep.
3469 When this variable is nil, Org will check if the date is
3470 representable in the specific Emacs implementation you are using.
3471 If not, it will force a year, usually the current year, and beep
3472 to remind you. Currently this setting is not recommended because
3473 the likelihood that you will open your Org files in an Emacs that
3474 has limited date range is not negligible.
3476 A workaround for this problem is to use diary sexp dates for time
3477 stamps outside of this range."
3478 :group 'org-time
3479 :version "24.1"
3480 :type 'boolean)
3482 (defcustom org-read-date-display-live t
3483 "Non-nil means display current interpretation of date prompt live.
3484 This display will be in an overlay, in the minibuffer."
3485 :group 'org-time
3486 :type 'boolean)
3488 (defcustom org-read-date-popup-calendar t
3489 "Non-nil means pop up a calendar when prompting for a date.
3490 In the calendar, the date can be selected with mouse-1. However, the
3491 minibuffer will also be active, and you can simply enter the date as well.
3492 When nil, only the minibuffer will be available."
3493 :group 'org-time
3494 :type 'boolean)
3495 (defvaralias 'org-popup-calendar-for-date-prompt
3496 'org-read-date-popup-calendar)
3498 (defcustom org-extend-today-until 0
3499 "The hour when your day really ends. Must be an integer.
3500 This has influence for the following applications:
3501 - When switching the agenda to \"today\". It it is still earlier than
3502 the time given here, the day recognized as TODAY is actually yesterday.
3503 - When a date is read from the user and it is still before the time given
3504 here, the current date and time will be assumed to be yesterday, 23:59.
3505 Also, timestamps inserted in capture templates follow this rule.
3507 IMPORTANT: This is a feature whose implementation is and likely will
3508 remain incomplete. Really, it is only here because past midnight seems to
3509 be the favorite working time of John Wiegley :-)"
3510 :group 'org-time
3511 :type 'integer)
3513 (defcustom org-use-effective-time nil
3514 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3515 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3516 \"effective time\" of any timestamps between midnight and 8am will be
3517 23:59 of the previous day."
3518 :group 'org-time
3519 :version "24.1"
3520 :type 'boolean)
3522 (defcustom org-use-last-clock-out-time-as-effective-time nil
3523 "When non-nil, use the last clock out time for `org-todo'.
3524 Note that this option has precedence over the combined use of
3525 `org-use-effective-time' and `org-extend-today-until'."
3526 :group 'org-time
3527 :version "24.4"
3528 :package-version '(Org . "8.0")
3529 :type 'boolean)
3531 (defcustom org-edit-timestamp-down-means-later nil
3532 "Non-nil means S-down will increase the time in a time stamp.
3533 When nil, S-up will increase."
3534 :group 'org-time
3535 :type 'boolean)
3537 (defcustom org-calendar-follow-timestamp-change t
3538 "Non-nil means make the calendar window follow timestamp changes.
3539 When a timestamp is modified and the calendar window is visible, it will be
3540 moved to the new date."
3541 :group 'org-time
3542 :type 'boolean)
3544 (defgroup org-tags nil
3545 "Options concerning tags in Org mode."
3546 :tag "Org Tags"
3547 :group 'org)
3549 (defcustom org-tag-alist nil
3550 "Default tags available in Org files.
3552 The value of this variable is an alist. Associations either:
3554 (TAG)
3555 (TAG . SELECT)
3556 (SPECIAL)
3558 where TAG is a tag as a string, SELECT is character, used to
3559 select that tag through the fast tag selection interface, and
3560 SPECIAL is one of the following keywords: `:startgroup',
3561 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3562 `:newline'. These keywords are used to define a hierarchy of
3563 tags. See manual for details.
3565 When this variable is nil, Org mode bases tag input on what is
3566 already in the buffer. The value can be overridden locally by
3567 using a TAGS keyword, e.g.,
3569 #+TAGS: tag1 tag2
3571 See also `org-tag-persistent-alist' to sidestep this behavior."
3572 :group 'org-tags
3573 :type '(repeat
3574 (choice
3575 (cons (string :tag "Tag name")
3576 (character :tag "Access char"))
3577 (const :tag "Start radio group" (:startgroup))
3578 (const :tag "Start tag group, non distinct" (:startgrouptag))
3579 (const :tag "Group tags delimiter" (:grouptags))
3580 (const :tag "End radio group" (:endgroup))
3581 (const :tag "End tag group, non distinct" (:endgrouptag))
3582 (const :tag "New line" (:newline)))))
3584 (defcustom org-tag-persistent-alist nil
3585 "Tags always available in Org files.
3587 The value of this variable is an alist. Associations either:
3589 (TAG)
3590 (TAG . SELECT)
3591 (SPECIAL)
3593 where TAG is a tag as a string, SELECT is a character, used to
3594 select that tag through the fast tag selection interface, and
3595 SPECIAL is one of the following keywords: `:startgroup',
3596 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3597 `:newline'. These keywords are used to define a hierarchy of
3598 tags. See manual for details.
3600 Unlike to `org-tag-alist', tags defined in this variable do not
3601 depend on a local TAGS keyword. Instead, to disable these tags
3602 on a per-file basis, insert anywhere in the file:
3604 #+STARTUP: noptag"
3605 :group 'org-tags
3606 :type '(repeat
3607 (choice
3608 (cons (string :tag "Tag name")
3609 (character :tag "Access char"))
3610 (const :tag "Start radio group" (:startgroup))
3611 (const :tag "Start tag group, non distinct" (:startgrouptag))
3612 (const :tag "Group tags delimiter" (:grouptags))
3613 (const :tag "End radio group" (:endgroup))
3614 (const :tag "End tag group, non distinct" (:endgrouptag))
3615 (const :tag "New line" (:newline)))))
3617 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3618 "If non-nil, always offer completion for all tags of all agenda files.
3619 Instead of customizing this variable directly, you might want to
3620 set it locally for capture buffers, because there no list of
3621 tags in that file can be created dynamically (there are none).
3623 (add-hook \\='org-capture-mode-hook
3624 (lambda ()
3625 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3626 :group 'org-tags
3627 :version "24.1"
3628 :type 'boolean)
3630 (defvar org-file-tags nil
3631 "List of tags that can be inherited by all entries in the file.
3632 The tags will be inherited if the variable `org-use-tag-inheritance'
3633 says they should be.
3634 This variable is populated from #+FILETAGS lines.")
3636 (defcustom org-use-fast-tag-selection 'auto
3637 "Non-nil means use fast tag selection scheme.
3638 This is a special interface to select and deselect tags with single keys.
3639 When nil, fast selection is never used.
3640 When the symbol `auto', fast selection is used if and only if selection
3641 characters for tags have been configured, either through the variable
3642 `org-tag-alist' or through a #+TAGS line in the buffer.
3643 When t, fast selection is always used and selection keys are assigned
3644 automatically if necessary."
3645 :group 'org-tags
3646 :type '(choice
3647 (const :tag "Always" t)
3648 (const :tag "Never" nil)
3649 (const :tag "When selection characters are configured" auto)))
3651 (defcustom org-fast-tag-selection-single-key nil
3652 "Non-nil means fast tag selection exits after first change.
3653 When nil, you have to press RET to exit it.
3654 During fast tag selection, you can toggle this flag with `C-c'.
3655 This variable can also have the value `expert'. In this case, the window
3656 displaying the tags menu is not even shown, until you press C-c again."
3657 :group 'org-tags
3658 :type '(choice
3659 (const :tag "No" nil)
3660 (const :tag "Yes" t)
3661 (const :tag "Expert" expert)))
3663 (defvar org-fast-tag-selection-include-todo nil
3664 "Non-nil means fast tags selection interface will also offer TODO states.
3665 This is an undocumented feature, you should not rely on it.")
3667 (defcustom org-tags-column -77
3668 "The column to which tags should be indented in a headline.
3669 If this number is positive, it specifies the column. If it is negative,
3670 it means that the tags should be flushright to that column. For example,
3671 -80 works well for a normal 80 character screen.
3672 When 0, place tags directly after headline text, with only one space in
3673 between."
3674 :group 'org-tags
3675 :type 'integer)
3677 (defcustom org-auto-align-tags t
3678 "Non-nil keeps tags aligned when modifying headlines.
3679 Some operations (i.e. demoting) change the length of a headline and
3680 therefore shift the tags around. With this option turned on, after
3681 each such operation the tags are again aligned to `org-tags-column'."
3682 :group 'org-tags
3683 :type 'boolean)
3685 (defcustom org-use-tag-inheritance t
3686 "Non-nil means tags in levels apply also for sublevels.
3687 When nil, only the tags directly given in a specific line apply there.
3688 This may also be a list of tags that should be inherited, or a regexp that
3689 matches tags that should be inherited. Additional control is possible
3690 with the variable `org-tags-exclude-from-inheritance' which gives an
3691 explicit list of tags to be excluded from inheritance, even if the value of
3692 `org-use-tag-inheritance' would select it for inheritance.
3694 If this option is t, a match early-on in a tree can lead to a large
3695 number of matches in the subtree when constructing the agenda or creating
3696 a sparse tree. If you only want to see the first match in a tree during
3697 a search, check out the variable `org-tags-match-list-sublevels'."
3698 :group 'org-tags
3699 :type '(choice
3700 (const :tag "Not" nil)
3701 (const :tag "Always" t)
3702 (repeat :tag "Specific tags" (string :tag "Tag"))
3703 (regexp :tag "Tags matched by regexp")))
3705 (defcustom org-tags-exclude-from-inheritance nil
3706 "List of tags that should never be inherited.
3707 This is a way to exclude a few tags from inheritance. For way to do
3708 the opposite, to actively allow inheritance for selected tags,
3709 see the variable `org-use-tag-inheritance'."
3710 :group 'org-tags
3711 :type '(repeat (string :tag "Tag")))
3713 (defun org-tag-inherit-p (tag)
3714 "Check if TAG is one that should be inherited."
3715 (cond
3716 ((member tag org-tags-exclude-from-inheritance) nil)
3717 ((eq org-use-tag-inheritance t) t)
3718 ((not org-use-tag-inheritance) nil)
3719 ((stringp org-use-tag-inheritance)
3720 (string-match org-use-tag-inheritance tag))
3721 ((listp org-use-tag-inheritance)
3722 (member tag org-use-tag-inheritance))
3723 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3725 (defcustom org-tags-match-list-sublevels t
3726 "Non-nil means list also sublevels of headlines matching a search.
3727 This variable applies to tags/property searches, and also to stuck
3728 projects because this search is based on a tags match as well.
3730 When set to the symbol `indented', sublevels are indented with
3731 leading dots.
3733 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3734 the sublevels of a headline matching a tag search often also match
3735 the same search. Listing all of them can create very long lists.
3736 Setting this variable to nil causes subtrees of a match to be skipped.
3738 This variable is semi-obsolete and probably should always be true. It
3739 is better to limit inheritance to certain tags using the variables
3740 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3741 :group 'org-tags
3742 :type '(choice
3743 (const :tag "No, don't list them" nil)
3744 (const :tag "Yes, do list them" t)
3745 (const :tag "List them, indented with leading dots" indented)))
3747 (defcustom org-tags-sort-function nil
3748 "When set, tags are sorted using this function as a comparator."
3749 :group 'org-tags
3750 :type '(choice
3751 (const :tag "No sorting" nil)
3752 (const :tag "Alphabetical" string<)
3753 (const :tag "Reverse alphabetical" string>)
3754 (function :tag "Custom function" nil)))
3756 (defvar org-tags-history nil
3757 "History of minibuffer reads for tags.")
3758 (defvar org-last-tags-completion-table nil
3759 "The last used completion table for tags.")
3760 (defvar org-after-tags-change-hook nil
3761 "Hook that is run after the tags in a line have changed.")
3763 (defgroup org-properties nil
3764 "Options concerning properties in Org mode."
3765 :tag "Org Properties"
3766 :group 'org)
3768 (defcustom org-property-format "%-10s %s"
3769 "How property key/value pairs should be formatted by `indent-line'.
3770 When `indent-line' hits a property definition, it will format the line
3771 according to this format, mainly to make sure that the values are
3772 lined-up with respect to each other."
3773 :group 'org-properties
3774 :type 'string)
3776 (defcustom org-properties-postprocess-alist nil
3777 "Alist of properties and functions to adjust inserted values.
3778 Elements of this alist must be of the form
3780 ([string] [function])
3782 where [string] must be a property name and [function] must be a
3783 lambda expression: this lambda expression must take one argument,
3784 the value to adjust, and return the new value as a string.
3786 For example, this element will allow the property \"Remaining\"
3787 to be updated wrt the relation between the \"Effort\" property
3788 and the clock summary:
3790 ((\"Remaining\" (lambda(value)
3791 (let ((clocksum (org-clock-sum-current-item))
3792 (effort (org-duration-string-to-minutes
3793 (org-entry-get (point) \"Effort\"))))
3794 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3795 :group 'org-properties
3796 :version "24.1"
3797 :type '(alist :key-type (string :tag "Property")
3798 :value-type (function :tag "Function")))
3800 (defcustom org-use-property-inheritance nil
3801 "Non-nil means properties apply also for sublevels.
3803 This setting is chiefly used during property searches. Turning it on can
3804 cause significant overhead when doing a search, which is why it is not
3805 on by default.
3807 When nil, only the properties directly given in the current entry count.
3808 When t, every property is inherited. The value may also be a list of
3809 properties that should have inheritance, or a regular expression matching
3810 properties that should be inherited.
3812 However, note that some special properties use inheritance under special
3813 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3814 and the properties ending in \"_ALL\" when they are used as descriptor
3815 for valid values of a property.
3817 Note for programmers:
3818 When querying an entry with `org-entry-get', you can control if inheritance
3819 should be used. By default, `org-entry-get' looks only at the local
3820 properties. You can request inheritance by setting the inherit argument
3821 to t (to force inheritance) or to `selective' (to respect the setting
3822 in this variable)."
3823 :group 'org-properties
3824 :type '(choice
3825 (const :tag "Not" nil)
3826 (const :tag "Always" t)
3827 (repeat :tag "Specific properties" (string :tag "Property"))
3828 (regexp :tag "Properties matched by regexp")))
3830 (defun org-property-inherit-p (property)
3831 "Return a non-nil value if PROPERTY should be inherited."
3832 (cond
3833 ((eq org-use-property-inheritance t) t)
3834 ((not org-use-property-inheritance) nil)
3835 ((stringp org-use-property-inheritance)
3836 (string-match org-use-property-inheritance property))
3837 ((listp org-use-property-inheritance)
3838 (member-ignore-case property org-use-property-inheritance))
3839 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3841 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3842 "The default column format, if no other format has been defined.
3843 This variable can be set on the per-file basis by inserting a line
3845 #+COLUMNS: %25ITEM ....."
3846 :group 'org-properties
3847 :type 'string)
3849 (defcustom org-columns-ellipses ".."
3850 "The ellipses to be used when a field in column view is truncated.
3851 When this is the empty string, as many characters as possible are shown,
3852 but then there will be no visual indication that the field has been truncated.
3853 When this is a string of length N, the last N characters of a truncated
3854 field are replaced by this string. If the column is narrower than the
3855 ellipses string, only part of the ellipses string will be shown."
3856 :group 'org-properties
3857 :type 'string)
3859 (defconst org-global-properties-fixed
3860 '(("VISIBILITY_ALL" . "folded children content all")
3861 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3862 "List of property/value pairs that can be inherited by any entry.
3864 These are fixed values, for the preset properties. The user variable
3865 that can be used to add to this list is `org-global-properties'.
3867 The entries in this list are cons cells where the car is a property
3868 name and cdr is a string with the value. If the value represents
3869 multiple items like an \"_ALL\" property, separate the items by
3870 spaces.")
3872 (defcustom org-global-properties nil
3873 "List of property/value pairs that can be inherited by any entry.
3875 This list will be combined with the constant `org-global-properties-fixed'.
3877 The entries in this list are cons cells where the car is a property
3878 name and cdr is a string with the value.
3880 You can set buffer-local values for the same purpose in the variable
3881 `org-file-properties' this by adding lines like
3883 #+PROPERTY: NAME VALUE"
3884 :group 'org-properties
3885 :type '(repeat
3886 (cons (string :tag "Property")
3887 (string :tag "Value"))))
3889 (defvar-local org-file-properties nil
3890 "List of property/value pairs that can be inherited by any entry.
3891 Valid for the current buffer.
3892 This variable is populated from #+PROPERTY lines.")
3894 (defgroup org-agenda nil
3895 "Options concerning agenda views in Org mode."
3896 :tag "Org Agenda"
3897 :group 'org)
3899 (defvar-local org-category nil
3900 "Variable used by org files to set a category for agenda display.
3901 Such files should use a file variable to set it, for example
3903 # -*- mode: org; org-category: \"ELisp\"
3905 or contain a special line
3907 #+CATEGORY: ELisp
3909 If the file does not specify a category, then file's base name
3910 is used instead.")
3911 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3913 (defcustom org-agenda-files nil
3914 "The files to be used for agenda display.
3916 If an entry is a directory, all files in that directory that are matched
3917 by `org-agenda-file-regexp' will be part of the file list.
3919 If the value of the variable is not a list but a single file name, then
3920 the list of agenda files is actually stored and maintained in that file,
3921 one agenda file per line. In this file paths can be given relative to
3922 `org-directory'. Tilde expansion and environment variable substitution
3923 are also made.
3925 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3926 and removed with `\\[org-remove-file]'."
3927 :group 'org-agenda
3928 :type '(choice
3929 (repeat :tag "List of files and directories" file)
3930 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3932 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3933 "Regular expression to match files for `org-agenda-files'.
3934 If any element in the list in that variable contains a directory instead
3935 of a normal file, all files in that directory that are matched by this
3936 regular expression will be included."
3937 :group 'org-agenda
3938 :type 'regexp)
3940 (defcustom org-agenda-text-search-extra-files nil
3941 "List of extra files to be searched by text search commands.
3942 These files will be searched in addition to the agenda files by the
3943 commands `org-search-view' (`\\[org-agenda] s') \
3944 and `org-occur-in-agenda-files'.
3945 Note that these files will only be searched for text search commands,
3946 not for the other agenda views like todo lists, tag searches or the weekly
3947 agenda. This variable is intended to list notes and possibly archive files
3948 that should also be searched by these two commands.
3949 In fact, if the first element in the list is the symbol `agenda-archives',
3950 then all archive files of all agenda files will be added to the search
3951 scope."
3952 :group 'org-agenda
3953 :type '(set :greedy t
3954 (const :tag "Agenda Archives" agenda-archives)
3955 (repeat :inline t (file))))
3957 (defvaralias 'org-agenda-multi-occur-extra-files
3958 'org-agenda-text-search-extra-files)
3960 (defcustom org-agenda-skip-unavailable-files nil
3961 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3962 A nil value means to remove them, after a query, from the list."
3963 :group 'org-agenda
3964 :type 'boolean)
3966 (defcustom org-calendar-to-agenda-key [?c]
3967 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3968 The command `org-calendar-goto-agenda' will be bound to this key. The
3969 default is the character `c' because then `c' can be used to switch back and
3970 forth between agenda and calendar."
3971 :group 'org-agenda
3972 :type 'sexp)
3974 (defcustom org-calendar-insert-diary-entry-key [?i]
3975 "The key to be installed in `calendar-mode-map' for adding diary entries.
3976 This option is irrelevant until `org-agenda-diary-file' has been configured
3977 to point to an Org file. When that is the case, the command
3978 `org-agenda-diary-entry' will be bound to the key given here, by default
3979 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3980 if you want to continue doing this, you need to change this to a different
3981 key."
3982 :group 'org-agenda
3983 :type 'sexp)
3985 (defcustom org-agenda-diary-file 'diary-file
3986 "File to which to add new entries with the `i' key in agenda and calendar.
3987 When this is the symbol `diary-file', the functionality in the Emacs
3988 calendar will be used to add entries to the `diary-file'. But when this
3989 points to a file, `org-agenda-diary-entry' will be used instead."
3990 :group 'org-agenda
3991 :type '(choice
3992 (const :tag "The standard Emacs diary file" diary-file)
3993 (file :tag "Special Org file diary entries")))
3995 (eval-after-load "calendar"
3996 '(progn
3997 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3998 'org-calendar-goto-agenda)
3999 (add-hook 'calendar-mode-hook
4000 (lambda ()
4001 (unless (eq org-agenda-diary-file 'diary-file)
4002 (define-key calendar-mode-map
4003 org-calendar-insert-diary-entry-key
4004 'org-agenda-diary-entry))))))
4006 (defgroup org-latex nil
4007 "Options for embedding LaTeX code into Org mode."
4008 :tag "Org LaTeX"
4009 :group 'org)
4011 (defcustom org-format-latex-options
4012 '(:foreground default :background default :scale 1.0
4013 :html-foreground "Black" :html-background "Transparent"
4014 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4015 "Options for creating images from LaTeX fragments.
4016 This is a property list with the following properties:
4017 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4018 `default' means use the foreground of the default face.
4019 `auto' means use the foreground from the text face.
4020 :background the background color, or \"Transparent\".
4021 `default' means use the background of the default face.
4022 `auto' means use the background from the text face.
4023 :scale a scaling factor for the size of the images, to get more pixels
4024 :html-foreground, :html-background, :html-scale
4025 the same numbers for HTML export.
4026 :matchers a list indicating which matchers should be used to
4027 find LaTeX fragments. Valid members of this list are:
4028 \"begin\" find environments
4029 \"$1\" find single characters surrounded by $.$
4030 \"$\" find math expressions surrounded by $...$
4031 \"$$\" find math expressions surrounded by $$....$$
4032 \"\\(\" find math expressions surrounded by \\(...\\)
4033 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4034 :group 'org-latex
4035 :type 'plist)
4037 (defcustom org-format-latex-signal-error t
4038 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4039 When nil, just push out a message."
4040 :group 'org-latex
4041 :version "24.1"
4042 :type 'boolean)
4044 (defcustom org-latex-to-mathml-jar-file nil
4045 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4046 Use this to specify additional executable file say a jar file.
4048 When using MathToWeb as the converter, specify the full-path to
4049 your mathtoweb.jar file."
4050 :group 'org-latex
4051 :version "24.1"
4052 :type '(choice
4053 (const :tag "None" nil)
4054 (file :tag "JAR file" :must-match t)))
4056 (defcustom org-latex-to-mathml-convert-command nil
4057 "Command to convert LaTeX fragments to MathML.
4058 Replace format-specifiers in the command as noted below and use
4059 `shell-command' to convert LaTeX to MathML.
4060 %j: Executable file in fully expanded form as specified by
4061 `org-latex-to-mathml-jar-file'.
4062 %I: Input LaTeX file in fully expanded form.
4063 %i: The latex fragment to be converted.
4064 %o: Output MathML file.
4066 This command is used by `org-create-math-formula'.
4068 When using MathToWeb as the converter, set this option to
4069 \"java -jar %j -unicode -force -df %o %I\".
4071 When using LaTeXML set this option to
4072 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4073 :group 'org-latex
4074 :version "24.1"
4075 :type '(choice
4076 (const :tag "None" nil)
4077 (string :tag "\nShell command")))
4079 (defcustom org-preview-latex-default-process 'dvipng
4080 "The default process to convert LaTeX fragments to image files.
4081 All available processes and theirs documents can be found in
4082 `org-preview-latex-process-alist', which see."
4083 :group 'org-latex
4084 :version "26.1"
4085 :package-version '(Org . "9.0")
4086 :type 'symbol)
4088 (defcustom org-preview-latex-process-alist
4089 '((dvipng
4090 :programs ("latex" "dvipng")
4091 :description "dvi > png"
4092 :message "you need to install the programs: latex and dvipng."
4093 :image-input-type "dvi"
4094 :image-output-type "png"
4095 :image-size-adjust (1.0 . 1.0)
4096 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4097 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4098 (dvisvgm
4099 :programs ("latex" "dvisvgm")
4100 :description "dvi > svg"
4101 :message "you need to install the programs: latex and dvisvgm."
4102 :use-xcolor t
4103 :image-input-type "dvi"
4104 :image-output-type "svg"
4105 :image-size-adjust (1.7 . 1.5)
4106 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4107 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4108 (imagemagick
4109 :programs ("latex" "convert")
4110 :description "pdf > png"
4111 :message "you need to install the programs: latex and imagemagick."
4112 :use-xcolor t
4113 :image-input-type "pdf"
4114 :image-output-type "png"
4115 :image-size-adjust (1.0 . 1.0)
4116 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4117 :image-converter
4118 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4119 "Definitions of external processes for LaTeX previewing.
4120 Org mode can use some external commands to generate TeX snippet's images for
4121 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4122 `org-create-formula-image' how to call them.
4124 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4125 PROPERTIES accepts the following attributes:
4127 :programs list of strings, required programs.
4128 :description string, describe the process.
4129 :message string, message it when required programs cannot be found.
4130 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4131 :image-output-type string, output file type of image converter (e.g., \"png\").
4132 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4133 deal with background and foreground color of image.
4134 Otherwise, dvipng style background and foregroud color
4135 format are generated. You may then refer to them in
4136 command options with \"%F\" and \"%B\".
4137 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4138 image size showed in buffer and the cdr element is for
4139 HTML file. This option is only useful for process
4140 developers, users should use variable
4141 `org-format-latex-options' instead.
4142 :post-clean list of strings, files matched are to be cleaned up once
4143 the image is generated. When nil, the files with \".dvi\",
4144 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4145 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4146 be cleaned up.
4147 :latex-header list of strings, the LaTeX header of the snippet file.
4148 When nil, the fallback value is used instead, which is
4149 controlled by `org-format-latex-header',
4150 `org-latex-default-packages-alist' and
4151 `org-latex-packages-alist', which see.
4152 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4153 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4154 replaced with values defined below.
4155 :image-converter list of image converter commands strings. Each of them is
4156 given to the shell and supports any of the following
4157 place-holders defined below.
4159 Place-holders used by `:image-converter' and `:latex-compiler':
4161 %f input file name
4162 %b base name of input file
4163 %o base directory of input file
4164 %O absolute output file name
4166 Place-holders only used by `:image-converter':
4168 %F foreground of image
4169 %B background of image
4170 %D dpi, which is used to adjust image size by some processing commands.
4171 %S the image size scale ratio, which is used to adjust image size by some
4172 processing commands."
4173 :group 'org-latex
4174 :version "26.1"
4175 :package-version '(Org . "9.0")
4176 :type '(alist :tag "LaTeX to image backends"
4177 :value-type (plist)))
4179 (defcustom org-preview-latex-image-directory "ltximg/"
4180 "Path to store latex preview images.
4181 A relative path here creates many directories relative to the
4182 processed org files paths. An absolute path puts all preview
4183 images at the same place."
4184 :group 'org-latex
4185 :version "26.1"
4186 :package-version '(Org . "9.0")
4187 :type 'string)
4189 (defun org-format-latex-mathml-available-p ()
4190 "Return t if `org-latex-to-mathml-convert-command' is usable."
4191 (save-match-data
4192 (when (and (boundp 'org-latex-to-mathml-convert-command)
4193 org-latex-to-mathml-convert-command)
4194 (let ((executable (car (split-string
4195 org-latex-to-mathml-convert-command))))
4196 (when (executable-find executable)
4197 (if (string-match
4198 "%j" org-latex-to-mathml-convert-command)
4199 (file-readable-p org-latex-to-mathml-jar-file)
4200 t))))))
4202 (defcustom org-format-latex-header "\\documentclass{article}
4203 \\usepackage[usenames]{color}
4204 \[PACKAGES]
4205 \[DEFAULT-PACKAGES]
4206 \\pagestyle{empty} % do not remove
4207 % The settings below are copied from fullpage.sty
4208 \\setlength{\\textwidth}{\\paperwidth}
4209 \\addtolength{\\textwidth}{-3cm}
4210 \\setlength{\\oddsidemargin}{1.5cm}
4211 \\addtolength{\\oddsidemargin}{-2.54cm}
4212 \\setlength{\\evensidemargin}{\\oddsidemargin}
4213 \\setlength{\\textheight}{\\paperheight}
4214 \\addtolength{\\textheight}{-\\headheight}
4215 \\addtolength{\\textheight}{-\\headsep}
4216 \\addtolength{\\textheight}{-\\footskip}
4217 \\addtolength{\\textheight}{-3cm}
4218 \\setlength{\\topmargin}{1.5cm}
4219 \\addtolength{\\topmargin}{-2.54cm}"
4220 "The document header used for processing LaTeX fragments.
4221 It is imperative that this header make sure that no page number
4222 appears on the page. The package defined in the variables
4223 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4224 will either replace the placeholder \"[PACKAGES]\" in this
4225 header, or they will be appended."
4226 :group 'org-latex
4227 :type 'string)
4229 (defun org-set-packages-alist (var val)
4230 "Set the packages alist and make sure it has 3 elements per entry."
4231 (set var (mapcar (lambda (x)
4232 (if (and (consp x) (= (length x) 2))
4233 (list (car x) (nth 1 x) t)
4235 val)))
4237 (defun org-get-packages-alist (var)
4238 "Get the packages alist and make sure it has 3 elements per entry."
4239 (mapcar (lambda (x)
4240 (if (and (consp x) (= (length x) 2))
4241 (list (car x) (nth 1 x) t)
4243 (default-value var)))
4245 (defcustom org-latex-default-packages-alist
4246 '(("AUTO" "inputenc" t ("pdflatex"))
4247 ("T1" "fontenc" t ("pdflatex"))
4248 ("" "graphicx" t)
4249 ("" "grffile" t)
4250 ("" "longtable" nil)
4251 ("" "wrapfig" nil)
4252 ("" "rotating" nil)
4253 ("normalem" "ulem" t)
4254 ("" "amsmath" t)
4255 ("" "textcomp" t)
4256 ("" "amssymb" t)
4257 ("" "capt-of" nil)
4258 ("" "hyperref" nil))
4259 "Alist of default packages to be inserted in the header.
4261 Change this only if one of the packages here causes an
4262 incompatibility with another package you are using.
4264 The packages in this list are needed by one part or another of
4265 Org mode to function properly:
4267 - inputenc, fontenc: for basic font and character selection
4268 - graphicx: for including images
4269 - grffile: allow periods and spaces in graphics file names
4270 - longtable: For multipage tables
4271 - wrapfig: for figure placement
4272 - rotating: for sideways figures and tables
4273 - ulem: for underline and strike-through
4274 - amsmath: for subscript and superscript and math environments
4275 - textcomp, amssymb: for various symbols used
4276 for interpreting the entities in `org-entities'. You can skip
4277 some of these packages if you don't use any of their symbols.
4278 - capt-of: for captions outside of floats
4279 - hyperref: for cross references
4281 Therefore you should not modify this variable unless you know
4282 what you are doing. The one reason to change it anyway is that
4283 you might be loading some other package that conflicts with one
4284 of the default packages. Each element is either a cell or
4285 a string.
4287 A cell is of the format
4289 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4291 If SNIPPET-FLAG is non-nil, the package also needs to be included
4292 when compiling LaTeX snippets into images for inclusion into
4293 non-LaTeX output. COMPILERS is a list of compilers that should
4294 include the package, see `org-latex-compiler'. If the document
4295 compiler is not in the list, and the list is non-nil, the package
4296 will not be inserted in the final document.
4298 A string will be inserted as-is in the header of the document."
4299 :group 'org-latex
4300 :group 'org-export-latex
4301 :set 'org-set-packages-alist
4302 :get 'org-get-packages-alist
4303 :version "26.1"
4304 :package-version '(Org . "8.3")
4305 :type '(repeat
4306 (choice
4307 (list :tag "options/package pair"
4308 (string :tag "options")
4309 (string :tag "package")
4310 (boolean :tag "Snippet"))
4311 (string :tag "A line of LaTeX"))))
4313 (defcustom org-latex-packages-alist nil
4314 "Alist of packages to be inserted in every LaTeX header.
4316 These will be inserted after `org-latex-default-packages-alist'.
4317 Each element is either a cell or a string.
4319 A cell is of the format:
4321 (\"options\" \"package\" SNIPPET-FLAG)
4323 SNIPPET-FLAG, when non-nil, indicates that this package is also
4324 needed when turning LaTeX snippets into images for inclusion into
4325 non-LaTeX output.
4327 A string will be inserted as-is in the header of the document.
4329 Make sure that you only list packages here which:
4331 - you want in every file;
4332 - do not conflict with the setup in `org-format-latex-header';
4333 - do not conflict with the default packages in
4334 `org-latex-default-packages-alist'."
4335 :group 'org-latex
4336 :group 'org-export-latex
4337 :set 'org-set-packages-alist
4338 :get 'org-get-packages-alist
4339 :type '(repeat
4340 (choice
4341 (list :tag "options/package pair"
4342 (string :tag "options")
4343 (string :tag "package")
4344 (boolean :tag "Snippet"))
4345 (string :tag "A line of LaTeX"))))
4347 (defgroup org-appearance nil
4348 "Settings for Org mode appearance."
4349 :tag "Org Appearance"
4350 :group 'org)
4352 (defcustom org-level-color-stars-only nil
4353 "Non-nil means fontify only the stars in each headline.
4354 When nil, the entire headline is fontified.
4355 Changing it requires restart of `font-lock-mode' to become effective
4356 also in regions already fontified."
4357 :group 'org-appearance
4358 :type 'boolean)
4360 (defcustom org-hide-leading-stars nil
4361 "Non-nil means hide the first N-1 stars in a headline.
4362 This works by using the face `org-hide' for these stars. This
4363 face is white for a light background, and black for a dark
4364 background. You may have to customize the face `org-hide' to
4365 make this work.
4366 Changing it requires restart of `font-lock-mode' to become effective
4367 also in regions already fontified.
4368 You may also set this on a per-file basis by adding one of the following
4369 lines to the buffer:
4371 #+STARTUP: hidestars
4372 #+STARTUP: showstars"
4373 :group 'org-appearance
4374 :type 'boolean)
4376 (defcustom org-hidden-keywords nil
4377 "List of symbols corresponding to keywords to be hidden the org buffer.
4378 For example, a value \\='(title) for this list will make the document's title
4379 appear in the buffer without the initial #+TITLE: keyword."
4380 :group 'org-appearance
4381 :version "24.1"
4382 :type '(set (const :tag "#+AUTHOR" author)
4383 (const :tag "#+DATE" date)
4384 (const :tag "#+EMAIL" email)
4385 (const :tag "#+TITLE" title)))
4387 (defcustom org-custom-properties nil
4388 "List of properties (as strings) with a special meaning.
4389 The default use of these custom properties is to let the user
4390 hide them with `org-toggle-custom-properties-visibility'."
4391 :group 'org-properties
4392 :group 'org-appearance
4393 :version "24.3"
4394 :type '(repeat (string :tag "Property Name")))
4396 (defcustom org-fontify-done-headline nil
4397 "Non-nil means change the face of a headline if it is marked DONE.
4398 Normally, only the TODO/DONE keyword indicates the state of a headline.
4399 When this is non-nil, the headline after the keyword is set to the
4400 `org-headline-done' as an additional indication."
4401 :group 'org-appearance
4402 :type 'boolean)
4404 (defcustom org-fontify-emphasized-text t
4405 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4406 Changing this variable requires a restart of Emacs to take effect."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-fontify-whole-heading-line nil
4411 "Non-nil means fontify the whole line for headings.
4412 This is useful when setting a background color for the
4413 org-level-* faces."
4414 :group 'org-appearance
4415 :type 'boolean)
4417 (defcustom org-highlight-latex-and-related nil
4418 "Non-nil means highlight LaTeX related syntax in the buffer.
4419 When non nil, the value should be a list containing any of the
4420 following symbols:
4421 `latex' Highlight LaTeX snippets and environments.
4422 `script' Highlight subscript and superscript.
4423 `entities' Highlight entities."
4424 :group 'org-appearance
4425 :version "24.4"
4426 :package-version '(Org . "8.0")
4427 :type '(choice
4428 (const :tag "No highlighting" nil)
4429 (set :greedy t :tag "Highlight"
4430 (const :tag "LaTeX snippets and environments" latex)
4431 (const :tag "Subscript and superscript" script)
4432 (const :tag "Entities" entities))))
4434 (defcustom org-hide-emphasis-markers nil
4435 "Non-nil mean font-lock should hide the emphasis marker characters."
4436 :group 'org-appearance
4437 :type 'boolean)
4439 (defcustom org-hide-macro-markers nil
4440 "Non-nil mean font-lock should hide the brackets marking macro calls."
4441 :group 'org-appearance
4442 :type 'boolean)
4444 (defcustom org-pretty-entities nil
4445 "Non-nil means show entities as UTF8 characters.
4446 When nil, the \\name form remains in the buffer."
4447 :group 'org-appearance
4448 :version "24.1"
4449 :type 'boolean)
4451 (defcustom org-pretty-entities-include-sub-superscripts t
4452 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4453 :group 'org-appearance
4454 :version "24.1"
4455 :type 'boolean)
4457 (defvar org-emph-re nil
4458 "Regular expression for matching emphasis.
4459 After a match, the match groups contain these elements:
4460 0 The match of the full regular expression, including the characters
4461 before and after the proper match
4462 1 The character before the proper match, or empty at beginning of line
4463 2 The proper match, including the leading and trailing markers
4464 3 The leading marker like * or /, indicating the type of highlighting
4465 4 The text between the emphasis markers, not including the markers
4466 5 The character after the match, empty at the end of a line")
4468 (defvar org-verbatim-re nil
4469 "Regular expression for matching verbatim text.")
4471 (defvar org-emphasis-regexp-components) ; defined just below
4472 (defvar org-emphasis-alist) ; defined just below
4473 (defun org-set-emph-re (var val)
4474 "Set variable and compute the emphasis regular expression."
4475 (set var val)
4476 (when (and (boundp 'org-emphasis-alist)
4477 (boundp 'org-emphasis-regexp-components)
4478 org-emphasis-alist org-emphasis-regexp-components)
4479 (pcase-let*
4480 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4481 (body (if (<= nl 0) body
4482 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4483 (template
4484 (format (concat "\\([%s]\\|^\\)" ;before markers
4485 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4486 "\\([%s]\\|$\\)") ;after markers
4487 pre border border body border post)))
4488 (setq org-emph-re (format template "*/_+"))
4489 (setq org-verbatim-re (format template "=~")))))
4491 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4492 ;; set this option proved cumbersome. See this message/thread:
4493 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4494 (defvar org-emphasis-regexp-components
4495 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4496 "Components used to build the regular expression for emphasis.
4497 This is a list with five entries. Terminology: In an emphasis string
4498 like \" *strong word* \", we call the initial space PREMATCH, the final
4499 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4500 and \"trong wor\" is the body. The different components in this variable
4501 specify what is allowed/forbidden in each part:
4503 pre Chars allowed as prematch. Beginning of line will be allowed too.
4504 post Chars allowed as postmatch. End of line will be allowed too.
4505 border The chars *forbidden* as border characters.
4506 body-regexp A regexp like \".\" to match a body character. Don't use
4507 non-shy groups here, and don't allow newline here.
4508 newline The maximum number of newlines allowed in an emphasis exp.
4510 You need to reload Org or to restart Emacs after customizing this.")
4512 (defcustom org-emphasis-alist
4513 '(("*" bold)
4514 ("/" italic)
4515 ("_" underline)
4516 ("=" org-verbatim verbatim)
4517 ("~" org-code verbatim)
4518 ("+" (:strike-through t)))
4519 "Alist of characters and faces to emphasize text.
4520 Text starting and ending with a special character will be emphasized,
4521 for example *bold*, _underlined_ and /italic/. This variable sets the
4522 marker characters and the face to be used by font-lock for highlighting
4523 in Org buffers.
4525 You need to reload Org or to restart Emacs after customizing this."
4526 :group 'org-appearance
4527 :set 'org-set-emph-re
4528 :version "24.4"
4529 :package-version '(Org . "8.0")
4530 :type '(repeat
4531 (list
4532 (string :tag "Marker character")
4533 (choice
4534 (face :tag "Font-lock-face")
4535 (plist :tag "Face property list"))
4536 (option (const verbatim)))))
4538 (defvar org-protecting-blocks '("src" "example" "export")
4539 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4540 This is needed for font-lock setup.")
4542 ;;; Functions and variables from their packages
4543 ;; Declared here to avoid compiler warnings
4544 (defvar mark-active)
4546 ;; Various packages
4547 (declare-function calc-eval "calc" (str &optional separator &rest args))
4548 (declare-function calendar-forward-day "cal-move" (arg))
4549 (declare-function calendar-goto-date "cal-move" (date))
4550 (declare-function calendar-goto-today "cal-move" ())
4551 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4552 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4553 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4554 (declare-function cdlatex-tab "ext:cdlatex" ())
4555 (declare-function dired-get-filename
4556 "dired"
4557 (&optional localp no-error-if-not-filep))
4558 (declare-function iswitchb-read-buffer
4559 "iswitchb"
4560 (prompt &optional
4561 default require-match _predicate start matches-set))
4562 (declare-function org-agenda-change-all-lines
4563 "org-agenda"
4564 (newhead hdmarker &optional fixface just-this))
4565 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4566 "org-agenda"
4567 (&optional end))
4568 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4569 (declare-function org-agenda-format-item
4570 "org-agenda"
4571 (extra txt &optional level category tags dotime
4572 remove-re habitp))
4573 (declare-function org-agenda-maybe-redo "org-agenda" ())
4574 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4575 (declare-function org-agenda-save-markers-for-cut-and-paste
4576 "org-agenda"
4577 (beg end))
4578 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4579 (declare-function org-agenda-skip "org-agenda" ())
4580 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4581 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4582 (declare-function org-indent-mode "org-indent" (&optional arg))
4583 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4584 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4585 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4586 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4587 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4588 (declare-function parse-time-string "parse-time" (string))
4589 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4591 (defvar align-mode-rules-list)
4592 (defvar calc-embedded-close-formula)
4593 (defvar calc-embedded-open-formula)
4594 (defvar calc-embedded-open-mode)
4595 (defvar font-lock-unfontify-region-function)
4596 (defvar iswitchb-temp-buflist)
4597 (defvar org-agenda-tags-todo-honor-ignore-options)
4598 (defvar remember-data-file)
4599 (defvar texmathp-why)
4601 ;;;###autoload
4602 (defun turn-on-orgtbl ()
4603 "Unconditionally turn on `orgtbl-mode'."
4604 (require 'org-table)
4605 (orgtbl-mode 1))
4607 (defun org-at-table-p (&optional table-type)
4608 "Non-nil if the cursor is inside an Org table.
4609 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4610 If `org-enable-table-editor' is nil, return nil unconditionally."
4611 (and
4612 org-enable-table-editor
4613 (save-excursion
4614 (beginning-of-line)
4615 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4616 (or (not (derived-mode-p 'org-mode))
4617 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4618 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4620 (defun org-at-table.el-p ()
4621 "Non-nil when point is at a table.el table."
4622 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4623 (let ((element (org-element-at-point)))
4624 (and (eq (org-element-type element) 'table)
4625 (eq (org-element-property :type element) 'table.el)))))
4627 (defun org-at-table-hline-p ()
4628 "Non-nil when point is inside a hline in a table.
4629 Assume point is already in a table. If `org-enable-table-editor'
4630 is nil, return nil unconditionally."
4631 (and org-enable-table-editor
4632 (save-excursion
4633 (beginning-of-line)
4634 (looking-at org-table-hline-regexp))))
4636 (defun org-table-map-tables (function &optional quietly)
4637 "Apply FUNCTION to the start of all tables in the buffer."
4638 (org-with-wide-buffer
4639 (goto-char (point-min))
4640 (while (re-search-forward org-table-any-line-regexp nil t)
4641 (unless quietly
4642 (message "Mapping tables: %d%%"
4643 (floor (* 100.0 (point)) (buffer-size))))
4644 (beginning-of-line 1)
4645 (when (and (looking-at org-table-line-regexp)
4646 ;; Exclude tables in src/example/verbatim/clocktable blocks
4647 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4648 (save-excursion (funcall function))
4649 (or (looking-at org-table-line-regexp)
4650 (forward-char 1)))
4651 (re-search-forward org-table-any-border-regexp nil 1)))
4652 (unless quietly (message "Mapping tables: done")))
4654 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4655 (declare-function org-clock-update-mode-line "org-clock" ())
4656 (declare-function org-resolve-clocks "org-clock"
4657 (&optional also-non-dangling-p prompt last-valid))
4659 (defun org-at-TBLFM-p (&optional pos)
4660 "Non-nil when point (or POS) is in #+TBLFM line."
4661 (save-excursion
4662 (goto-char (or pos (point)))
4663 (beginning-of-line)
4664 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4665 (eq (org-element-type (org-element-at-point)) 'table))))
4667 (defvar org-clock-start-time)
4668 (defvar org-clock-marker (make-marker)
4669 "Marker recording the last clock-in.")
4670 (defvar org-clock-hd-marker (make-marker)
4671 "Marker recording the last clock-in, but the headline position.")
4672 (defvar org-clock-heading ""
4673 "The heading of the current clock entry.")
4674 (defun org-clock-is-active ()
4675 "Return the buffer where the clock is currently running.
4676 Return nil if no clock is running."
4677 (marker-buffer org-clock-marker))
4679 (defun org-check-running-clock ()
4680 "Check if the current buffer contains the running clock.
4681 If yes, offer to stop it and to save the buffer with the changes."
4682 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4683 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4684 (buffer-name))))
4685 (org-clock-out)
4686 (when (y-or-n-p "Save changed buffer?")
4687 (save-buffer))))
4689 (defun org-clocktable-try-shift (dir n)
4690 "Check if this line starts a clock table, if yes, shift the time block."
4691 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4692 (org-clocktable-shift dir n)))
4694 ;;;###autoload
4695 (defun org-clock-persistence-insinuate ()
4696 "Set up hooks for clock persistence."
4697 (require 'org-clock)
4698 (add-hook 'org-mode-hook 'org-clock-load)
4699 (add-hook 'kill-emacs-hook 'org-clock-save))
4701 (defgroup org-archive nil
4702 "Options concerning archiving in Org mode."
4703 :tag "Org Archive"
4704 :group 'org-structure)
4706 (defcustom org-archive-location "%s_archive::"
4707 "The location where subtrees should be archived.
4709 The value of this variable is a string, consisting of two parts,
4710 separated by a double-colon. The first part is a filename and
4711 the second part is a headline.
4713 When the filename is omitted, archiving happens in the same file.
4714 %s in the filename will be replaced by the current file
4715 name (without the directory part). Archiving to a different file
4716 is useful to keep archived entries from contributing to the
4717 Org Agenda.
4719 The archived entries will be filed as subtrees of the specified
4720 headline. When the headline is omitted, the subtrees are simply
4721 filed away at the end of the file, as top-level entries. Also in
4722 the heading you can use %s to represent the file name, this can be
4723 useful when using the same archive for a number of different files.
4725 Here are a few examples:
4726 \"%s_archive::\"
4727 If the current file is Projects.org, archive in file
4728 Projects.org_archive, as top-level trees. This is the default.
4730 \"::* Archived Tasks\"
4731 Archive in the current file, under the top-level headline
4732 \"* Archived Tasks\".
4734 \"~/org/archive.org::\"
4735 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4737 \"~/org/archive.org::* From %s\"
4738 Archive in file ~/org/archive.org (absolute path), under headlines
4739 \"From FILENAME\" where file name is the current file name.
4741 \"~/org/datetree.org::datetree/* Finished Tasks\"
4742 The \"datetree/\" string is special, signifying to archive
4743 items to the datetree. Items are placed in either the CLOSED
4744 date of the item, or the current date if there is no CLOSED date.
4745 The heading will be a subentry to the current date. There doesn't
4746 need to be a heading, but there always needs to be a slash after
4747 datetree. For example, to store archived items directly in the
4748 datetree, use \"~/org/datetree.org::datetree/\".
4750 \"basement::** Finished Tasks\"
4751 Archive in file ./basement (relative path), as level 3 trees
4752 below the level 2 heading \"** Finished Tasks\".
4754 You may set this option on a per-file basis by adding to the buffer a
4755 line like
4757 #+ARCHIVE: basement::** Finished Tasks
4759 You may also define it locally for a subtree by setting an ARCHIVE property
4760 in the entry. If such a property is found in an entry, or anywhere up
4761 the hierarchy, it will be used."
4762 :group 'org-archive
4763 :type 'string)
4765 (defcustom org-agenda-skip-archived-trees t
4766 "Non-nil means the agenda will skip any items located in archived trees.
4767 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4768 variable is no longer recommended, you should leave it at the value t.
4769 Instead, use the key `v' to cycle the archives-mode in the agenda."
4770 :group 'org-archive
4771 :group 'org-agenda-skip
4772 :type 'boolean)
4774 (defcustom org-columns-skip-archived-trees t
4775 "Non-nil means ignore archived trees when creating column view."
4776 :group 'org-archive
4777 :group 'org-properties
4778 :type 'boolean)
4780 (defcustom org-cycle-open-archived-trees nil
4781 "Non-nil means `org-cycle' will open archived trees.
4782 An archived tree is a tree marked with the tag ARCHIVE.
4783 When nil, archived trees will stay folded. You can still open them with
4784 normal outline commands like `show-all', but not with the cycling commands."
4785 :group 'org-archive
4786 :group 'org-cycle
4787 :type 'boolean)
4789 (defcustom org-sparse-tree-open-archived-trees nil
4790 "Non-nil means sparse tree construction shows matches in archived trees.
4791 When nil, matches in these trees are highlighted, but the trees are kept in
4792 collapsed state."
4793 :group 'org-archive
4794 :group 'org-sparse-trees
4795 :type 'boolean)
4797 (defcustom org-sparse-tree-default-date-type nil
4798 "The default date type when building a sparse tree.
4799 When this is nil, a date is a scheduled or a deadline timestamp.
4800 Otherwise, these types are allowed:
4802 all: all timestamps
4803 active: only active timestamps (<...>)
4804 inactive: only inactive timestamps ([...])
4805 scheduled: only scheduled timestamps
4806 deadline: only deadline timestamps"
4807 :type '(choice (const :tag "Scheduled or deadline" nil)
4808 (const :tag "All timestamps" all)
4809 (const :tag "Only active timestamps" active)
4810 (const :tag "Only inactive timestamps" inactive)
4811 (const :tag "Only scheduled timestamps" scheduled)
4812 (const :tag "Only deadline timestamps" deadline)
4813 (const :tag "Only closed timestamps" closed))
4814 :version "26.1"
4815 :package-version '(Org . "8.3")
4816 :group 'org-sparse-trees)
4818 (defun org-cycle-hide-archived-subtrees (state)
4819 "Re-hide all archived subtrees after a visibility state change."
4820 (when (and (not org-cycle-open-archived-trees)
4821 (not (memq state '(overview folded))))
4822 (save-excursion
4823 (let* ((globalp (memq state '(contents all)))
4824 (beg (if globalp (point-min) (point)))
4825 (end (if globalp (point-max) (org-end-of-subtree t))))
4826 (org-hide-archived-subtrees beg end)
4827 (goto-char beg)
4828 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4829 (message "%s" (substitute-command-keys
4830 "Subtree is archived and stays closed. Use \
4831 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4833 (defun org-force-cycle-archived ()
4834 "Cycle subtree even if it is archived."
4835 (interactive)
4836 (setq this-command 'org-cycle)
4837 (let ((org-cycle-open-archived-trees t))
4838 (call-interactively 'org-cycle)))
4840 (defun org-hide-archived-subtrees (beg end)
4841 "Re-hide all archived subtrees after a visibility state change."
4842 (org-with-wide-buffer
4843 (let ((case-fold-search nil)
4844 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4845 (goto-char beg)
4846 ;; Include headline point is currently on.
4847 (beginning-of-line)
4848 (while (and (< (point) end) (re-search-forward re end t))
4849 (when (member org-archive-tag (org-get-tags))
4850 (org-flag-subtree t)
4851 (org-end-of-subtree t))))))
4853 (declare-function outline-end-of-heading "outline" ())
4854 (declare-function outline-flag-region "outline" (from to flag))
4855 (defun org-flag-subtree (flag)
4856 (save-excursion
4857 (org-back-to-heading t)
4858 (outline-end-of-heading)
4859 (outline-flag-region (point)
4860 (progn (org-end-of-subtree t) (point))
4861 flag)))
4863 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4865 ;; Declare Column View Code
4867 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4868 (declare-function org-columns-compute "org-colview" (property))
4870 ;; Declare ID code
4872 (declare-function org-id-store-link "org-id")
4873 (declare-function org-id-locations-load "org-id")
4874 (declare-function org-id-locations-save "org-id")
4875 (defvar org-id-track-globally)
4877 ;;; Variables for pre-computed regular expressions, all buffer local
4879 (defvar-local org-todo-regexp nil
4880 "Matches any of the TODO state keywords.
4881 Since TODO keywords are case-sensitive, `case-fold-search' is
4882 expected to be bound to nil when matching against this regexp.")
4884 (defvar-local org-not-done-regexp nil
4885 "Matches any of the TODO state keywords except the last one.
4886 Since TODO keywords are case-sensitive, `case-fold-search' is
4887 expected to be bound to nil when matching against this regexp.")
4889 (defvar-local org-not-done-heading-regexp nil
4890 "Matches a TODO headline that is not done.
4891 Since TODO keywords are case-sensitive, `case-fold-search' is
4892 expected to be bound to nil when matching against this regexp.")
4894 (defvar-local org-todo-line-regexp nil
4895 "Matches a headline and puts TODO state into group 2 if present.
4896 Since TODO keywords are case-sensitive, `case-fold-search' is
4897 expected to be bound to nil when matching against this regexp.")
4899 (defvar-local org-complex-heading-regexp nil
4900 "Matches a headline and puts everything into groups:
4902 group 1: Stars
4903 group 2: The TODO keyword, maybe
4904 group 3: Priority cookie
4905 group 4: True headline
4906 group 5: Tags
4908 Since TODO keywords are case-sensitive, `case-fold-search' is
4909 expected to be bound to nil when matching against this regexp.")
4911 (defvar-local org-complex-heading-regexp-format nil
4912 "Printf format to make regexp to match an exact headline.
4913 This regexp will match the headline of any node which has the
4914 exact headline text that is put into the format, but may have any
4915 TODO state, priority and tags.")
4917 (defvar-local org-todo-line-tags-regexp nil
4918 "Matches a headline and puts TODO state into group 2 if present.
4919 Also put tags into group 4 if tags are present.")
4921 (defconst org-plain-time-of-day-regexp
4922 (concat
4923 "\\(\\<[012]?[0-9]"
4924 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4925 "\\(--?"
4926 "\\(\\<[012]?[0-9]"
4927 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4928 "\\)?")
4929 "Regular expression to match a plain time or time range.
4930 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4931 groups carry important information:
4932 0 the full match
4933 1 the first time, range or not
4934 8 the second time, if it is a range.")
4936 (defconst org-plain-time-extension-regexp
4937 (concat
4938 "\\(\\<[012]?[0-9]"
4939 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4940 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4941 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4942 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4943 groups carry important information:
4944 0 the full match
4945 7 hours of duration
4946 9 minutes of duration")
4948 (defconst org-stamp-time-of-day-regexp
4949 (concat
4950 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4951 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4952 "\\(--?"
4953 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4954 "Regular expression to match a timestamp time or time range.
4955 After a match, the following groups carry important information:
4956 0 the full match
4957 1 date plus weekday, for back referencing to make sure both times are on the same day
4958 2 the first time, range or not
4959 4 the second time, if it is a range.")
4961 (defconst org-startup-options
4962 '(("fold" org-startup-folded t)
4963 ("overview" org-startup-folded t)
4964 ("nofold" org-startup-folded nil)
4965 ("showall" org-startup-folded nil)
4966 ("showeverything" org-startup-folded showeverything)
4967 ("content" org-startup-folded content)
4968 ("indent" org-startup-indented t)
4969 ("noindent" org-startup-indented nil)
4970 ("hidestars" org-hide-leading-stars t)
4971 ("showstars" org-hide-leading-stars nil)
4972 ("odd" org-odd-levels-only t)
4973 ("oddeven" org-odd-levels-only nil)
4974 ("align" org-startup-align-all-tables t)
4975 ("noalign" org-startup-align-all-tables nil)
4976 ("inlineimages" org-startup-with-inline-images t)
4977 ("noinlineimages" org-startup-with-inline-images nil)
4978 ("latexpreview" org-startup-with-latex-preview t)
4979 ("nolatexpreview" org-startup-with-latex-preview nil)
4980 ("customtime" org-display-custom-times t)
4981 ("logdone" org-log-done time)
4982 ("lognotedone" org-log-done note)
4983 ("nologdone" org-log-done nil)
4984 ("lognoteclock-out" org-log-note-clock-out t)
4985 ("nolognoteclock-out" org-log-note-clock-out nil)
4986 ("logrepeat" org-log-repeat state)
4987 ("lognoterepeat" org-log-repeat note)
4988 ("logdrawer" org-log-into-drawer t)
4989 ("nologdrawer" org-log-into-drawer nil)
4990 ("logstatesreversed" org-log-states-order-reversed t)
4991 ("nologstatesreversed" org-log-states-order-reversed nil)
4992 ("nologrepeat" org-log-repeat nil)
4993 ("logreschedule" org-log-reschedule time)
4994 ("lognotereschedule" org-log-reschedule note)
4995 ("nologreschedule" org-log-reschedule nil)
4996 ("logredeadline" org-log-redeadline time)
4997 ("lognoteredeadline" org-log-redeadline note)
4998 ("nologredeadline" org-log-redeadline nil)
4999 ("logrefile" org-log-refile time)
5000 ("lognoterefile" org-log-refile note)
5001 ("nologrefile" org-log-refile nil)
5002 ("fninline" org-footnote-define-inline t)
5003 ("nofninline" org-footnote-define-inline nil)
5004 ("fnlocal" org-footnote-section nil)
5005 ("fnauto" org-footnote-auto-label t)
5006 ("fnprompt" org-footnote-auto-label nil)
5007 ("fnconfirm" org-footnote-auto-label confirm)
5008 ("fnplain" org-footnote-auto-label plain)
5009 ("fnadjust" org-footnote-auto-adjust t)
5010 ("nofnadjust" org-footnote-auto-adjust nil)
5011 ("constcgs" constants-unit-system cgs)
5012 ("constSI" constants-unit-system SI)
5013 ("noptag" org-tag-persistent-alist nil)
5014 ("hideblocks" org-hide-block-startup t)
5015 ("nohideblocks" org-hide-block-startup nil)
5016 ("beamer" org-startup-with-beamer-mode t)
5017 ("entitiespretty" org-pretty-entities t)
5018 ("entitiesplain" org-pretty-entities nil))
5019 "Variable associated with STARTUP options for org-mode.
5020 Each element is a list of three items: the startup options (as written
5021 in the #+STARTUP line), the corresponding variable, and the value to set
5022 this variable to if the option is found. An optional forth element PUSH
5023 means to push this value onto the list in the variable.")
5025 (defcustom org-group-tags t
5026 "When non-nil (the default), use group tags.
5027 This can be turned on/off through `org-toggle-tags-groups'."
5028 :group 'org-tags
5029 :group 'org-startup
5030 :type 'boolean)
5032 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5034 (defun org-toggle-tags-groups ()
5035 "Toggle support for group tags.
5036 Support for group tags is controlled by the option
5037 `org-group-tags', which is non-nil by default."
5038 (interactive)
5039 (setq org-group-tags (not org-group-tags))
5040 (cond ((and (derived-mode-p 'org-agenda-mode)
5041 org-group-tags)
5042 (org-agenda-redo))
5043 ((derived-mode-p 'org-mode)
5044 (let ((org-inhibit-startup t)) (org-mode))))
5045 (message "Groups tags support has been turned %s"
5046 (if org-group-tags "on" "off")))
5048 (defun org-set-regexps-and-options (&optional tags-only)
5049 "Precompute regular expressions used in the current buffer.
5050 When optional argument TAGS-ONLY is non-nil, only compute tags
5051 related expressions."
5052 (when (derived-mode-p 'org-mode)
5053 (let ((alist (org--setup-collect-keywords
5054 (org-make-options-regexp
5055 (append '("FILETAGS" "TAGS" "SETUPFILE")
5056 (and (not tags-only)
5057 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5058 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5059 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5060 ;; Startup options. Get this early since it does change
5061 ;; behavior for other options (e.g., tags).
5062 (let ((startup (cdr (assq 'startup alist))))
5063 (dolist (option startup)
5064 (let ((entry (assoc-string option org-startup-options t)))
5065 (when entry
5066 (let ((var (nth 1 entry))
5067 (val (nth 2 entry)))
5068 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5069 (unless (listp (symbol-value var))
5070 (set (make-local-variable var) nil))
5071 (add-to-list var val)))))))
5072 (setq-local org-file-tags
5073 (mapcar #'org-add-prop-inherited
5074 (cdr (assq 'filetags alist))))
5075 (setq org-current-tag-alist
5076 (append org-tag-persistent-alist
5077 (let ((tags (cdr (assq 'tags alist))))
5078 (if tags (org-tag-string-to-alist tags)
5079 org-tag-alist))))
5080 (setq org-tag-groups-alist
5081 (org-tag-alist-to-groups org-current-tag-alist))
5082 (unless tags-only
5083 ;; File properties.
5084 (setq-local org-file-properties (cdr (assq 'property alist)))
5085 ;; Archive location.
5086 (let ((archive (cdr (assq 'archive alist))))
5087 (when archive (setq-local org-archive-location archive)))
5088 ;; Category.
5089 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5090 (when cat
5091 (setq-local org-category (intern cat))
5092 (setq-local org-file-properties
5093 (org--update-property-plist
5094 "CATEGORY" cat org-file-properties))))
5095 ;; Columns.
5096 (let ((column (cdr (assq 'columns alist))))
5097 (when column (setq-local org-columns-default-format column)))
5098 ;; Constants.
5099 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5100 ;; Link abbreviations.
5101 (let ((links (cdr (assq 'link alist))))
5102 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5103 ;; Priorities.
5104 (let ((priorities (cdr (assq 'priorities alist))))
5105 (when priorities
5106 (setq-local org-highest-priority (nth 0 priorities))
5107 (setq-local org-lowest-priority (nth 1 priorities))
5108 (setq-local org-default-priority (nth 2 priorities))))
5109 ;; Scripts.
5110 (let ((scripts (assq 'scripts alist)))
5111 (when scripts
5112 (setq-local org-use-sub-superscripts (cdr scripts))))
5113 ;; TODO keywords.
5114 (setq-local org-todo-kwd-alist nil)
5115 (setq-local org-todo-key-alist nil)
5116 (setq-local org-todo-key-trigger nil)
5117 (setq-local org-todo-keywords-1 nil)
5118 (setq-local org-done-keywords nil)
5119 (setq-local org-todo-heads nil)
5120 (setq-local org-todo-sets nil)
5121 (setq-local org-todo-log-states nil)
5122 (let ((todo-sequences
5123 (or (nreverse (cdr (assq 'todo alist)))
5124 (let ((d (default-value 'org-todo-keywords)))
5125 (if (not (stringp (car d))) d
5126 ;; XXX: Backward compatibility code.
5127 (list (cons org-todo-interpretation d)))))))
5128 (dolist (sequence todo-sequences)
5129 (let* ((sequence (or (run-hook-with-args-until-success
5130 'org-todo-setup-filter-hook sequence)
5131 sequence))
5132 (sequence-type (car sequence))
5133 (keywords (cdr sequence))
5134 (sep (member "|" keywords))
5135 names alist)
5136 (dolist (k (remove "|" keywords))
5137 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5139 (error "Invalid TODO keyword %s" k))
5140 (let ((name (match-string 1 k))
5141 (key (match-string 2 k))
5142 (log (org-extract-log-state-settings k)))
5143 (push name names)
5144 (push (cons name (and key (string-to-char key))) alist)
5145 (when log (push log org-todo-log-states))))
5146 (let* ((names (nreverse names))
5147 (done (if sep (org-remove-keyword-keys (cdr sep))
5148 (last names)))
5149 (head (car names))
5150 (tail (list sequence-type head (car done) (org-last done))))
5151 (add-to-list 'org-todo-heads head 'append)
5152 (push names org-todo-sets)
5153 (setq org-done-keywords (append org-done-keywords done nil))
5154 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5155 (setq org-todo-key-alist
5156 (append org-todo-key-alist
5157 (and alist
5158 (append '((:startgroup))
5159 (nreverse alist)
5160 '((:endgroup))))))
5161 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5162 (setq org-todo-sets (nreverse org-todo-sets)
5163 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5164 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5165 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5166 ;; Compute the regular expressions and other local variables.
5167 ;; Using `org-outline-regexp-bol' would complicate them much,
5168 ;; because of the fixed white space at the end of that string.
5169 (unless org-done-keywords
5170 (setq org-done-keywords
5171 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5172 (setq org-not-done-keywords
5173 (org-delete-all org-done-keywords
5174 (copy-sequence org-todo-keywords-1))
5175 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5176 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5177 org-not-done-heading-regexp
5178 (format org-heading-keyword-regexp-format org-not-done-regexp)
5179 org-todo-line-regexp
5180 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5181 org-complex-heading-regexp
5182 (concat "^\\(\\*+\\)"
5183 "\\(?: +" org-todo-regexp "\\)?"
5184 "\\(?: +\\(\\[#.\\]\\)\\)?"
5185 "\\(?: +\\(.*?\\)\\)??"
5186 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5187 "[ \t]*$")
5188 org-complex-heading-regexp-format
5189 (concat "^\\(\\*+\\)"
5190 "\\(?: +" org-todo-regexp "\\)?"
5191 "\\(?: +\\(\\[#.\\]\\)\\)?"
5192 "\\(?: +"
5193 ;; Stats cookies can be stuck to body.
5194 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5195 "\\(%s\\)"
5196 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5197 "\\)"
5198 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5199 "[ \t]*$")
5200 org-todo-line-tags-regexp
5201 (concat "^\\(\\*+\\)"
5202 "\\(?: +" org-todo-regexp "\\)?"
5203 "\\(?: +\\(.*?\\)\\)??"
5204 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5205 "[ \t]*$"))
5206 (org-compute-latex-and-related-regexp)))))
5208 (defun org--setup-collect-keywords (regexp &optional files alist)
5209 "Return setup keywords values as an alist.
5211 REGEXP matches a subset of setup keywords. FILES is a list of
5212 file names already visited. It is used to avoid circular setup
5213 files. ALIST, when non-nil, is the alist computed so far.
5215 Return value contains the following keys: `archive', `category',
5216 `columns', `constants', `filetags', `link', `priorities',
5217 `property', `scripts', `startup', `tags' and `todo'."
5218 (org-with-wide-buffer
5219 (goto-char (point-min))
5220 (let ((case-fold-search t))
5221 (while (re-search-forward regexp nil t)
5222 (let ((element (org-element-at-point)))
5223 (when (eq (org-element-type element) 'keyword)
5224 (let ((key (org-element-property :key element))
5225 (value (org-element-property :value element)))
5226 (cond
5227 ((equal key "ARCHIVE")
5228 (when (org-string-nw-p value)
5229 (push (cons 'archive value) alist)))
5230 ((equal key "CATEGORY") (push (cons 'category value) alist))
5231 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5232 ((equal key "CONSTANTS")
5233 (let* ((constants (assq 'constants alist))
5234 (store (cdr constants)))
5235 (dolist (pair (org-split-string value))
5236 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5237 pair)
5238 (let* ((name (match-string 1 pair))
5239 (value (match-string 2 pair))
5240 (old (assoc name store)))
5241 (if old (setcdr old value)
5242 (push (cons name value) store)))))
5243 (if constants (setcdr constants store)
5244 (push (cons 'constants store) alist))))
5245 ((equal key "FILETAGS")
5246 (when (org-string-nw-p value)
5247 (let ((old (assq 'filetags alist))
5248 (new (apply #'nconc
5249 (mapcar (lambda (x) (org-split-string x ":"))
5250 (org-split-string value)))))
5251 (if old (setcdr old (append new (cdr old)))
5252 (push (cons 'filetags new) alist)))))
5253 ((equal key "LINK")
5254 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5255 (let ((links (assq 'link alist))
5256 (pair (cons (match-string-no-properties 1 value)
5257 (match-string-no-properties 2 value))))
5258 (if links (push pair (cdr links))
5259 (push (list 'link pair) alist)))))
5260 ((equal key "OPTIONS")
5261 (when (and (org-string-nw-p value)
5262 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5263 (push (cons 'scripts (read (match-string 1 value))) alist)))
5264 ((equal key "PRIORITIES")
5265 (push (cons 'priorities
5266 (let ((prio (org-split-string value)))
5267 (if (< (length prio) 3) '(?A ?C ?B)
5268 (mapcar #'string-to-char prio))))
5269 alist))
5270 ((equal key "PROPERTY")
5271 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5272 (let* ((property (assq 'property alist))
5273 (value (org--update-property-plist
5274 (match-string-no-properties 1 value)
5275 (match-string-no-properties 2 value)
5276 (cdr property))))
5277 (if property (setcdr property value)
5278 (push (cons 'property value) alist)))))
5279 ((equal key "STARTUP")
5280 (let ((startup (assq 'startup alist)))
5281 (if startup
5282 (setcdr startup
5283 (append (cdr startup) (org-split-string value)))
5284 (push (cons 'startup (org-split-string value)) alist))))
5285 ((equal key "TAGS")
5286 (let ((tag-cell (assq 'tags alist)))
5287 (if tag-cell
5288 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5289 (push (cons 'tags value) alist))))
5290 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5291 (let ((todo (assq 'todo alist))
5292 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5293 (org-split-string value))))
5294 (if todo (push value (cdr todo))
5295 (push (list 'todo value) alist))))
5296 ((equal key "SETUPFILE")
5297 (unless buffer-read-only ; Do not check in Gnus messages.
5298 (let ((f (and (org-string-nw-p value)
5299 (expand-file-name
5300 (org-unbracket-string "\"" "\"" value)))))
5301 (when (and f (file-readable-p f) (not (member f files)))
5302 (with-temp-buffer
5303 (setq default-directory (file-name-directory f))
5304 (insert-file-contents f)
5305 (setq alist
5306 ;; Fake Org mode to benefit from cache
5307 ;; without recurring needlessly.
5308 (let ((major-mode 'org-mode))
5309 (org--setup-collect-keywords
5310 regexp (cons f files) alist)))))))))))))))
5311 alist)
5313 (defun org-tag-string-to-alist (s)
5314 "Return tag alist associated to string S.
5315 S is a value for TAGS keyword or produced with
5316 `org-tag-alist-to-string'. Return value is an alist suitable for
5317 `org-tag-alist' or `org-tag-persistent-alist'."
5318 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5319 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5320 "\\|{.+?}\\)" ; regular expression
5321 "\\(?:(\\(.\\))\\)?\\'"))
5322 alist group-flag)
5323 (dolist (tokens lines (cdr (nreverse alist)))
5324 (push '(:newline) alist)
5325 (while tokens
5326 (let ((token (pop tokens)))
5327 (pcase token
5328 ("{"
5329 (push '(:startgroup) alist)
5330 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5331 ("}"
5332 (push '(:endgroup) alist)
5333 (setq group-flag nil))
5334 ("["
5335 (push '(:startgrouptag) alist)
5336 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5337 ("]"
5338 (push '(:endgrouptag) alist)
5339 (setq group-flag nil))
5340 (":"
5341 (push '(:grouptags) alist))
5342 ((guard (string-match tag-re token))
5343 (let ((tag (match-string 1 token))
5344 (key (and (match-beginning 2)
5345 (string-to-char (match-string 2 token)))))
5346 ;; Push all tags in groups, no matter if they already
5347 ;; appear somewhere else in the list.
5348 (when (or group-flag (not (assoc tag alist)))
5349 (push (cons tag key) alist))))))))))
5351 (defun org-tag-alist-to-string (alist &optional skip-key)
5352 "Return tag string associated to ALIST.
5354 ALIST is an alist, as defined in `org-tag-alist' or
5355 `org-tag-persistent-alist', or produced with
5356 `org-tag-string-to-alist'.
5358 Return value is a string suitable as a value for \"TAGS\"
5359 keyword.
5361 When optional argument SKIP-KEY is non-nil, skip selection keys
5362 next to tags."
5363 (mapconcat (lambda (token)
5364 (pcase token
5365 (`(:startgroup) "{")
5366 (`(:endgroup) "}")
5367 (`(:startgrouptag) "[")
5368 (`(:endgrouptag) "]")
5369 (`(:grouptags) ":")
5370 (`(:newline) "\\n")
5371 ((and
5372 (guard (not skip-key))
5373 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5374 (format "%s(%c)" tag key))
5375 (`(,(and tag (pred stringp)) . ,_) tag)
5376 (_ (user-error "Invalid tag token: %S" token))))
5377 alist
5378 " "))
5380 (defun org-tag-alist-to-groups (alist)
5381 "Return group alist from tag ALIST.
5382 ALIST is an alist, as defined in `org-tag-alist' or
5383 `org-tag-persistent-alist', or produced with
5384 `org-tag-string-to-alist'. Return value is an alist following
5385 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5386 a string, summarizing TAGS, as a list of strings."
5387 (let (groups group-status current-group)
5388 (dolist (token alist (nreverse groups))
5389 (pcase token
5390 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5391 (`(,(or :endgroup :endgrouptag))
5392 (when (eq group-status 'append)
5393 (push (nreverse current-group) groups))
5394 (setq group-status nil))
5395 (`(:grouptags) (setq group-status 'append))
5396 ((and `(,tag . ,_) (guard group-status))
5397 (if (eq group-status 'append) (push tag current-group)
5398 (setq current-group (list tag))))
5399 (_ nil)))))
5401 (defun org-file-contents (file &optional noerror)
5402 "Return the contents of FILE, as a string."
5403 (if (and file (file-readable-p file))
5404 (with-temp-buffer
5405 (insert-file-contents file)
5406 (buffer-string))
5407 (funcall (if noerror 'message 'error)
5408 "Cannot read file \"%s\"%s"
5409 file
5410 (let ((from (buffer-file-name (buffer-base-buffer))))
5411 (if from (concat " (referenced in file \"" from "\")") "")))))
5413 (defun org-extract-log-state-settings (x)
5414 "Extract the log state setting from a TODO keyword string.
5415 This will extract info from a string like \"WAIT(w@/!)\"."
5416 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5417 (let ((kw (match-string 1 x))
5418 (log1 (and (match-end 3) (match-string 3 x)))
5419 (log2 (and (match-end 4) (match-string 4 x))))
5420 (and (or log1 log2)
5421 (list kw
5422 (and log1 (if (equal log1 "!") 'time 'note))
5423 (and log2 (if (equal log2 "!") 'time 'note)))))))
5425 (defun org-remove-keyword-keys (list)
5426 "Remove a pair of parenthesis at the end of each string in LIST."
5427 (mapcar (lambda (x)
5428 (if (string-match "(.*)$" x)
5429 (substring x 0 (match-beginning 0))
5431 list))
5433 (defun org-assign-fast-keys (alist)
5434 "Assign fast keys to a keyword-key alist.
5435 Respect keys that are already there."
5436 (let (new e (alt ?0))
5437 (while (setq e (pop alist))
5438 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5439 (cdr e)) ;; Key already assigned.
5440 (push e new)
5441 (let ((clist (string-to-list (downcase (car e))))
5442 (used (append new alist)))
5443 (when (= (car clist) ?@)
5444 (pop clist))
5445 (while (and clist (rassoc (car clist) used))
5446 (pop clist))
5447 (unless clist
5448 (while (rassoc alt used)
5449 (cl-incf alt)))
5450 (push (cons (car e) (or (car clist) alt)) new))))
5451 (nreverse new)))
5453 ;;; Some variables used in various places
5455 (defvar org-window-configuration nil
5456 "Used in various places to store a window configuration.")
5457 (defvar org-selected-window nil
5458 "Used in various places to store a window configuration.")
5459 (defvar org-finish-function nil
5460 "Function to be called when `C-c C-c' is used.
5461 This is for getting out of special buffers like capture.")
5462 (defvar org-last-state)
5464 ;; Defined somewhere in this file, but used before definition.
5465 (defvar org-entities) ;; defined in org-entities.el
5466 (defvar org-struct-menu)
5467 (defvar org-org-menu)
5468 (defvar org-tbl-menu)
5470 ;;;; Define the Org mode
5472 ;; We use a before-change function to check if a table might need
5473 ;; an update.
5474 (defvar org-table-may-need-update t
5475 "Indicates that a table might need an update.
5476 This variable is set by `org-before-change-function'.
5477 `org-table-align' sets it back to nil.")
5478 (defun org-before-change-function (_beg _end)
5479 "Every change indicates that a table might need an update."
5480 (setq org-table-may-need-update t))
5481 (defvar org-mode-map)
5482 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5483 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5484 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5485 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5486 (defvar org-table-buffer-is-an nil)
5488 (defvar bidi-paragraph-direction)
5489 (defvar buffer-face-mode-face)
5491 (require 'outline)
5493 ;; Other stuff we need.
5494 (require 'time-date)
5495 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5496 (require 'easymenu)
5497 (autoload 'easy-menu-add "easymenu")
5498 (require 'overlay)
5500 ;; (require 'org-macs) moved higher up in the file before it is first used
5501 (require 'org-entities)
5502 ;; (require 'org-compat) moved higher up in the file before it is first used
5503 (require 'org-faces)
5504 (require 'org-list)
5505 (require 'org-pcomplete)
5506 (require 'org-src)
5507 (require 'org-footnote)
5508 (require 'org-macro)
5510 ;; babel
5511 (require 'ob)
5513 ;;;###autoload
5514 (define-derived-mode org-mode outline-mode "Org"
5515 "Outline-based notes management and organizer, alias
5516 \"Carsten's outline-mode for keeping track of everything.\"
5518 Org mode develops organizational tasks around a NOTES file which
5519 contains information about projects as plain text. Org mode is
5520 implemented on top of Outline mode, which is ideal to keep the content
5521 of large files well structured. It supports ToDo items, deadlines and
5522 time stamps, which magically appear in the diary listing of the Emacs
5523 calendar. Tables are easily created with a built-in table editor.
5524 Plain text URL-like links connect to websites, emails (VM), Usenet
5525 messages (Gnus), BBDB entries, and any files related to the project.
5526 For printing and sharing of notes, an Org file (or a part of it)
5527 can be exported as a structured ASCII or HTML file.
5529 The following commands are available:
5531 \\{org-mode-map}"
5533 ;; Get rid of Outline menus, they are not needed
5534 ;; Need to do this here because define-derived-mode sets up
5535 ;; the keymap so late. Still, it is a waste to call this each time
5536 ;; we switch another buffer into Org mode.
5537 (define-key org-mode-map [menu-bar headings] 'undefined)
5538 (define-key org-mode-map [menu-bar hide] 'undefined)
5539 (define-key org-mode-map [menu-bar show] 'undefined)
5541 (org-load-modules-maybe)
5542 (org-install-agenda-files-menu)
5543 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5544 (add-to-invisibility-spec '(org-cwidth))
5545 (add-to-invisibility-spec '(org-hide-block . t))
5546 (setq-local outline-regexp org-outline-regexp)
5547 (setq-local outline-level 'org-outline-level)
5548 (setq bidi-paragraph-direction 'left-to-right)
5549 (when (and org-ellipsis
5550 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5551 (fboundp 'make-glyph-code))
5552 (unless org-display-table
5553 (setq org-display-table (make-display-table)))
5554 (set-display-table-slot
5555 org-display-table 4
5556 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5557 (if (stringp org-ellipsis) org-ellipsis "..."))))
5558 (setq buffer-display-table org-display-table))
5559 (org-set-regexps-and-options)
5560 (org-set-font-lock-defaults)
5561 (when (and org-tag-faces (not org-tags-special-faces-re))
5562 ;; tag faces set outside customize.... force initialization.
5563 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5564 ;; Calc embedded
5565 (setq-local calc-embedded-open-mode "# ")
5566 ;; Modify a few syntax entries
5567 (modify-syntax-entry ?@ "w")
5568 (modify-syntax-entry ?\" "\"")
5569 (modify-syntax-entry ?\\ "_")
5570 (modify-syntax-entry ?~ "_")
5571 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5572 ;; Activate before-change-function
5573 (setq-local org-table-may-need-update t)
5574 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5575 ;; Check for running clock before killing a buffer
5576 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5577 ;; Initialize macros templates.
5578 (org-macro-initialize-templates)
5579 ;; Initialize radio targets.
5580 (org-update-radio-target-regexp)
5581 ;; Indentation.
5582 (setq-local indent-line-function 'org-indent-line)
5583 (setq-local indent-region-function 'org-indent-region)
5584 ;; Filling and auto-filling.
5585 (org-setup-filling)
5586 ;; Comments.
5587 (org-setup-comments-handling)
5588 ;; Initialize cache.
5589 (org-element-cache-reset)
5590 ;; Beginning/end of defun
5591 (setq-local beginning-of-defun-function 'org-backward-element)
5592 (setq-local end-of-defun-function
5593 (lambda ()
5594 (if (not (org-at-heading-p))
5595 (org-forward-element)
5596 (org-forward-element)
5597 (forward-char -1))))
5598 ;; Next error for sparse trees
5599 (setq-local next-error-function 'org-occur-next-match)
5600 ;; Make sure dependence stuff works reliably, even for users who set it
5601 ;; too late :-(
5602 (if org-enforce-todo-dependencies
5603 (add-hook 'org-blocker-hook
5604 'org-block-todo-from-children-or-siblings-or-parent)
5605 (remove-hook 'org-blocker-hook
5606 'org-block-todo-from-children-or-siblings-or-parent))
5607 (if org-enforce-todo-checkbox-dependencies
5608 (add-hook 'org-blocker-hook
5609 'org-block-todo-from-checkboxes)
5610 (remove-hook 'org-blocker-hook
5611 'org-block-todo-from-checkboxes))
5613 ;; Align options lines
5614 (setq-local
5615 align-mode-rules-list
5616 '((org-in-buffer-settings
5617 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5618 (modes . '(org-mode)))))
5620 ;; Imenu
5621 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5623 ;; Make isearch reveal context
5624 (setq-local outline-isearch-open-invisible-function
5625 (lambda (&rest _) (org-show-context 'isearch)))
5627 ;; Setup the pcomplete hooks
5628 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5629 (setq-local pcomplete-command-name-function 'org-command-at-point)
5630 (setq-local pcomplete-default-completion-function 'ignore)
5631 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5632 (setq-local pcomplete-termination-string "")
5633 (setq-local buffer-face-mode-face 'org-default)
5635 ;; If empty file that did not turn on Org mode automatically, make
5636 ;; it to.
5637 (when (and org-insert-mode-line-in-empty-file
5638 (called-interactively-p 'any)
5639 (= (point-min) (point-max)))
5640 (insert "# -*- mode: org -*-\n\n"))
5641 (unless org-inhibit-startup
5642 (org-unmodified
5643 (when org-startup-with-beamer-mode (org-beamer-mode))
5644 (when org-startup-align-all-tables
5645 (org-table-map-tables #'org-table-align t))
5646 (when org-startup-with-inline-images (org-display-inline-images))
5647 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5648 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5649 (when org-startup-truncated (setq truncate-lines t))
5650 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5651 (org-refresh-effort-properties)))
5652 ;; Try to set `org-hide' face correctly.
5653 (let ((foreground (org-find-invisible-foreground)))
5654 (when foreground
5655 (set-face-foreground 'org-hide foreground))))
5657 ;; Update `customize-package-emacs-version-alist'
5658 (add-to-list 'customize-package-emacs-version-alist
5659 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5660 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5661 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5662 ("9.0" . "26.1")))
5664 (defvar org-mode-transpose-word-syntax-table
5665 (let ((st (make-syntax-table text-mode-syntax-table)))
5666 (dolist (c org-emphasis-alist st)
5667 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5669 (when (fboundp 'abbrev-table-put)
5670 (abbrev-table-put org-mode-abbrev-table
5671 :parents (list text-mode-abbrev-table)))
5673 (defun org-find-invisible-foreground ()
5674 (let ((candidates (remove
5675 "unspecified-bg"
5676 (nconc
5677 (list (face-background 'default)
5678 (face-background 'org-default))
5679 (mapcar
5680 (lambda (alist)
5681 (when (boundp alist)
5682 (cdr (assq 'background-color (symbol-value alist)))))
5683 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5684 (list (face-foreground 'org-hide))))))
5685 (car (remove nil candidates))))
5687 (defun org-current-time (&optional rounding-minutes past)
5688 "Current time, possibly rounded to ROUNDING-MINUTES.
5689 When ROUNDING-MINUTES is not an integer, fall back on the car of
5690 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5691 the rounding returns a past time."
5692 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5693 (car org-time-stamp-rounding-minutes)))
5694 (time (decode-time)) res)
5695 (if (< r 1)
5696 (current-time)
5697 (setq res
5698 (apply 'encode-time
5699 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5700 (nthcdr 2 time))))
5701 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5702 (seconds-to-time (- (float-time res) (* r 60)))
5703 res))))
5705 (defun org-today ()
5706 "Return today date, considering `org-extend-today-until'."
5707 (time-to-days
5708 (time-subtract (current-time)
5709 (list 0 (* 3600 org-extend-today-until) 0))))
5711 ;;;; Font-Lock stuff, including the activators
5713 (defvar org-mouse-map (make-sparse-keymap))
5714 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5715 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5716 (when org-mouse-1-follows-link
5717 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5718 (when org-tab-follows-link
5719 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5720 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5722 (require 'font-lock)
5724 (defconst org-non-link-chars "]\t\n\r<>")
5725 (defvar org-link-types-re nil
5726 "Matches a link that has a url-like prefix like \"http:\"")
5727 (defvar org-link-re-with-space nil
5728 "Matches a link with spaces, optional angular brackets around it.")
5729 (defvar org-link-re-with-space2 nil
5730 "Matches a link with spaces, optional angular brackets around it.")
5731 (defvar org-link-re-with-space3 nil
5732 "Matches a link with spaces, only for internal part in bracket links.")
5733 (defvar org-angle-link-re nil
5734 "Matches link with angular brackets, spaces are allowed.")
5735 (defvar org-plain-link-re nil
5736 "Matches plain link, without spaces.")
5737 (defvar org-bracket-link-regexp nil
5738 "Matches a link in double brackets.")
5739 (defvar org-bracket-link-analytic-regexp nil
5740 "Regular expression used to analyze links.
5741 Here is what the match groups contain after a match:
5742 1: http:
5743 2: http
5744 3: path
5745 4: [desc]
5746 5: desc")
5747 (defvar org-bracket-link-analytic-regexp++ nil
5748 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5749 (defvar org-any-link-re nil
5750 "Regular expression matching any link.")
5752 (defconst org-match-sexp-depth 3
5753 "Number of stacked braces for sub/superscript matching.")
5755 (defun org-create-multibrace-regexp (left right n)
5756 "Create a regular expression which will match a balanced sexp.
5757 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5758 as single character strings.
5759 The regexp returned will match the entire expression including the
5760 delimiters. It will also define a single group which contains the
5761 match except for the outermost delimiters. The maximum depth of
5762 stacked delimiters is N. Escaping delimiters is not possible."
5763 (let* ((nothing (concat "[^" left right "]*?"))
5764 (or "\\|")
5765 (re nothing)
5766 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5767 (while (> n 1)
5768 (setq n (1- n)
5769 re (concat re or next)
5770 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5771 (concat left "\\(" re "\\)" right)))
5773 (defconst org-match-substring-regexp
5774 (concat
5775 "\\(\\S-\\)\\([_^]\\)\\("
5776 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5777 "\\|"
5778 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5779 "\\|"
5780 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5781 "The regular expression matching a sub- or superscript.")
5783 (defconst org-match-substring-with-braces-regexp
5784 (concat
5785 "\\(\\S-\\)\\([_^]\\)"
5786 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5787 "The regular expression matching a sub- or superscript, forcing braces.")
5789 (defun org-make-link-regexps ()
5790 "Update the link regular expressions.
5791 This should be called after the variable `org-link-parameters' has changed."
5792 (let ((types-re (regexp-opt (org-link-types) t)))
5793 (setq org-link-types-re
5794 (concat "\\`" types-re ":")
5795 org-link-re-with-space
5796 (concat "<?" types-re ":"
5797 "\\([^" org-non-link-chars " ]"
5798 "[^" org-non-link-chars "]*"
5799 "[^" org-non-link-chars " ]\\)>?")
5800 org-link-re-with-space2
5801 (concat "<?" types-re ":"
5802 "\\([^" org-non-link-chars " ]"
5803 "[^\t\n\r]*"
5804 "[^" org-non-link-chars " ]\\)>?")
5805 org-link-re-with-space3
5806 (concat "<?" types-re ":"
5807 "\\([^" org-non-link-chars " ]"
5808 "[^\t\n\r]*\\)")
5809 org-angle-link-re
5810 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5811 types-re)
5812 org-plain-link-re
5813 (concat
5814 "\\<" types-re ":"
5815 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5816 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5817 org-bracket-link-regexp
5818 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5819 org-bracket-link-analytic-regexp
5820 (concat
5821 "\\[\\["
5822 "\\(" types-re ":\\)?"
5823 "\\([^]]+\\)"
5824 "\\]"
5825 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5826 "\\]")
5827 org-bracket-link-analytic-regexp++
5828 (concat
5829 "\\[\\["
5830 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5831 "\\([^]]+\\)"
5832 "\\]"
5833 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5834 "\\]")
5835 org-any-link-re
5836 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5837 org-angle-link-re "\\)\\|\\("
5838 org-plain-link-re "\\)"))))
5840 (org-make-link-regexps)
5842 (defvar org-emph-face nil)
5844 (defun org-do-emphasis-faces (limit)
5845 "Run through the buffer and emphasize strings."
5846 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5847 (car org-emphasis-regexp-components))))
5848 (catch :exit
5849 (while (re-search-forward quick-re limit t)
5850 (let* ((marker (match-string 2))
5851 (verbatim? (member marker '("~" "="))))
5852 (when (save-excursion
5853 (goto-char (match-beginning 0))
5854 ;; Do not match headline stars. Do not consider
5855 ;; stars of a headline as closing marker for bold
5856 ;; markup either.
5857 (and (not (looking-at-p org-outline-regexp-bol))
5858 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5859 (not (string-match-p
5860 (concat org-outline-regexp-bol "\\'")
5861 (match-string 0)))))
5862 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5863 (font-lock-prepend-text-property
5864 (match-beginning 2) (match-end 2) 'face face)
5865 (when verbatim?
5866 (org-remove-flyspell-overlays-in
5867 (match-beginning 0) (match-end 0)))
5868 (add-text-properties (match-beginning 2) (match-end 2)
5869 '(font-lock-multiline t org-emphasis t))
5870 (when org-hide-emphasis-markers
5871 (add-text-properties (match-end 4) (match-beginning 5)
5872 '(invisible org-link))
5873 (add-text-properties (match-beginning 3) (match-end 3)
5874 '(invisible org-link)))
5875 (throw :exit t))))))))
5877 (defun org-emphasize (&optional char)
5878 "Insert or change an emphasis, i.e. a font like bold or italic.
5879 If there is an active region, change that region to a new emphasis.
5880 If there is no region, just insert the marker characters and position
5881 the cursor between them.
5882 CHAR should be the marker character. If it is a space, it means to
5883 remove the emphasis of the selected region.
5884 If CHAR is not given (for example in an interactive call) it will be
5885 prompted for."
5886 (interactive)
5887 (let ((erc org-emphasis-regexp-components)
5888 (string "") beg end move s)
5889 (if (org-region-active-p)
5890 (setq beg (region-beginning)
5891 end (region-end)
5892 string (buffer-substring beg end))
5893 (setq move t))
5895 (unless char
5896 (message "Emphasis marker or tag: [%s]"
5897 (mapconcat #'car org-emphasis-alist ""))
5898 (setq char (read-char-exclusive)))
5899 (if (equal char ?\s)
5900 (setq s ""
5901 move nil)
5902 (unless (assoc (char-to-string char) org-emphasis-alist)
5903 (user-error "No such emphasis marker: \"%c\"" char))
5904 (setq s (char-to-string char)))
5905 (while (and (> (length string) 1)
5906 (equal (substring string 0 1) (substring string -1))
5907 (assoc (substring string 0 1) org-emphasis-alist))
5908 (setq string (substring string 1 -1)))
5909 (setq string (concat s string s))
5910 (when beg (delete-region beg end))
5911 (unless (or (bolp)
5912 (string-match (concat "[" (nth 0 erc) "\n]")
5913 (char-to-string (char-before (point)))))
5914 (insert " "))
5915 (unless (or (eobp)
5916 (string-match (concat "[" (nth 1 erc) "\n]")
5917 (char-to-string (char-after (point)))))
5918 (insert " ") (backward-char 1))
5919 (insert string)
5920 (and move (backward-char 1))))
5922 (defconst org-nonsticky-props
5923 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5925 (defsubst org-rear-nonsticky-at (pos)
5926 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5928 (defun org-activate-plain-links (limit)
5929 "Add link properties for plain links."
5930 (when (and (re-search-forward org-plain-link-re limit t)
5931 (not (org-in-src-block-p)))
5933 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5934 'face))
5935 (link (match-string-no-properties 0))
5936 (type (match-string-no-properties 1))
5937 (path (match-string-no-properties 2))
5938 (link-start (match-beginning 0))
5939 (link-end (match-end 0))
5940 (link-face (org-link-get-parameter type :face))
5941 (help-echo (org-link-get-parameter type :help-echo))
5942 (htmlize-link (org-link-get-parameter type :htmlize-link))
5943 (activate-func (org-link-get-parameter type :activate-func)))
5944 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5945 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5946 (add-text-properties (match-beginning 0) (match-end 0)
5947 (list
5948 'mouse-face (or (org-link-get-parameter type :mouse-face)
5949 'highlight)
5950 'face (cond
5951 ;; A function that returns a face
5952 ((functionp link-face)
5953 (funcall link-face path))
5954 ;; a face
5955 ((facep link-face)
5956 link-face)
5957 ;; An anonymous face
5958 ((consp link-face)
5959 link-face)
5960 ;; default
5962 'org-link))
5963 'help-echo (cond
5964 ((stringp help-echo)
5965 help-echo)
5966 ((functionp help-echo)
5967 help-echo)
5969 (concat "LINK: "
5970 (save-match-data
5971 (org-link-unescape link)))))
5972 'htmlize-link (cond
5973 ((functionp htmlize-link)
5974 (funcall htmlize-link path))
5976 `(:uri ,link)))
5977 'keymap (or (org-link-get-parameter type :keymap)
5978 org-mouse-map)
5979 'org-link-start (match-beginning 0)))
5980 (org-rear-nonsticky-at (match-end 0))
5981 (when activate-func
5982 (funcall activate-func link-start link-end path nil))
5983 t))))
5985 (defun org-activate-code (limit)
5986 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5987 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (remove-text-properties (match-beginning 0) (match-end 0)
5989 '(display t invisible t intangible t))
5992 (defcustom org-src-fontify-natively t
5993 "When non-nil, fontify code in code blocks.
5994 See also the `org-block' face."
5995 :type 'boolean
5996 :version "24.4"
5997 :package-version '(Org . "8.3")
5998 :group 'org-appearance
5999 :group 'org-babel)
6001 (defcustom org-allow-promoting-top-level-subtree nil
6002 "When non-nil, allow promoting a top level subtree.
6003 The leading star of the top level headline will be replaced
6004 by a #."
6005 :type 'boolean
6006 :version "24.1"
6007 :group 'org-appearance)
6009 (defun org-fontify-meta-lines-and-blocks (limit)
6010 (condition-case nil
6011 (org-fontify-meta-lines-and-blocks-1 limit)
6012 (error (message "org-mode fontification error in %S at %d"
6013 (current-buffer)
6014 (line-number-at-pos)))))
6016 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6017 "Fontify #+ lines and blocks."
6018 (let ((case-fold-search t))
6019 (when (re-search-forward
6020 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6021 limit t)
6022 (let ((beg (match-beginning 0))
6023 (block-start (match-end 0))
6024 (block-end nil)
6025 (lang (match-string 7))
6026 (beg1 (line-beginning-position 2))
6027 (dc1 (downcase (match-string 2)))
6028 (dc3 (downcase (match-string 3)))
6029 end end1 quoting block-type)
6030 (cond
6031 ((and (match-end 4) (equal dc3 "+begin"))
6032 ;; Truly a block
6033 (setq block-type (downcase (match-string 5))
6034 quoting (member block-type org-protecting-blocks))
6035 (when (re-search-forward
6036 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6037 nil t) ;; on purpose, we look further than LIMIT
6038 (setq end (min (point-max) (match-end 0))
6039 end1 (min (point-max) (1- (match-beginning 0))))
6040 (setq block-end (match-beginning 0))
6041 (when quoting
6042 (org-remove-flyspell-overlays-in beg1 end1)
6043 (remove-text-properties beg end
6044 '(display t invisible t intangible t)))
6045 (add-text-properties
6046 beg end '(font-lock-fontified t font-lock-multiline t))
6047 (add-text-properties beg beg1 '(face org-meta-line))
6048 (org-remove-flyspell-overlays-in beg beg1)
6049 (add-text-properties ; For end_src
6050 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6051 (org-remove-flyspell-overlays-in end1 end)
6052 (cond
6053 ((and lang (not (string= lang "")) org-src-fontify-natively)
6054 (org-src-font-lock-fontify-block lang block-start block-end)
6055 (add-text-properties beg1 block-end '(src-block t)))
6056 (quoting
6057 (add-text-properties beg1 (min (point-max) (1+ end1))
6058 (list 'face
6059 (list :inherit
6060 (let ((face-name
6061 (intern (format "org-block-%s" lang))))
6062 (append (and (facep face-name) (list face-name))
6063 '(org-block))))))) ; end of source block
6064 ((not org-fontify-quote-and-verse-blocks))
6065 ((string= block-type "quote")
6066 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6067 ((string= block-type "verse")
6068 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6069 (add-text-properties beg beg1 '(face org-block-begin-line))
6070 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6071 '(face org-block-end-line))
6073 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6074 (org-remove-flyspell-overlays-in
6075 (match-beginning 0)
6076 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6077 (add-text-properties
6078 beg (match-end 3)
6079 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6080 '(font-lock-fontified t invisible t)
6081 '(font-lock-fontified t face org-document-info-keyword)))
6082 (add-text-properties
6083 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6084 (if (string-equal dc1 "+title:")
6085 '(font-lock-fontified t face org-document-title)
6086 '(font-lock-fontified t face org-document-info))))
6087 ((string-prefix-p "+caption" dc1)
6088 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6089 (remove-text-properties (match-beginning 0) (match-end 0)
6090 '(display t invisible t intangible t))
6091 ;; Handle short captions.
6092 (save-excursion
6093 (beginning-of-line)
6094 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6095 (add-text-properties (line-beginning-position) (match-end 1)
6096 '(font-lock-fontified t face org-meta-line))
6097 (add-text-properties (match-end 0) (line-end-position)
6098 '(font-lock-fontified t face org-block))
6100 ((member dc3 '(" " ""))
6101 (org-remove-flyspell-overlays-in beg (match-end 0))
6102 (add-text-properties
6103 beg (match-end 0)
6104 '(font-lock-fontified t face font-lock-comment-face)))
6105 (t ;; just any other in-buffer setting, but not indented
6106 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6107 (remove-text-properties (match-beginning 0) (match-end 0)
6108 '(display t invisible t intangible t))
6109 (add-text-properties beg (match-end 0)
6110 '(font-lock-fontified t face org-meta-line))
6111 t))))))
6113 (defun org-fontify-drawers (limit)
6114 "Fontify drawers."
6115 (when (re-search-forward org-drawer-regexp limit t)
6116 (add-text-properties
6117 (match-beginning 0) (match-end 0)
6118 '(font-lock-fontified t face org-special-keyword))
6119 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6122 (defun org-fontify-macros (limit)
6123 "Fontify macros."
6124 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6125 (add-text-properties
6126 (match-beginning 0) (match-end 0)
6127 '(font-lock-fontified t face org-macro))
6128 (when org-hide-macro-markers
6129 (add-text-properties (match-end 2) (match-beginning 2)
6130 '(invisible t))
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 '(invisible t)))
6133 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6136 (defun org-activate-angle-links (limit)
6137 "Add text properties for angle links."
6138 (when (and (re-search-forward org-angle-link-re limit t)
6139 (not (org-in-src-block-p)))
6140 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6141 (add-text-properties (match-beginning 0) (match-end 0)
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map
6144 'font-lock-multiline t))
6145 (org-rear-nonsticky-at (match-end 0))
6148 (defun org-activate-footnote-links (limit)
6149 "Add text properties for footnotes."
6150 (let ((fn (org-footnote-next-reference-or-definition limit)))
6151 (when fn
6152 (let* ((beg (nth 1 fn))
6153 (end (nth 2 fn))
6154 (label (car fn))
6155 (referencep (/= (line-beginning-position) beg)))
6156 (when (and referencep (nth 3 fn))
6157 (save-excursion
6158 (goto-char beg)
6159 (search-forward (or label "fn:"))
6160 (org-remove-flyspell-overlays-in beg (match-end 0))))
6161 (add-text-properties beg end
6162 (list 'mouse-face 'highlight
6163 'keymap org-mouse-map
6164 'help-echo
6165 (if referencep "Footnote reference"
6166 "Footnote definition")
6167 'font-lock-fontified t
6168 'font-lock-multiline t
6169 'face 'org-footnote))))))
6171 (defun org-activate-bracket-links (limit)
6172 "Add text properties for bracketed links."
6173 (when (and (re-search-forward org-bracket-link-regexp limit t)
6174 (not (org-in-src-block-p)))
6175 (let* ((hl (save-match-data
6176 (org-link-expand-abbrev (match-string-no-properties 1))))
6177 (type (save-match-data
6178 (and (string-match org-plain-link-re hl)
6179 (match-string-no-properties 1 hl))))
6180 (path (save-match-data
6181 (and (string-match org-plain-link-re hl)
6182 (match-string-no-properties 2 hl))))
6183 (link-start (match-beginning 0))
6184 (link-end (match-end 0))
6185 (bracketp t)
6186 (help-echo (org-link-get-parameter type :help-echo))
6187 (help (cond
6188 ((stringp help-echo)
6189 help-echo)
6190 ((functionp help-echo)
6191 help-echo)
6193 (concat "LINK: "
6194 (save-match-data
6195 (org-link-unescape hl))))))
6196 (link-face (org-link-get-parameter type :face))
6197 (face (cond
6198 ;; A function that returns a face
6199 ((functionp link-face)
6200 (funcall link-face path))
6201 ;; a face
6202 ((facep link-face)
6203 link-face)
6204 ;; An anonymous face
6205 ((consp link-face)
6206 link-face)
6207 ;; default
6209 'org-link)))
6210 (keymap (or (org-link-get-parameter type :keymap)
6211 org-mouse-map))
6212 (mouse-face (or (org-link-get-parameter type :mouse-face)
6213 'highlight))
6214 (htmlize (org-link-get-parameter type :htmlize-link))
6215 (htmlize-link (cond
6216 ((functionp htmlize)
6217 (funcall htmlize))
6219 `(:uri ,(format "%s:%s" type path)))))
6220 (activate-func (org-link-get-parameter type :activate-func))
6221 ;; invisible part
6222 (ip (list 'invisible (or
6223 (org-link-get-parameter type :display)
6224 'org-link)
6225 'face face
6226 'keymap keymap
6227 'mouse-face mouse-face
6228 'font-lock-multiline t
6229 'help-echo help
6230 'htmlize-link htmlize-link))
6231 ;; visible part
6232 (vp (list 'keymap keymap
6233 'face face
6234 'mouse-face mouse-face
6235 'font-lock-multiline t
6236 'help-echo help
6237 'htmlize-link htmlize-link)))
6238 ;; We need to remove the invisible property here. Table narrowing
6239 ;; may have made some of this invisible.
6240 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6241 (remove-text-properties (match-beginning 0) (match-end 0)
6242 '(invisible nil))
6243 (if (match-end 3)
6244 (progn
6245 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6246 (org-rear-nonsticky-at (match-beginning 3))
6247 (add-text-properties (match-beginning 3) (match-end 3) vp)
6248 (org-rear-nonsticky-at (match-end 3))
6249 (add-text-properties (match-end 3) (match-end 0) ip)
6250 (org-rear-nonsticky-at (match-end 0)))
6251 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6252 (org-rear-nonsticky-at (match-beginning 1))
6253 (add-text-properties (match-beginning 1) (match-end 1) vp)
6254 (org-rear-nonsticky-at (match-end 1))
6255 (add-text-properties (match-end 1) (match-end 0) ip)
6256 (org-rear-nonsticky-at (match-end 0)))
6257 (when activate-func
6258 (funcall activate-func link-start link-end path bracketp))
6259 t)))
6261 (defun org-activate-dates (limit)
6262 "Add text properties for dates."
6263 (when (and (re-search-forward org-tsr-regexp-both limit t)
6264 (not (equal (char-before (match-beginning 0)) 91)))
6265 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6266 (add-text-properties (match-beginning 0) (match-end 0)
6267 (list 'mouse-face 'highlight
6268 'keymap org-mouse-map))
6269 (org-rear-nonsticky-at (match-end 0))
6270 (when org-display-custom-times
6271 (if (match-end 3)
6272 (org-display-custom-time (match-beginning 3) (match-end 3))
6273 (org-display-custom-time (match-beginning 1) (match-end 1))))
6276 (defvar-local org-target-link-regexp nil
6277 "Regular expression matching radio targets in plain text.")
6279 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6280 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6281 border border border))
6282 "Regular expression matching a link target.")
6284 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6285 "Regular expression matching a radio target.")
6287 (defconst org-any-target-regexp
6288 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6289 "Regular expression matching any target.")
6291 (defun org-activate-target-links (limit)
6292 "Add text properties for target matches."
6293 (when org-target-link-regexp
6294 (let ((case-fold-search t))
6295 (when (re-search-forward org-target-link-regexp limit t)
6296 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6297 (add-text-properties (match-beginning 1) (match-end 1)
6298 (list 'mouse-face 'highlight
6299 'keymap org-mouse-map
6300 'help-echo "Radio target link"
6301 'org-linked-text t))
6302 (org-rear-nonsticky-at (match-end 1))
6303 t))))
6305 (defun org-update-radio-target-regexp ()
6306 "Find all radio targets in this file and update the regular expression.
6307 Also refresh fontification if needed."
6308 (interactive)
6309 (let ((old-regexp org-target-link-regexp)
6310 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6311 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6312 (targets
6313 (org-with-wide-buffer
6314 (goto-char (point-min))
6315 (let (rtn)
6316 (while (re-search-forward org-radio-target-regexp nil t)
6317 ;; Make sure point is really within the object.
6318 (backward-char)
6319 (let ((obj (org-element-context)))
6320 (when (eq (org-element-type obj) 'radio-target)
6321 (cl-pushnew (org-element-property :value obj) rtn
6322 :test #'equal))))
6323 rtn))))
6324 (setq org-target-link-regexp
6325 (and targets
6326 (concat before-re
6327 (mapconcat
6328 (lambda (x)
6329 (replace-regexp-in-string
6330 " +" "\\s-+" (regexp-quote x) t t))
6331 targets
6332 "\\|")
6333 after-re)))
6334 (unless (equal old-regexp org-target-link-regexp)
6335 ;; Clean-up cache.
6336 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6337 ((not org-target-link-regexp) old-regexp)
6339 (concat before-re
6340 (mapconcat
6341 (lambda (re)
6342 (substring re (length before-re)
6343 (- (length after-re))))
6344 (list old-regexp org-target-link-regexp)
6345 "\\|")
6346 after-re)))))
6347 (org-with-wide-buffer
6348 (goto-char (point-min))
6349 (while (re-search-forward regexp nil t)
6350 (org-element-cache-refresh (match-beginning 1)))))
6351 ;; Re fontify buffer.
6352 (when (memq 'radio org-highlight-links)
6353 (org-restart-font-lock)))))
6355 (defun org-hide-wide-columns (limit)
6356 (let (s e)
6357 (setq s (text-property-any (point) (or limit (point-max))
6358 'org-cwidth t))
6359 (when s
6360 (setq e (next-single-property-change s 'org-cwidth))
6361 (add-text-properties s e '(invisible org-cwidth))
6362 (goto-char e)
6363 t)))
6365 (defvar org-latex-and-related-regexp nil
6366 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6368 (defun org-compute-latex-and-related-regexp ()
6369 "Compute regular expression for LaTeX, entities and sub/superscript.
6370 Result depends on variable `org-highlight-latex-and-related'."
6371 (setq-local
6372 org-latex-and-related-regexp
6373 (let* ((re-sub
6374 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6375 ((eq org-use-sub-superscripts '{})
6376 (list org-match-substring-with-braces-regexp))
6377 (org-use-sub-superscripts (list org-match-substring-regexp))))
6378 (re-latex
6379 (when (memq 'latex org-highlight-latex-and-related)
6380 (let ((matchers (plist-get org-format-latex-options :matchers)))
6381 (delq nil
6382 (mapcar (lambda (x)
6383 (and (member (car x) matchers) (nth 1 x)))
6384 org-latex-regexps)))))
6385 (re-entities
6386 (when (memq 'entities org-highlight-latex-and-related)
6387 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6388 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6390 (defun org-do-latex-and-related (limit)
6391 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6392 LIMIT bounds the search for syntax to highlight. Stop at first
6393 highlighted object, if any. Return t if some highlighting was
6394 done, nil otherwise."
6395 (when (org-string-nw-p org-latex-and-related-regexp)
6396 (catch 'found
6397 (while (re-search-forward org-latex-and-related-regexp limit t)
6398 (unless
6399 (cl-some
6400 (lambda (f)
6401 (memq f '(org-code org-verbatim underline org-special-keyword)))
6402 (save-excursion
6403 (goto-char (1+ (match-beginning 0)))
6404 (face-at-point nil t)))
6405 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6406 '(?_ ?^))
6408 0)))
6409 (font-lock-prepend-text-property
6410 (+ offset (match-beginning 0)) (match-end 0)
6411 'face 'org-latex-and-related)
6412 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6413 '(font-lock-multiline t)))
6414 (throw 'found t)))
6415 nil)))
6417 (defun org-restart-font-lock ()
6418 "Restart `font-lock-mode', to force refontification."
6419 (when (and (boundp 'font-lock-mode) font-lock-mode)
6420 (font-lock-mode -1)
6421 (font-lock-mode 1)))
6423 (defun org-activate-tags (limit)
6424 (when (re-search-forward
6425 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6426 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6427 (add-text-properties (match-beginning 1) (match-end 1)
6428 (list 'mouse-face 'highlight
6429 'keymap org-mouse-map))
6430 (org-rear-nonsticky-at (match-end 1))
6433 (defun org-outline-level ()
6434 "Compute the outline level of the heading at point.
6436 If this is called at a normal headline, the level is the number
6437 of stars. Use `org-reduced-level' to remove the effect of
6438 `org-odd-levels'. Unlike to `org-current-level', this function
6439 takes into consideration inlinetasks."
6440 (org-with-wide-buffer
6441 (end-of-line)
6442 (if (re-search-backward org-outline-regexp-bol nil t)
6443 (1- (- (match-end 0) (match-beginning 0)))
6444 0)))
6446 (defvar org-font-lock-keywords nil)
6448 (defsubst org-re-property (property &optional literal allow-null value)
6449 "Return a regexp matching a PROPERTY line.
6451 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6452 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6453 non-nil, match properties even without a value.
6455 Match group 3 is set to the value when it exists. If there is no
6456 value and ALLOW-NULL is non-nil, it is set to the empty string.
6458 With optional argument VALUE, match only property lines with
6459 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6460 unless LITERAL is non-nil."
6461 (concat
6462 "^\\(?4:[ \t]*\\)"
6463 (format "\\(?1::\\(?2:%s\\):\\)"
6464 (if literal property (regexp-quote property)))
6465 (cond (value
6466 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6467 (if literal value (regexp-quote value))))
6468 (allow-null
6469 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6471 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6473 (defconst org-property-re
6474 (org-re-property "\\S-+" 'literal t)
6475 "Regular expression matching a property line.
6476 There are four matching groups:
6477 1: :PROPKEY: including the leading and trailing colon,
6478 2: PROPKEY without the leading and trailing colon,
6479 3: PROPVAL without leading or trailing spaces,
6480 4: the indentation of the current line,
6481 5: trailing whitespace.")
6483 (defvar org-font-lock-hook nil
6484 "Functions to be called for special font lock stuff.")
6486 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6488 (defvar org-font-lock-set-keywords-hook nil
6489 "Functions that can manipulate `org-font-lock-extra-keywords'.
6490 This is called after `org-font-lock-extra-keywords' is defined, but before
6491 it is installed to be used by font lock. This can be useful if something
6492 needs to be inserted at a specific position in the font-lock sequence.")
6494 (defun org-font-lock-hook (limit)
6495 "Run `org-font-lock-hook' within LIMIT."
6496 (run-hook-with-args 'org-font-lock-hook limit))
6498 (defun org-set-font-lock-defaults ()
6499 "Set font lock defaults for the current buffer."
6500 (let* ((em org-fontify-emphasized-text)
6501 (lk org-highlight-links)
6502 (org-font-lock-extra-keywords
6503 (list
6504 ;; Call the hook
6505 '(org-font-lock-hook)
6506 ;; Headlines
6507 `(,(if org-fontify-whole-heading-line
6508 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6509 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6510 (1 (org-get-level-face 1))
6511 (2 (org-get-level-face 2))
6512 (3 (org-get-level-face 3)))
6513 ;; Table lines
6514 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6515 (1 'org-table t))
6516 ;; Table internals
6517 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6518 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6519 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6520 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6521 ;; Drawers
6522 '(org-fontify-drawers)
6523 ;; Properties
6524 (list org-property-re
6525 '(1 'org-special-keyword t)
6526 '(3 'org-property-value t))
6527 ;; Links
6528 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6529 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6530 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6531 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6532 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6533 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6534 (when (memq 'footnote lk) '(org-activate-footnote-links))
6535 ;; Targets.
6536 (list org-any-target-regexp '(0 'org-target t))
6537 ;; Diary sexps.
6538 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6539 ;; Macro
6540 '(org-fontify-macros)
6541 '(org-hide-wide-columns (0 nil append))
6542 ;; TODO keyword
6543 (list (format org-heading-keyword-regexp-format
6544 org-todo-regexp)
6545 '(2 (org-get-todo-face 2) t))
6546 ;; DONE
6547 (if org-fontify-done-headline
6548 (list (format org-heading-keyword-regexp-format
6549 (concat
6550 "\\(?:"
6551 (mapconcat 'regexp-quote org-done-keywords "\\|")
6552 "\\)"))
6553 '(2 'org-headline-done t))
6554 nil)
6555 ;; Priorities
6556 '(org-font-lock-add-priority-faces)
6557 ;; Tags
6558 '(org-font-lock-add-tag-faces)
6559 ;; Tags groups
6560 (when (and org-group-tags org-tag-groups-alist)
6561 (list (concat org-outline-regexp-bol ".+\\(:"
6562 (regexp-opt (mapcar 'car org-tag-groups-alist))
6563 ":\\).*$")
6564 '(1 'org-tag-group prepend)))
6565 ;; Special keywords
6566 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6567 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6568 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6569 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6570 ;; Emphasis
6571 (when em '(org-do-emphasis-faces))
6572 ;; Checkboxes
6573 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6574 1 'org-checkbox prepend)
6575 (when (cdr (assq 'checkbox org-list-automatic-rules))
6576 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6577 (0 (org-get-checkbox-statistics-face) t)))
6578 ;; Description list items
6579 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6580 1 'org-list-dt prepend)
6581 ;; ARCHIVEd headings
6582 (list (concat
6583 org-outline-regexp-bol
6584 "\\(.*:" org-archive-tag ":.*\\)")
6585 '(1 'org-archived prepend))
6586 ;; Specials
6587 '(org-do-latex-and-related)
6588 '(org-fontify-entities)
6589 '(org-raise-scripts)
6590 ;; Code
6591 '(org-activate-code (1 'org-code t))
6592 ;; COMMENT
6593 (list (format
6594 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6595 org-todo-regexp
6596 org-comment-string)
6597 '(9 'org-special-keyword t))
6598 ;; Blocks and meta lines
6599 '(org-fontify-meta-lines-and-blocks))))
6600 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6601 (run-hooks 'org-font-lock-set-keywords-hook)
6602 ;; Now set the full font-lock-keywords
6603 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6604 (setq-local font-lock-defaults
6605 '(org-font-lock-keywords t nil nil backward-paragraph))
6606 (kill-local-variable 'font-lock-keywords)
6607 nil))
6609 (defun org-toggle-pretty-entities ()
6610 "Toggle the composition display of entities as UTF8 characters."
6611 (interactive)
6612 (setq-local org-pretty-entities (not org-pretty-entities))
6613 (org-restart-font-lock)
6614 (if org-pretty-entities
6615 (message "Entities are now displayed as UTF8 characters")
6616 (save-restriction
6617 (widen)
6618 (decompose-region (point-min) (point-max))
6619 (message "Entities are now displayed as plain text"))))
6621 (defvar-local org-custom-properties-overlays nil
6622 "List of overlays used for custom properties.")
6624 (defun org-toggle-custom-properties-visibility ()
6625 "Display or hide properties in `org-custom-properties'."
6626 (interactive)
6627 (if org-custom-properties-overlays
6628 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6629 (setq org-custom-properties-overlays nil))
6630 (when org-custom-properties
6631 (org-with-wide-buffer
6632 (goto-char (point-min))
6633 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6634 (while (re-search-forward regexp nil t)
6635 (let ((end (cdr (save-match-data (org-get-property-block)))))
6636 (when (and end (< (point) end))
6637 ;; Hide first custom property in current drawer.
6638 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6639 (overlay-put o 'invisible t)
6640 (overlay-put o 'org-custom-property t)
6641 (push o org-custom-properties-overlays))
6642 ;; Hide additional custom properties in the same drawer.
6643 (while (re-search-forward regexp end t)
6644 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6645 (overlay-put o 'invisible t)
6646 (overlay-put o 'org-custom-property t)
6647 (push o org-custom-properties-overlays)))))
6648 ;; Each entry is limited to a single property drawer.
6649 (outline-next-heading)))))))
6651 (defun org-fontify-entities (limit)
6652 "Find an entity to fontify."
6653 (let (ee)
6654 (when org-pretty-entities
6655 (catch 'match
6656 ;; "\_ "-family is left out on purpose. Only the first one,
6657 ;; i.e., "\_ ", could be fontified anyway, and it would be
6658 ;; confusing when adding a second white space character.
6659 (while (re-search-forward
6660 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6661 limit t)
6662 (when (and (not (org-at-comment-p))
6663 (setq ee (org-entity-get (match-string 1)))
6664 (= (length (nth 6 ee)) 1))
6665 (let* ((end (if (equal (match-string 2) "{}")
6666 (match-end 2)
6667 (match-end 1))))
6668 (add-text-properties
6669 (match-beginning 0) end
6670 (list 'font-lock-fontified t))
6671 (compose-region (match-beginning 0) end
6672 (nth 6 ee) nil)
6673 (backward-char 1)
6674 (throw 'match t))))
6675 nil))))
6677 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6678 "Fontify string S like in Org mode."
6679 (with-temp-buffer
6680 (insert s)
6681 (let ((org-odd-levels-only odd-levels))
6682 (org-mode)
6683 (org-font-lock-ensure)
6684 (buffer-string))))
6686 (defvar org-m nil)
6687 (defvar org-l nil)
6688 (defvar org-f nil)
6689 (defun org-get-level-face (n)
6690 "Get the right face for match N in font-lock matching of headlines."
6691 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6692 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6693 (if org-cycle-level-faces
6694 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6695 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6696 (cond
6697 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6698 ((eq n 2) org-f)
6699 (t (unless org-level-color-stars-only org-f))))
6701 (defun org-face-from-face-or-color (context inherit face-or-color)
6702 "Create a face list that inherits INHERIT, but sets the foreground color.
6703 When FACE-OR-COLOR is not a string, just return it."
6704 (if (stringp face-or-color)
6705 (list :inherit inherit
6706 (cdr (assoc context org-faces-easy-properties))
6707 face-or-color)
6708 face-or-color))
6710 (defun org-get-todo-face (kwd)
6711 "Get the right face for a TODO keyword KWD.
6712 If KWD is a number, get the corresponding match group."
6713 (when (numberp kwd) (setq kwd (match-string kwd)))
6714 (or (org-face-from-face-or-color
6715 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6716 (and (member kwd org-done-keywords) 'org-done)
6717 'org-todo))
6719 (defun org-get-priority-face (priority)
6720 "Get the right face for PRIORITY.
6721 PRIORITY is a character."
6722 (or (org-face-from-face-or-color
6723 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6724 'org-priority))
6726 (defun org-get-tag-face (tag)
6727 "Get the right face for TAG.
6728 If TAG is a number, get the corresponding match group."
6729 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6730 (or (org-face-from-face-or-color
6731 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6732 'org-tag)))
6734 (defun org-font-lock-add-priority-faces (limit)
6735 "Add the special priority faces."
6736 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6737 (add-text-properties
6738 (match-beginning 1) (match-end 1)
6739 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6740 'font-lock-fontified t))))
6742 (defun org-font-lock-add-tag-faces (limit)
6743 "Add the special tag faces."
6744 (when (and org-tag-faces org-tags-special-faces-re)
6745 (while (re-search-forward org-tags-special-faces-re limit t)
6746 (add-text-properties (match-beginning 1) (match-end 1)
6747 (list 'face (org-get-tag-face 1)
6748 'font-lock-fontified t))
6749 (backward-char 1))))
6751 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6752 "Remove fontification and activation overlays from links."
6753 (font-lock-default-unfontify-region beg end)
6754 (let* ((buffer-undo-list t)
6755 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6756 (inhibit-modification-hooks t)
6757 deactivate-mark buffer-file-name buffer-file-truename)
6758 (decompose-region beg end)
6759 (remove-text-properties beg end
6760 '(mouse-face t keymap t org-linked-text t
6761 invisible t intangible t
6762 org-emphasis t))
6763 (org-remove-font-lock-display-properties beg end)))
6765 (defconst org-script-display '(((raise -0.3) (height 0.7))
6766 ((raise 0.3) (height 0.7))
6767 ((raise -0.5))
6768 ((raise 0.5)))
6769 "Display properties for showing superscripts and subscripts.")
6771 (defun org-remove-font-lock-display-properties (beg end)
6772 "Remove specific display properties that have been added by font lock.
6773 The will remove the raise properties that are used to show superscripts
6774 and subscripts."
6775 (let (next prop)
6776 (while (< beg end)
6777 (setq next (next-single-property-change beg 'display nil end)
6778 prop (get-text-property beg 'display))
6779 (when (member prop org-script-display)
6780 (put-text-property beg next 'display nil))
6781 (setq beg next))))
6783 (defun org-raise-scripts (limit)
6784 "Add raise properties to sub/superscripts."
6785 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6786 (re-search-forward
6787 (if (eq org-use-sub-superscripts t)
6788 org-match-substring-regexp
6789 org-match-substring-with-braces-regexp)
6790 limit t))
6791 (let* ((pos (point)) table-p comment-p
6792 (mpos (match-beginning 3))
6793 (emph-p (get-text-property mpos 'org-emphasis))
6794 (link-p (get-text-property mpos 'mouse-face))
6795 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6796 (goto-char (point-at-bol))
6797 (setq table-p (looking-at-p org-table-dataline-regexp)
6798 comment-p (looking-at-p "^[ \t]*#[ +]"))
6799 (goto-char pos)
6800 ;; Handle a_b^c
6801 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6802 (unless (or comment-p emph-p link-p keyw-p)
6803 (put-text-property (match-beginning 3) (match-end 0)
6804 'display
6805 (if (equal (char-after (match-beginning 2)) ?^)
6806 (nth (if table-p 3 1) org-script-display)
6807 (nth (if table-p 2 0) org-script-display)))
6808 (add-text-properties (match-beginning 2) (match-end 2)
6809 (list 'invisible t
6810 'org-dwidth t 'org-dwidth-n 1))
6811 (if (and (eq (char-after (match-beginning 3)) ?{)
6812 (eq (char-before (match-end 3)) ?}))
6813 (progn
6814 (add-text-properties
6815 (match-beginning 3) (1+ (match-beginning 3))
6816 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6817 (add-text-properties
6818 (1- (match-end 3)) (match-end 3)
6819 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6820 t)))
6822 ;;;; Visibility cycling, including org-goto and indirect buffer
6824 ;;; Cycling
6826 (defvar-local org-cycle-global-status nil)
6827 (put 'org-cycle-global-status 'org-state t)
6828 (defvar-local org-cycle-subtree-status nil)
6829 (put 'org-cycle-subtree-status 'org-state t)
6831 (defvar org-inlinetask-min-level)
6833 (defun org-unlogged-message (&rest args)
6834 "Display a message, but avoid logging it in the *Messages* buffer."
6835 (let ((message-log-max nil))
6836 (apply 'message args)))
6838 ;;;###autoload
6839 (defun org-cycle (&optional arg)
6840 "TAB-action and visibility cycling for Org mode.
6842 This is the command invoked in Org mode by the `TAB' key. Its main
6843 purpose is outline visibility cycling, but it also invokes other actions
6844 in special contexts.
6846 When this function is called with a `\\[universal-argument]' prefix, rotate \
6847 the entire
6848 buffer through 3 states (global cycling)
6849 1. OVERVIEW: Show only top-level headlines.
6850 2. CONTENTS: Show all headlines of all levels, but no body text.
6851 3. SHOW ALL: Show everything.
6853 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6854 switch to the startup visibility,
6855 determined by the variable `org-startup-folded', and by any VISIBILITY
6856 properties in the buffer.
6858 With a `\\[universal-argument] \\[universal-argument] \
6859 \\[universal-argument]' prefix argument, show the entire buffer, including
6860 any drawers.
6862 When inside a table, re-align the table and move to the next field.
6864 When point is at the beginning of a headline, rotate the subtree started
6865 by this line through 3 different states (local cycling)
6866 1. FOLDED: Only the main headline is shown.
6867 2. CHILDREN: The main headline and the direct children are shown.
6868 From this state, you can move to one of the children
6869 and zoom in further.
6870 3. SUBTREE: Show the entire subtree, including body text.
6871 If there is no subtree, switch directly from CHILDREN to FOLDED.
6873 When point is at the beginning of an empty headline and the variable
6874 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6875 of the headline by demoting and promoting it to likely levels. This
6876 speeds up creation document structure by pressing `TAB' once or several
6877 times right after creating a new headline.
6879 When there is a numeric prefix, go up to a heading with level ARG, do
6880 a `show-subtree' and return to the previous cursor position. If ARG
6881 is negative, go up that many levels.
6883 When point is not at the beginning of a headline, execute the global
6884 binding for `TAB', which is re-indenting the line. See the option
6885 `org-cycle-emulate-tab' for details.
6887 As a special case, if point is at the beginning of the buffer and there is
6888 no headline in line 1, this function will act as if called with prefix arg
6889 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6890 prefix arg, but only
6891 if the variable `org-cycle-global-at-bob' is t."
6892 (interactive "P")
6893 (org-load-modules-maybe)
6894 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6895 (and org-cycle-level-after-item/entry-creation
6896 (or (org-cycle-level)
6897 (org-cycle-item-indentation))))
6898 (let* ((limit-level
6899 (or org-cycle-max-level
6900 (and (boundp 'org-inlinetask-min-level)
6901 org-inlinetask-min-level
6902 (1- org-inlinetask-min-level))))
6903 (nstars (and limit-level
6904 (if org-odd-levels-only
6905 (and limit-level (1- (* limit-level 2)))
6906 limit-level)))
6907 (org-outline-regexp
6908 (if (not (derived-mode-p 'org-mode))
6909 outline-regexp
6910 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6911 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6912 (not (looking-at org-outline-regexp))))
6913 (org-cycle-hook
6914 (if bob-special
6915 (delq 'org-optimize-window-after-visibility-change
6916 (copy-sequence org-cycle-hook))
6917 org-cycle-hook))
6918 (pos (point)))
6920 (cond
6922 ((equal arg '(16))
6923 (setq last-command 'dummy)
6924 (org-set-startup-visibility)
6925 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6927 ((equal arg '(64))
6928 (outline-show-all)
6929 (org-unlogged-message "Entire buffer visible, including drawers"))
6931 ((equal arg '(4)) (org-cycle-internal-global))
6933 ;; Try hiding block at point.
6934 ((org-hide-block-toggle-maybe))
6936 ;; Try cdlatex TAB completion
6937 ((org-try-cdlatex-tab))
6939 ;; Table: enter it or move to the next field.
6940 ((org-at-table-p 'any)
6941 (if (org-at-table.el-p)
6942 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6943 Use `\\[org-edit-special]' to edit table.el tables"))
6944 (if arg (org-table-edit-field t)
6945 (org-table-justify-field-maybe)
6946 (call-interactively 'org-table-next-field))))
6948 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6950 ;; Global cycling: delegate to `org-cycle-internal-global'.
6951 (bob-special (org-cycle-internal-global))
6953 ;; Drawers: delegate to `org-flag-drawer'.
6954 ((save-excursion
6955 (beginning-of-line 1)
6956 (looking-at org-drawer-regexp))
6957 (org-flag-drawer ; toggle block visibility
6958 (not (get-char-property (match-end 0) 'invisible))))
6960 ;; Show-subtree, ARG levels up from here.
6961 ((integerp arg)
6962 (save-excursion
6963 (org-back-to-heading)
6964 (outline-up-heading (if (< arg 0) (- arg)
6965 (- (funcall outline-level) arg)))
6966 (org-show-subtree)))
6968 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6969 ((and (featurep 'org-inlinetask)
6970 (org-inlinetask-at-task-p)
6971 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6972 (org-inlinetask-toggle-visibility))
6974 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6975 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6976 (save-excursion (move-beginning-of-line 1)
6977 (looking-at org-outline-regexp)))
6978 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6979 (org-cycle-internal-local))
6981 ;; From there: TAB emulation and template completion.
6982 (buffer-read-only (org-back-to-heading))
6984 ((run-hook-with-args-until-success
6985 'org-tab-after-check-for-cycling-hook))
6987 ((org-try-structure-completion))
6989 ((run-hook-with-args-until-success
6990 'org-tab-before-tab-emulation-hook))
6992 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6993 (or (not (bolp))
6994 (not (looking-at org-outline-regexp))))
6995 (call-interactively (global-key-binding "\t")))
6997 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6998 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6999 (or (and (eq org-cycle-emulate-tab 'white)
7000 (= (match-end 0) (point-at-eol)))
7001 (and (eq org-cycle-emulate-tab 'whitestart)
7002 (>= (match-end 0) pos))))
7004 (eq org-cycle-emulate-tab t))
7005 (call-interactively (global-key-binding "\t")))
7007 (t (save-excursion
7008 (org-back-to-heading)
7009 (org-cycle)))))))
7011 (defun org-cycle-internal-global ()
7012 "Do the global cycling action."
7013 ;; Hack to avoid display of messages for .org attachments in Gnus
7014 (let ((ga (string-match "\\*fontification" (buffer-name))))
7015 (cond
7016 ((and (eq last-command this-command)
7017 (eq org-cycle-global-status 'overview))
7018 ;; We just created the overview - now do table of contents
7019 ;; This can be slow in very large buffers, so indicate action
7020 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7021 (unless ga (org-unlogged-message "CONTENTS..."))
7022 (org-content)
7023 (unless ga (org-unlogged-message "CONTENTS...done"))
7024 (setq org-cycle-global-status 'contents)
7025 (run-hook-with-args 'org-cycle-hook 'contents))
7027 ((and (eq last-command this-command)
7028 (eq org-cycle-global-status 'contents))
7029 ;; We just showed the table of contents - now show everything
7030 (run-hook-with-args 'org-pre-cycle-hook 'all)
7031 (outline-show-all)
7032 (unless ga (org-unlogged-message "SHOW ALL"))
7033 (setq org-cycle-global-status 'all)
7034 (run-hook-with-args 'org-cycle-hook 'all))
7037 ;; Default action: go to overview
7038 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7039 (org-overview)
7040 (unless ga (org-unlogged-message "OVERVIEW"))
7041 (setq org-cycle-global-status 'overview)
7042 (run-hook-with-args 'org-cycle-hook 'overview)))))
7044 (defvar org-called-with-limited-levels nil
7045 "Non-nil when `org-with-limited-levels' is currently active.")
7047 (defun org-cycle-internal-local ()
7048 "Do the local cycling action."
7049 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7050 ;; First, determine end of headline (EOH), end of subtree or item
7051 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7052 (save-excursion
7053 (if (org-at-item-p)
7054 (progn
7055 (beginning-of-line)
7056 (setq struct (org-list-struct))
7057 (setq eoh (point-at-eol))
7058 (setq eos (org-list-get-item-end-before-blank (point) struct))
7059 (setq has-children (org-list-has-child-p (point) struct)))
7060 (org-back-to-heading)
7061 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7062 (setq eos (save-excursion (org-end-of-subtree t t)
7063 (when (bolp) (backward-char)) (point)))
7064 (setq has-children
7065 (or (save-excursion
7066 (let ((level (funcall outline-level)))
7067 (outline-next-heading)
7068 (and (org-at-heading-p t)
7069 (> (funcall outline-level) level))))
7070 (save-excursion
7071 (org-list-search-forward (org-item-beginning-re) eos t)))))
7072 ;; Determine end invisible part of buffer (EOL)
7073 (beginning-of-line 2)
7074 (while (and (not (eobp)) ;This is like `next-line'.
7075 (get-char-property (1- (point)) 'invisible))
7076 (goto-char (next-single-char-property-change (point) 'invisible))
7077 (and (eolp) (beginning-of-line 2)))
7078 (setq eol (point)))
7079 ;; Find out what to do next and set `this-command'
7080 (cond
7081 ((= eos eoh)
7082 ;; Nothing is hidden behind this heading
7083 (unless (org-before-first-heading-p)
7084 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7085 (org-unlogged-message "EMPTY ENTRY")
7086 (setq org-cycle-subtree-status nil)
7087 (save-excursion
7088 (goto-char eos)
7089 (outline-next-heading)
7090 (when (outline-invisible-p) (org-flag-heading nil))))
7091 ((and (or (>= eol eos)
7092 (not (string-match "\\S-" (buffer-substring eol eos))))
7093 (or has-children
7094 (not (setq children-skipped
7095 org-cycle-skip-children-state-if-no-children))))
7096 ;; Entire subtree is hidden in one line: children view
7097 (unless (org-before-first-heading-p)
7098 (run-hook-with-args 'org-pre-cycle-hook 'children))
7099 (if (org-at-item-p)
7100 (org-list-set-item-visibility (point-at-bol) struct 'children)
7101 (org-show-entry)
7102 (org-with-limited-levels (org-show-children))
7103 ;; FIXME: This slows down the func way too much.
7104 ;; How keep drawers hidden in subtree anyway?
7105 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7106 ;; (org-cycle-hide-drawers 'subtree))
7108 ;; Fold every list in subtree to top-level items.
7109 (when (eq org-cycle-include-plain-lists 'integrate)
7110 (save-excursion
7111 (org-back-to-heading)
7112 (while (org-list-search-forward (org-item-beginning-re) eos t)
7113 (beginning-of-line 1)
7114 (let* ((struct (org-list-struct))
7115 (prevs (org-list-prevs-alist struct))
7116 (end (org-list-get-bottom-point struct)))
7117 (dolist (e (org-list-get-all-items (point) struct prevs))
7118 (org-list-set-item-visibility e struct 'folded))
7119 (goto-char (if (< end eos) end eos)))))))
7120 (org-unlogged-message "CHILDREN")
7121 (save-excursion
7122 (goto-char eos)
7123 (outline-next-heading)
7124 (when (outline-invisible-p) (org-flag-heading nil)))
7125 (setq org-cycle-subtree-status 'children)
7126 (unless (org-before-first-heading-p)
7127 (run-hook-with-args 'org-cycle-hook 'children)))
7128 ((or children-skipped
7129 (and (eq last-command this-command)
7130 (eq org-cycle-subtree-status 'children)))
7131 ;; We just showed the children, or no children are there,
7132 ;; now show everything.
7133 (unless (org-before-first-heading-p)
7134 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7135 (outline-flag-region eoh eos nil)
7136 (org-unlogged-message
7137 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7138 (setq org-cycle-subtree-status 'subtree)
7139 (unless (org-before-first-heading-p)
7140 (run-hook-with-args 'org-cycle-hook 'subtree)))
7142 ;; Default action: hide the subtree.
7143 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7144 (outline-flag-region eoh eos t)
7145 (org-unlogged-message "FOLDED")
7146 (setq org-cycle-subtree-status 'folded)
7147 (unless (org-before-first-heading-p)
7148 (run-hook-with-args 'org-cycle-hook 'folded))))))
7150 ;;;###autoload
7151 (defun org-global-cycle (&optional arg)
7152 "Cycle the global visibility. For details see `org-cycle'.
7153 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7154 With a numeric prefix, show all headlines up to that level."
7155 (interactive "P")
7156 (let ((org-cycle-include-plain-lists
7157 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7158 (cond
7159 ((integerp arg)
7160 (outline-show-all)
7161 (outline-hide-sublevels arg)
7162 (setq org-cycle-global-status 'contents))
7163 ((equal arg '(4))
7164 (org-set-startup-visibility)
7165 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7167 (org-cycle '(4))))))
7169 (defun org-set-startup-visibility ()
7170 "Set the visibility required by startup options and properties."
7171 (cond
7172 ((eq org-startup-folded t)
7173 (org-overview))
7174 ((eq org-startup-folded 'content)
7175 (org-content))
7176 ((or (eq org-startup-folded 'showeverything)
7177 (eq org-startup-folded nil))
7178 (outline-show-all)))
7179 (unless (eq org-startup-folded 'showeverything)
7180 (when org-hide-block-startup (org-hide-block-all))
7181 (org-set-visibility-according-to-property 'no-cleanup)
7182 (org-cycle-hide-archived-subtrees 'all)
7183 (org-cycle-hide-drawers 'all)
7184 (org-cycle-show-empty-lines t)))
7186 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7187 "Switch subtree visibilities according to :VISIBILITY: property."
7188 (interactive)
7189 (org-with-wide-buffer
7190 (goto-char (point-min))
7191 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7192 (if (not (org-at-property-p)) (outline-next-heading)
7193 (let ((state (match-string 3)))
7194 (save-excursion
7195 (org-back-to-heading t)
7196 (outline-hide-subtree)
7197 (org-reveal)
7198 (cond
7199 ((equal state "folded")
7200 (outline-hide-subtree))
7201 ((equal state "children")
7202 (org-show-hidden-entry)
7203 (org-show-children))
7204 ((equal state "content")
7205 (save-excursion
7206 (save-restriction
7207 (org-narrow-to-subtree)
7208 (org-content))))
7209 ((member state '("all" "showall"))
7210 (outline-show-subtree)))))))
7211 (unless no-cleanup
7212 (org-cycle-hide-archived-subtrees 'all)
7213 (org-cycle-hide-drawers 'all)
7214 (org-cycle-show-empty-lines 'all))))
7216 ;; This function uses outline-regexp instead of the more fundamental
7217 ;; org-outline-regexp so that org-cycle-global works outside of Org
7218 ;; buffers, where outline-regexp is needed.
7219 (defun org-overview ()
7220 "Switch to overview mode, showing only top-level headlines.
7221 This shows all headlines with a level equal or greater than the level
7222 of the first headline in the buffer. This is important, because if the
7223 first headline is not level one, then (hide-sublevels 1) gives confusing
7224 results."
7225 (interactive)
7226 (save-excursion
7227 (let ((level
7228 (save-excursion
7229 (goto-char (point-min))
7230 (when (re-search-forward (concat "^" outline-regexp) nil t)
7231 (goto-char (match-beginning 0))
7232 (funcall outline-level)))))
7233 (and level (outline-hide-sublevels level)))))
7235 (defun org-content (&optional arg)
7236 "Show all headlines in the buffer, like a table of contents.
7237 With numerical argument N, show content up to level N."
7238 (interactive "P")
7239 (org-overview)
7240 (save-excursion
7241 ;; Visit all headings and show their offspring
7242 (and (integerp arg) (org-overview))
7243 (goto-char (point-max))
7244 (catch 'exit
7245 (while (and (progn (condition-case nil
7246 (outline-previous-visible-heading 1)
7247 (error (goto-char (point-min))))
7249 (looking-at org-outline-regexp))
7250 (if (integerp arg)
7251 (org-show-children (1- arg))
7252 (outline-show-branches))
7253 (when (bobp) (throw 'exit nil))))))
7255 (defun org-optimize-window-after-visibility-change (state)
7256 "Adjust the window after a change in outline visibility.
7257 This function is the default value of the hook `org-cycle-hook'."
7258 (when (get-buffer-window (current-buffer))
7259 (cond
7260 ((eq state 'content) nil)
7261 ((eq state 'all) nil)
7262 ((eq state 'folded) nil)
7263 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7264 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7266 (defun org-remove-empty-overlays-at (pos)
7267 "Remove outline overlays that do not contain non-white stuff."
7268 (dolist (o (overlays-at pos))
7269 (and (eq 'outline (overlay-get o 'invisible))
7270 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7271 (overlay-end o))))
7272 (delete-overlay o))))
7274 (defun org-clean-visibility-after-subtree-move ()
7275 "Fix visibility issues after moving a subtree."
7276 ;; First, find a reasonable region to look at:
7277 ;; Start two siblings above, end three below
7278 (let* ((beg (save-excursion
7279 (and (org-get-last-sibling)
7280 (org-get-last-sibling))
7281 (point)))
7282 (end (save-excursion
7283 (and (org-get-next-sibling)
7284 (org-get-next-sibling)
7285 (org-get-next-sibling))
7286 (if (org-at-heading-p)
7287 (point-at-eol)
7288 (point))))
7289 (level (looking-at "\\*+"))
7290 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7291 (save-excursion
7292 (save-restriction
7293 (narrow-to-region beg end)
7294 (when re
7295 ;; Properly fold already folded siblings
7296 (goto-char (point-min))
7297 (while (re-search-forward re nil t)
7298 (when (and (not (outline-invisible-p))
7299 (save-excursion
7300 (goto-char (point-at-eol)) (outline-invisible-p)))
7301 (outline-hide-entry))))
7302 (org-cycle-show-empty-lines 'overview)
7303 (org-cycle-hide-drawers 'overview)))))
7305 (defun org-cycle-show-empty-lines (state)
7306 "Show empty lines above all visible headlines.
7307 The region to be covered depends on STATE when called through
7308 `org-cycle-hook'. Lisp program can use t for STATE to get the
7309 entire buffer covered. Note that an empty line is only shown if there
7310 are at least `org-cycle-separator-lines' empty lines before the headline."
7311 (when (/= org-cycle-separator-lines 0)
7312 (save-excursion
7313 (let* ((n (abs org-cycle-separator-lines))
7314 (re (cond
7315 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7316 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7317 (t (let ((ns (number-to-string (- n 2))))
7318 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7319 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7320 beg end)
7321 (cond
7322 ((memq state '(overview contents t))
7323 (setq beg (point-min) end (point-max)))
7324 ((memq state '(children folded))
7325 (setq beg (point)
7326 end (progn (org-end-of-subtree t t)
7327 (line-beginning-position 2)))))
7328 (when beg
7329 (goto-char beg)
7330 (while (re-search-forward re end t)
7331 (unless (get-char-property (match-end 1) 'invisible)
7332 (let ((e (match-end 1))
7333 (b (if (>= org-cycle-separator-lines 0)
7334 (match-beginning 1)
7335 (save-excursion
7336 (goto-char (match-beginning 0))
7337 (skip-chars-backward " \t\n")
7338 (line-end-position)))))
7339 (outline-flag-region b e nil))))))))
7340 ;; Never hide empty lines at the end of the file.
7341 (save-excursion
7342 (goto-char (point-max))
7343 (outline-previous-heading)
7344 (outline-end-of-heading)
7345 (when (and (looking-at "[ \t\n]+")
7346 (= (match-end 0) (point-max)))
7347 (outline-flag-region (point) (match-end 0) nil))))
7349 (defun org-show-empty-lines-in-parent ()
7350 "Move to the parent and re-show empty lines before visible headlines."
7351 (save-excursion
7352 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7353 (org-cycle-show-empty-lines context))))
7355 (defun org-files-list ()
7356 "Return `org-agenda-files' list, plus all open Org files.
7357 This is useful for operations that need to scan all of a user's
7358 open and agenda-wise Org files."
7359 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7360 (dolist (buf (buffer-list))
7361 (with-current-buffer buf
7362 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7363 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7364 files))
7366 (defsubst org-entry-beginning-position ()
7367 "Return the beginning position of the current entry."
7368 (save-excursion (org-back-to-heading t) (point)))
7370 (defsubst org-entry-end-position ()
7371 "Return the end position of the current entry."
7372 (save-excursion (outline-next-heading) (point)))
7374 (defun org-cycle-hide-drawers (state &optional exceptions)
7375 "Re-hide all drawers after a visibility state change.
7376 When non-nil, optional argument EXCEPTIONS is a list of strings
7377 specifying which drawers should not be hidden."
7378 (when (and (derived-mode-p 'org-mode)
7379 (not (memq state '(overview folded contents))))
7380 (save-excursion
7381 (let* ((globalp (memq state '(contents all)))
7382 (beg (if globalp (point-min) (point)))
7383 (end (if globalp (point-max)
7384 (if (eq state 'children)
7385 (save-excursion (outline-next-heading) (point))
7386 (org-end-of-subtree t)))))
7387 (goto-char beg)
7388 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7389 (unless (member-ignore-case (match-string 1) exceptions)
7390 (let ((drawer (org-element-at-point)))
7391 (when (memq (org-element-type drawer) '(drawer property-drawer))
7392 (org-flag-drawer t drawer)
7393 ;; Make sure to skip drawer entirely or we might flag
7394 ;; it another time when matching its ending line with
7395 ;; `org-drawer-regexp'.
7396 (goto-char (org-element-property :end drawer))))))))))
7398 (defun org-flag-drawer (flag &optional element)
7399 "When FLAG is non-nil, hide the drawer we are at.
7400 Otherwise make it visible. When optional argument ELEMENT is
7401 a parsed drawer, as returned by `org-element-at-point', hide or
7402 show that drawer instead."
7403 (let ((drawer (or element
7404 (and (save-excursion
7405 (beginning-of-line)
7406 (looking-at-p org-drawer-regexp))
7407 (org-element-at-point)))))
7408 (when (memq (org-element-type drawer) '(drawer property-drawer))
7409 (let ((post (org-element-property :post-affiliated drawer)))
7410 (save-excursion
7411 (outline-flag-region
7412 (progn (goto-char post) (line-end-position))
7413 (progn (goto-char (org-element-property :end drawer))
7414 (skip-chars-backward " \r\t\n")
7415 (line-end-position))
7416 flag))
7417 ;; When the drawer is hidden away, make sure point lies in
7418 ;; a visible part of the buffer.
7419 (when (and flag (> (line-beginning-position) post))
7420 (goto-char post))))))
7422 (defun org-subtree-end-visible-p ()
7423 "Is the end of the current subtree visible?"
7424 (pos-visible-in-window-p
7425 (save-excursion (org-end-of-subtree t) (point))))
7427 (defun org-first-headline-recenter ()
7428 "Move cursor to the first headline and recenter the headline."
7429 (let ((window (get-buffer-window)))
7430 (when window
7431 (goto-char (point-min))
7432 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7433 (set-window-start window (line-beginning-position))))))
7435 ;;; Saving and restoring visibility
7437 (defun org-outline-overlay-data (&optional use-markers)
7438 "Return a list of the locations of all outline overlays.
7439 These are overlays with the `invisible' property value `outline'.
7440 The return value is a list of cons cells, with start and stop
7441 positions for each overlay.
7442 If USE-MARKERS is set, return the positions as markers."
7443 (let (beg end)
7444 (org-with-wide-buffer
7445 (delq nil
7446 (mapcar (lambda (o)
7447 (when (eq (overlay-get o 'invisible) 'outline)
7448 (setq beg (overlay-start o)
7449 end (overlay-end o))
7450 (and beg end (> end beg)
7451 (if use-markers
7452 (cons (copy-marker beg)
7453 (copy-marker end t))
7454 (cons beg end)))))
7455 (overlays-in (point-min) (point-max)))))))
7457 (defun org-set-outline-overlay-data (data)
7458 "Create visibility overlays for all positions in DATA.
7459 DATA should have been made by `org-outline-overlay-data'."
7460 (org-with-wide-buffer
7461 (outline-show-all)
7462 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7464 ;;; Folding of blocks
7466 (defvar-local org-hide-block-overlays nil
7467 "Overlays hiding blocks.")
7469 (defun org-block-map (function &optional start end)
7470 "Call FUNCTION at the head of all source blocks in the current buffer.
7471 Optional arguments START and END can be used to limit the range."
7472 (let ((start (or start (point-min)))
7473 (end (or end (point-max))))
7474 (save-excursion
7475 (goto-char start)
7476 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7477 (save-excursion
7478 (save-match-data
7479 (goto-char (match-beginning 0))
7480 (funcall function)))))))
7482 (defun org-hide-block-toggle-all ()
7483 "Toggle the visibility of all blocks in the current buffer."
7484 (org-block-map 'org-hide-block-toggle))
7486 (defun org-hide-block-all ()
7487 "Fold all blocks in the current buffer."
7488 (interactive)
7489 (org-show-block-all)
7490 (org-block-map 'org-hide-block-toggle-maybe))
7492 (defun org-show-block-all ()
7493 "Unfold all blocks in the current buffer."
7494 (interactive)
7495 (mapc #'delete-overlay org-hide-block-overlays)
7496 (setq org-hide-block-overlays nil))
7498 (defun org-hide-block-toggle-maybe ()
7499 "Toggle visibility of block at point.
7500 Unlike to `org-hide-block-toggle', this function does not throw
7501 an error. Return a non-nil value when toggling is successful."
7502 (interactive)
7503 (ignore-errors (org-hide-block-toggle)))
7505 (defun org-hide-block-toggle (&optional force)
7506 "Toggle the visibility of the current block.
7507 When optional argument FORCE is `off', make block visible. If it
7508 is non-nil, hide it unconditionally. Throw an error when not at
7509 a block. Return a non-nil value when toggling is successful."
7510 (interactive)
7511 (let ((element (org-element-at-point)))
7512 (unless (memq (org-element-type element)
7513 '(center-block comment-block dynamic-block example-block
7514 export-block quote-block special-block
7515 src-block verse-block))
7516 (user-error "Not at a block"))
7517 (let* ((start (save-excursion
7518 (goto-char (org-element-property :post-affiliated element))
7519 (line-end-position)))
7520 (end (save-excursion
7521 (goto-char (org-element-property :end element))
7522 (skip-chars-backward " \r\t\n")
7523 (line-end-position)))
7524 (overlays (overlays-at start)))
7525 (cond
7526 ;; Do nothing when not before or at the block opening line or
7527 ;; at the block closing line.
7528 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7529 ((and (not (eq force 'off))
7530 (not (memq t (mapcar
7531 (lambda (o)
7532 (eq (overlay-get o 'invisible) 'org-hide-block))
7533 overlays))))
7534 (let ((ov (make-overlay start end)))
7535 (overlay-put ov 'invisible 'org-hide-block)
7536 ;; Make the block accessible to `isearch'.
7537 (overlay-put
7538 ov 'isearch-open-invisible
7539 (lambda (ov)
7540 (when (memq ov org-hide-block-overlays)
7541 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7542 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7543 (delete-overlay ov))))
7544 (push ov org-hide-block-overlays)
7545 ;; When the block is hidden away, make sure point is left in
7546 ;; a visible part of the buffer.
7547 (when (> (line-beginning-position) start)
7548 (goto-char start)
7549 (beginning-of-line))
7550 ;; Signal successful toggling.
7552 ((or (not force) (eq force 'off))
7553 (dolist (ov overlays t)
7554 (when (memq ov org-hide-block-overlays)
7555 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7556 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7557 (delete-overlay ov))))))))
7559 ;; Remove overlays when changing major mode
7560 (add-hook 'org-mode-hook
7561 (lambda () (add-hook 'change-major-mode-hook
7562 'org-show-block-all 'append 'local)))
7564 ;;; Org-goto
7566 (defvar org-goto-window-configuration nil)
7567 (defvar org-goto-marker nil)
7568 (defvar org-goto-map)
7569 (defun org-goto-map ()
7570 "Set the keymap `org-goto'."
7571 (setq org-goto-map
7572 (let ((map (make-sparse-keymap)))
7573 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7574 mouse-drag-region universal-argument org-occur)))
7575 (dolist (cmd cmds)
7576 (substitute-key-definition cmd cmd map global-map)))
7577 (suppress-keymap map)
7578 (org-defkey map "\C-m" 'org-goto-ret)
7579 (org-defkey map [(return)] 'org-goto-ret)
7580 (org-defkey map [(left)] 'org-goto-left)
7581 (org-defkey map [(right)] 'org-goto-right)
7582 (org-defkey map [(control ?g)] 'org-goto-quit)
7583 (org-defkey map "\C-i" 'org-cycle)
7584 (org-defkey map [(tab)] 'org-cycle)
7585 (org-defkey map [(down)] 'outline-next-visible-heading)
7586 (org-defkey map [(up)] 'outline-previous-visible-heading)
7587 (if org-goto-auto-isearch
7588 (if (fboundp 'define-key-after)
7589 (define-key-after map [t] 'org-goto-local-auto-isearch)
7590 nil)
7591 (org-defkey map "q" 'org-goto-quit)
7592 (org-defkey map "n" 'outline-next-visible-heading)
7593 (org-defkey map "p" 'outline-previous-visible-heading)
7594 (org-defkey map "f" 'outline-forward-same-level)
7595 (org-defkey map "b" 'outline-backward-same-level)
7596 (org-defkey map "u" 'outline-up-heading))
7597 (org-defkey map "/" 'org-occur)
7598 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7599 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7600 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7601 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7602 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7603 map)))
7605 (defconst org-goto-help
7606 "Browse buffer copy, to find location or copy text.%s
7607 RET=jump to location C-g=quit and return to previous location
7608 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7610 (defvar org-goto-start-pos) ; dynamically scoped parameter
7612 (defun org-goto (&optional alternative-interface)
7613 "Look up a different location in the current file, keeping current visibility.
7615 When you want look-up or go to a different location in a
7616 document, the fastest way is often to fold the entire buffer and
7617 then dive into the tree. This method has the disadvantage, that
7618 the previous location will be folded, which may not be what you
7619 want.
7621 This command works around this by showing a copy of the current
7622 buffer in an indirect buffer, in overview mode. You can dive
7623 into the tree in that copy, use org-occur and incremental search
7624 to find a location. When pressing RET or `Q', the command
7625 returns to the original buffer in which the visibility is still
7626 unchanged. After RET it will also jump to the location selected
7627 in the indirect buffer and expose the headline hierarchy above.
7629 With a prefix argument, use the alternative interface: e.g., if
7630 `org-goto-interface' is `outline' use `outline-path-completion'."
7631 (interactive "P")
7632 (org-goto-map)
7633 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7634 (org-refile-use-outline-path t)
7635 (org-refile-target-verify-function nil)
7636 (interface
7637 (if (not alternative-interface)
7638 org-goto-interface
7639 (if (eq org-goto-interface 'outline)
7640 'outline-path-completion
7641 'outline)))
7642 (org-goto-start-pos (point))
7643 (selected-point
7644 (if (eq interface 'outline)
7645 (car (org-get-location (current-buffer) org-goto-help))
7646 (let ((pa (org-refile-get-location "Goto")))
7647 (org-refile-check-position pa)
7648 (nth 3 pa)))))
7649 (if selected-point
7650 (progn
7651 (org-mark-ring-push org-goto-start-pos)
7652 (goto-char selected-point)
7653 (when (or (outline-invisible-p) (org-invisible-p2))
7654 (org-show-context 'org-goto)))
7655 (message "Quit"))))
7657 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7658 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7659 (defvar org-goto-local-auto-isearch-map) ; defined below
7661 (defun org-get-location (_buf help)
7662 "Let the user select a location in current buffer.
7663 This function uses a recursive edit. It returns the selected position
7664 or nil."
7665 (org-no-popups
7666 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7667 (isearch-hide-immediately nil)
7668 (isearch-search-fun-function
7669 (lambda () 'org-goto-local-search-headings))
7670 (org-goto-selected-point org-goto-exit-command))
7671 (save-excursion
7672 (save-window-excursion
7673 (delete-other-windows)
7674 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7675 (pop-to-buffer-same-window
7676 (condition-case nil
7677 (make-indirect-buffer (current-buffer) "*org-goto*")
7678 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7679 (with-output-to-temp-buffer "*Org Help*"
7680 (princ (format help (if org-goto-auto-isearch
7681 " Just type for auto-isearch."
7682 " n/p/f/b/u to navigate, q to quit."))))
7683 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7684 (setq buffer-read-only nil)
7685 (let ((org-startup-truncated t)
7686 (org-startup-folded nil)
7687 (org-startup-align-all-tables nil))
7688 (org-mode)
7689 (org-overview))
7690 (setq buffer-read-only t)
7691 (if (and (boundp 'org-goto-start-pos)
7692 (integer-or-marker-p org-goto-start-pos))
7693 (progn (goto-char org-goto-start-pos)
7694 (when (outline-invisible-p)
7695 (org-show-set-visibility 'lineage)))
7696 (goto-char (point-min)))
7697 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7698 (message "Select location and press RET")
7699 (use-local-map org-goto-map)
7700 (recursive-edit)))
7701 (kill-buffer "*org-goto*")
7702 (cons org-goto-selected-point org-goto-exit-command))))
7704 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7705 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7706 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7707 (if (fboundp 'isearch-other-control-char)
7708 (progn
7709 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7710 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7711 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7712 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7713 (define-key org-goto-local-auto-isearch-map [return] nil))
7715 (defun org-goto-local-search-headings (string bound noerror)
7716 "Search and make sure that any matches are in headlines."
7717 (catch 'return
7718 (while (if isearch-forward
7719 (search-forward string bound noerror)
7720 (search-backward string bound noerror))
7721 (when (save-match-data
7722 (and (save-excursion
7723 (beginning-of-line)
7724 (looking-at org-complex-heading-regexp))
7725 (or (not (match-beginning 5))
7726 (< (point) (match-beginning 5)))))
7727 (throw 'return (point))))))
7729 (defun org-goto-local-auto-isearch ()
7730 "Start isearch."
7731 (interactive)
7732 (goto-char (point-min))
7733 (let ((keys (this-command-keys)))
7734 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7735 (isearch-mode t)
7736 (isearch-process-search-char (string-to-char keys)))))
7738 (defun org-goto-ret (&optional _arg)
7739 "Finish `org-goto' by going to the new location."
7740 (interactive "P")
7741 (setq org-goto-selected-point (point))
7742 (setq org-goto-exit-command 'return)
7743 (throw 'exit nil))
7745 (defun org-goto-left ()
7746 "Finish `org-goto' by going to the new location."
7747 (interactive)
7748 (if (org-at-heading-p)
7749 (progn
7750 (beginning-of-line 1)
7751 (setq org-goto-selected-point (point)
7752 org-goto-exit-command 'left)
7753 (throw 'exit nil))
7754 (user-error "Not on a heading")))
7756 (defun org-goto-right ()
7757 "Finish `org-goto' by going to the new location."
7758 (interactive)
7759 (if (org-at-heading-p)
7760 (progn
7761 (setq org-goto-selected-point (point)
7762 org-goto-exit-command 'right)
7763 (throw 'exit nil))
7764 (user-error "Not on a heading")))
7766 (defun org-goto-quit ()
7767 "Finish `org-goto' without cursor motion."
7768 (interactive)
7769 (setq org-goto-selected-point nil)
7770 (setq org-goto-exit-command 'quit)
7771 (throw 'exit nil))
7773 ;;; Indirect buffer display of subtrees
7775 (defvar org-indirect-dedicated-frame nil
7776 "This is the frame being used for indirect tree display.")
7777 (defvar org-last-indirect-buffer nil)
7779 (defun org-tree-to-indirect-buffer (&optional arg)
7780 "Create indirect buffer and narrow it to current subtree.
7782 With a numerical prefix ARG, go up to this level and then take that tree.
7783 If ARG is negative, go up that many levels.
7785 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7786 indirect buffer previously made with this command, to avoid proliferation of
7787 indirect buffers. However, when you call the command with a \
7788 `\\[universal-argument]' prefix, or
7789 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7790 so that you can work with several indirect buffers at the same time. If
7791 `org-indirect-buffer-display' is `dedicated-frame', the \
7792 `\\[universal-argument]' prefix also
7793 requests that a new frame be made for the new buffer, so that the dedicated
7794 frame is not changed."
7795 (interactive "P")
7796 (let ((cbuf (current-buffer))
7797 (cwin (selected-window))
7798 (pos (point))
7799 beg end level heading ibuf)
7800 (save-excursion
7801 (org-back-to-heading t)
7802 (when (numberp arg)
7803 (setq level (org-outline-level))
7804 (when (< arg 0) (setq arg (+ level arg)))
7805 (while (> (setq level (org-outline-level)) arg)
7806 (org-up-heading-safe)))
7807 (setq beg (point)
7808 heading (org-get-heading 'no-tags))
7809 (org-end-of-subtree t t)
7810 (when (org-at-heading-p) (backward-char 1))
7811 (setq end (point)))
7812 (when (and (buffer-live-p org-last-indirect-buffer)
7813 (not (eq org-indirect-buffer-display 'new-frame))
7814 (not arg))
7815 (kill-buffer org-last-indirect-buffer))
7816 (setq ibuf (org-get-indirect-buffer cbuf heading)
7817 org-last-indirect-buffer ibuf)
7818 (cond
7819 ((or (eq org-indirect-buffer-display 'new-frame)
7820 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7821 (select-frame (make-frame))
7822 (delete-other-windows)
7823 (pop-to-buffer-same-window ibuf)
7824 (org-set-frame-title heading))
7825 ((eq org-indirect-buffer-display 'dedicated-frame)
7826 (raise-frame
7827 (select-frame (or (and org-indirect-dedicated-frame
7828 (frame-live-p org-indirect-dedicated-frame)
7829 org-indirect-dedicated-frame)
7830 (setq org-indirect-dedicated-frame (make-frame)))))
7831 (delete-other-windows)
7832 (pop-to-buffer-same-window ibuf)
7833 (org-set-frame-title (concat "Indirect: " heading)))
7834 ((eq org-indirect-buffer-display 'current-window)
7835 (pop-to-buffer-same-window ibuf))
7836 ((eq org-indirect-buffer-display 'other-window)
7837 (pop-to-buffer ibuf))
7838 (t (error "Invalid value")))
7839 (narrow-to-region beg end)
7840 (outline-show-all)
7841 (goto-char pos)
7842 (run-hook-with-args 'org-cycle-hook 'all)
7843 (and (window-live-p cwin) (select-window cwin))))
7845 (defun org-get-indirect-buffer (&optional buffer heading)
7846 (setq buffer (or buffer (current-buffer)))
7847 (let ((n 1) (base (buffer-name buffer)) bname)
7848 (while (buffer-live-p
7849 (get-buffer
7850 (setq bname
7851 (concat base "-"
7852 (if heading (concat heading "-" (number-to-string n))
7853 (number-to-string n))))))
7854 (setq n (1+ n)))
7855 (condition-case nil
7856 (make-indirect-buffer buffer bname 'clone)
7857 (error (make-indirect-buffer buffer bname)))))
7859 (defun org-set-frame-title (title)
7860 "Set the title of the current frame to the string TITLE."
7861 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7863 ;;;; Structure editing
7865 ;;; Inserting headlines
7867 (defun org--line-empty-p (n)
7868 "Is the Nth next line empty?
7870 Counts the current line as N = 1 and the previous line as N = 0;
7871 see `beginning-of-line'."
7872 (save-excursion
7873 (and (not (bobp))
7874 (or (beginning-of-line n) t)
7875 (save-match-data
7876 (looking-at "[ \t]*$")))))
7878 (defun org-previous-line-empty-p ()
7879 "Is the previous line a blank line?
7880 When NEXT is non-nil, check the next line instead."
7881 (org--line-empty-p 0))
7883 (defun org-next-line-empty-p ()
7884 "Is the previous line a blank line?
7885 When NEXT is non-nil, check the next line instead."
7886 (org--line-empty-p 2))
7888 (defun org--blank-before-heading-p (&optional parent)
7889 "Non-nil when an empty line should precede a new heading here.
7890 When optional argument PARENT is non-nil, consider parent
7891 headline instead of current one."
7892 (pcase (assq 'heading org-blank-before-new-entry)
7893 (`(heading . auto)
7894 (save-excursion
7895 (org-with-limited-levels
7896 (unless (and (org-before-first-heading-p)
7897 (not (outline-next-heading)))
7898 (org-back-to-heading t)
7899 (when parent (org-up-heading-safe))
7900 (cond ((not (bobp))
7901 (org-previous-line-empty-p))
7902 ((outline-next-heading)
7903 (org-previous-line-empty-p))
7904 ;; Ignore trailing spaces on last buffer line.
7905 ((progn (skip-chars-backward " \t") (bolp))
7906 (org-previous-line-empty-p))
7907 (t nil))))))
7908 (`(heading . ,value) value)
7909 (_ nil)))
7911 (defun org-insert-heading (&optional arg invisible-ok top)
7912 "Insert a new heading or an item with the same depth at point.
7914 If point is at the beginning of a heading, insert a new heading
7915 or a new headline above the current one. When at the beginning
7916 of a regular line of text, turn it into a heading.
7918 If point is in the middle of a line, split it and create a new
7919 headline with the text in the current line after point (see
7920 `org-M-RET-may-split-line' on how to modify this behavior). As
7921 a special case, on a headline, splitting can only happen on the
7922 title itself. E.g., this excludes breaking stars or tags.
7924 With a `\\[universal-argument]' prefix, set \
7925 `org-insert-heading-respect-content' to
7926 a non-nil value for the duration of the command. This forces the
7927 insertion of a heading after the current subtree, independently
7928 on the location of point.
7930 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7931 insert the heading at the end of the tree
7932 above the current heading. For example, if point is within a
7933 2nd-level heading, then it will insert a 2nd-level heading at
7934 the end of the 1st-level parent subtree.
7936 When INVISIBLE-OK is set, stop at invisible headlines when going
7937 back. This is important for non-interactive uses of the
7938 command.
7940 When optional argument TOP is non-nil, insert a level 1 heading,
7941 unconditionally."
7942 (interactive "P")
7943 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7944 (level (org-current-level))
7945 (stars (make-string (if (and level (not top)) level 1) ?*)))
7946 (cond
7947 ((or org-insert-heading-respect-content
7948 (member arg '((4) (16)))
7949 (and (not invisible-ok)
7950 (invisible-p (max (1- (point)) (point-min)))))
7951 ;; Position point at the location of insertion.
7952 (if (not level) ;before first headline
7953 (org-with-limited-levels (outline-next-heading))
7954 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7955 ;; is nil.
7956 (org-with-limited-levels (org-back-to-heading invisible-ok))
7957 (cond ((equal arg '(16))
7958 (org-up-heading-safe)
7959 (org-end-of-subtree t t))
7961 (org-end-of-subtree t t))))
7962 (unless (bolp) (insert "\n")) ;ensure final newline
7963 (unless (and blank? (org-previous-line-empty-p))
7964 (org-N-empty-lines-before-current (if blank? 1 0)))
7965 (insert stars " \n")
7966 (forward-char -1))
7967 ;; At a headline...
7968 ((org-at-heading-p)
7969 (cond ((bolp)
7970 (when blank? (save-excursion (insert "\n")))
7971 (save-excursion (insert stars " \n"))
7972 (unless (and blank? (org-previous-line-empty-p))
7973 (org-N-empty-lines-before-current (if blank? 1 0)))
7974 (end-of-line))
7975 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7976 (org-match-line org-complex-heading-regexp)
7977 (org-pos-in-match-range (point) 4))
7978 ;; Grab the text that should moved to the new headline.
7979 ;; Preserve tags.
7980 (let ((split (delete-and-extract-region (point) (match-end 4))))
7981 (if (looking-at "[ \t]*$") (replace-match "")
7982 (org-set-tags nil t))
7983 (end-of-line)
7984 (when blank? (insert "\n"))
7985 (insert "\n" stars " ")
7986 (when (org-string-nw-p split) (insert split))
7987 (insert "\n")
7988 (forward-char -1)))
7990 (end-of-line)
7991 (when blank? (insert "\n"))
7992 (insert "\n" stars " \n")
7993 (forward-char -1))))
7994 ;; On regular text, turn line into a headline or split, if
7995 ;; appropriate.
7996 ((bolp)
7997 (insert stars " ")
7998 (unless (and blank? (org-previous-line-empty-p))
7999 (org-N-empty-lines-before-current (if blank? 1 0))))
8001 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
8002 (end-of-line))
8003 (insert "\n" stars " ")
8004 (unless (and blank? (org-previous-line-empty-p))
8005 (org-N-empty-lines-before-current (if blank? 1 0))))))
8006 (run-hooks 'org-insert-heading-hook))
8008 (defun org-N-empty-lines-before-current (n)
8009 "Make the number of empty lines before current exactly N.
8010 So this will delete or add empty lines."
8011 (let ((column (current-column))
8012 (empty-lines (make-string n ?\n)))
8013 (beginning-of-line)
8014 (let ((p (point)))
8015 (skip-chars-backward " \r\t\n")
8016 (unless (bolp) (forward-line))
8017 (delete-region (point) p))
8018 (insert empty-lines)
8019 (move-to-column column)))
8021 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
8022 "Return the heading of the current entry, without the stars.
8023 When NO-TAGS is non-nil, don't include tags.
8024 When NO-TODO is non-nil, don't include TODO keywords.
8025 When NO-PRIORITY is non-nil, don't include priority cookie.
8026 When NO-COMMENT is non-nil, don't include COMMENT string."
8027 (save-excursion
8028 (org-back-to-heading t)
8029 (let ((case-fold-search nil))
8030 (looking-at org-complex-heading-regexp)
8031 (let ((todo (and (not no-todo) (match-string 2)))
8032 (priority (and (not no-priority) (match-string 3)))
8033 (headline (pcase (match-string 4)
8034 (`nil "")
8035 ((and (guard no-comment) h)
8036 (replace-regexp-in-string
8037 (eval-when-compile
8038 (format "\\`%s[ \t]+" org-comment-string))
8039 "" h))
8040 (h h)))
8041 (tags (and (not no-tags) (match-string 5))))
8042 (mapconcat #'identity
8043 (delq nil (list todo priority headline tags))
8044 " ")))))
8046 (defvar orgstruct-mode) ; defined below
8048 (defun org-heading-components ()
8049 "Return the components of the current heading.
8050 This is a list with the following elements:
8051 - the level as an integer
8052 - the reduced level, different if `org-odd-levels-only' is set.
8053 - the TODO keyword, or nil
8054 - the priority character, like ?A, or nil if no priority is given
8055 - the headline text itself, or the tags string if no headline text
8056 - the tags string, or nil."
8057 (save-excursion
8058 (org-back-to-heading t)
8059 (when (let (case-fold-search)
8060 (looking-at
8061 (if orgstruct-mode
8062 org-heading-regexp
8063 org-complex-heading-regexp)))
8064 (if orgstruct-mode
8065 (list (length (match-string 1))
8066 (org-reduced-level (length (match-string 1)))
8069 (match-string 2)
8070 nil)
8071 (list (length (match-string 1))
8072 (org-reduced-level (length (match-string 1)))
8073 (match-string-no-properties 2)
8074 (and (match-end 3) (aref (match-string 3) 2))
8075 (match-string-no-properties 4)
8076 (match-string-no-properties 5))))))
8078 (defun org-get-entry ()
8079 "Get the entry text, after heading, entire subtree."
8080 (save-excursion
8081 (org-back-to-heading t)
8082 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8084 (defun org-edit-headline (&optional heading)
8085 "Edit the current headline.
8086 Set it to HEADING when provided."
8087 (interactive)
8088 (org-with-wide-buffer
8089 (org-back-to-heading t)
8090 (let ((case-fold-search nil))
8091 (when (looking-at org-complex-heading-regexp)
8092 (let* ((old (match-string-no-properties 4))
8093 (new (save-match-data
8094 (org-trim (or heading (read-string "Edit: " old))))))
8095 (unless (equal old new)
8096 (if old (replace-match new t t nil 4)
8097 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8098 (insert " " new))
8099 (org-set-tags nil t)
8100 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8102 (defun org-insert-heading-after-current ()
8103 "Insert a new heading with same level as current, after current subtree."
8104 (interactive)
8105 (org-back-to-heading)
8106 (org-insert-heading)
8107 (org-move-subtree-down)
8108 (end-of-line 1))
8110 (defun org-insert-heading-respect-content (&optional invisible-ok)
8111 "Insert heading with `org-insert-heading-respect-content' set to t."
8112 (interactive)
8113 (org-insert-heading '(4) invisible-ok))
8115 (defun org-insert-todo-heading-respect-content (&optional force-state)
8116 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8117 (interactive)
8118 (org-insert-todo-heading force-state '(4)))
8120 (defun org-insert-todo-heading (arg &optional force-heading)
8121 "Insert a new heading with the same level and TODO state as current heading.
8123 If the heading has no TODO state, or if the state is DONE, use
8124 the first state (TODO by default). Also with one prefix arg,
8125 force first state. With two prefix args, force inserting at the
8126 end of the parent subtree.
8128 When called at a plain list item, insert a new item with an
8129 unchecked check box."
8130 (interactive "P")
8131 (when (or force-heading (not (org-insert-item 'checkbox)))
8132 (org-insert-heading (or (and (equal arg '(16)) '(16))
8133 force-heading))
8134 (save-excursion
8135 (org-back-to-heading)
8136 (outline-previous-heading)
8137 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8138 (let* ((new-mark-x
8139 (if (or (equal arg '(4))
8140 (not (match-beginning 2))
8141 (member (match-string 2) org-done-keywords))
8142 (car org-todo-keywords-1)
8143 (match-string 2)))
8144 (new-mark
8146 (run-hook-with-args-until-success
8147 'org-todo-get-default-hook new-mark-x nil)
8148 new-mark-x)))
8149 (beginning-of-line 1)
8150 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8151 (if org-treat-insert-todo-heading-as-state-change
8152 (org-todo new-mark)
8153 (insert new-mark " "))))
8154 (when org-provide-todo-statistics
8155 (org-update-parent-todo-statistics))))
8157 (defun org-insert-subheading (arg)
8158 "Insert a new subheading and demote it.
8159 Works for outline headings and for plain lists alike."
8160 (interactive "P")
8161 (org-insert-heading arg)
8162 (cond
8163 ((org-at-heading-p) (org-do-demote))
8164 ((org-at-item-p) (org-indent-item))))
8166 (defun org-insert-todo-subheading (arg)
8167 "Insert a new subheading with TODO keyword or checkbox and demote it.
8168 Works for outline headings and for plain lists alike."
8169 (interactive "P")
8170 (org-insert-todo-heading arg)
8171 (cond
8172 ((org-at-heading-p) (org-do-demote))
8173 ((org-at-item-p) (org-indent-item))))
8175 ;;; Promotion and Demotion
8177 (defvar org-after-demote-entry-hook nil
8178 "Hook run after an entry has been demoted.
8179 The cursor will be at the beginning of the entry.
8180 When a subtree is being demoted, the hook will be called for each node.")
8182 (defvar org-after-promote-entry-hook nil
8183 "Hook run after an entry has been promoted.
8184 The cursor will be at the beginning of the entry.
8185 When a subtree is being promoted, the hook will be called for each node.")
8187 (defun org-promote-subtree ()
8188 "Promote the entire subtree.
8189 See also `org-promote'."
8190 (interactive)
8191 (save-excursion
8192 (org-with-limited-levels (org-map-tree 'org-promote)))
8193 (org-fix-position-after-promote))
8195 (defun org-demote-subtree ()
8196 "Demote the entire subtree.
8197 See `org-demote' and `org-promote'."
8198 (interactive)
8199 (save-excursion
8200 (org-with-limited-levels (org-map-tree 'org-demote)))
8201 (org-fix-position-after-promote))
8203 (defun org-do-promote ()
8204 "Promote the current heading higher up the tree.
8205 If the region is active in `transient-mark-mode', promote all
8206 headings in the region."
8207 (interactive)
8208 (save-excursion
8209 (if (org-region-active-p)
8210 (org-map-region 'org-promote (region-beginning) (region-end))
8211 (org-promote)))
8212 (org-fix-position-after-promote))
8214 (defun org-do-demote ()
8215 "Demote the current heading lower down the tree.
8216 If the region is active in `transient-mark-mode', demote all
8217 headings in the region."
8218 (interactive)
8219 (save-excursion
8220 (if (org-region-active-p)
8221 (org-map-region 'org-demote (region-beginning) (region-end))
8222 (org-demote)))
8223 (org-fix-position-after-promote))
8225 (defun org-fix-position-after-promote ()
8226 "Fix cursor position and indentation after demoting/promoting."
8227 (let ((pos (point)))
8228 (when (save-excursion
8229 (beginning-of-line)
8230 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8231 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8232 (cond ((eobp) (insert " "))
8233 ((eolp) (insert " "))
8234 ((equal (char-after) ?\s) (forward-char 1))))))
8236 (defun org-current-level ()
8237 "Return the level of the current entry, or nil if before the first headline.
8238 The level is the number of stars at the beginning of the
8239 headline. Use `org-reduced-level' to remove the effect of
8240 `org-odd-levels'. Unlike to `org-outline-level', this function
8241 ignores inlinetasks."
8242 (let ((level (org-with-limited-levels (org-outline-level))))
8243 (and (> level 0) level)))
8245 (defun org-get-previous-line-level ()
8246 "Return the outline depth of the last headline before the current line.
8247 Returns 0 for the first headline in the buffer, and nil if before the
8248 first headline."
8249 (and (org-current-level)
8250 (or (and (/= (line-beginning-position) (point-min))
8251 (save-excursion (beginning-of-line 0) (org-current-level)))
8252 0)))
8254 (defun org-reduced-level (l)
8255 "Compute the effective level of a heading.
8256 This takes into account the setting of `org-odd-levels-only'."
8257 (cond
8258 ((zerop l) 0)
8259 (org-odd-levels-only (1+ (floor (/ l 2))))
8260 (t l)))
8262 (defun org-level-increment ()
8263 "Return the number of stars that will be added or removed at a
8264 time to headlines when structure editing, based on the value of
8265 `org-odd-levels-only'."
8266 (if org-odd-levels-only 2 1))
8268 (defun org-get-valid-level (level &optional change)
8269 "Rectify a level change under the influence of `org-odd-levels-only'.
8270 LEVEL is a current level, CHANGE is by how much the level should
8271 be modified. Even if CHANGE is nil, LEVEL may be returned
8272 modified because even level numbers will become the next higher
8273 odd number. Returns values greater than 0."
8274 (if org-odd-levels-only
8275 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8276 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8277 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8278 (max 1 (+ level (or change 0)))))
8280 (defun org-promote ()
8281 "Promote the current heading higher up the tree."
8282 (org-with-wide-buffer
8283 (org-back-to-heading t)
8284 (let* ((after-change-functions (remq 'flyspell-after-change-function
8285 after-change-functions))
8286 (level (save-match-data (funcall outline-level)))
8287 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8288 (diff (abs (- level (length up-head) -1))))
8289 (cond
8290 ((and (= level 1) org-allow-promoting-top-level-subtree)
8291 (replace-match "# " nil t))
8292 ((= level 1)
8293 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8294 (t (replace-match up-head nil t)))
8295 (unless (= level 1)
8296 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8297 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8298 (run-hooks 'org-after-promote-entry-hook))))
8300 (defun org-demote ()
8301 "Demote the current heading lower down the tree."
8302 (org-with-wide-buffer
8303 (org-back-to-heading t)
8304 (let* ((after-change-functions (remq 'flyspell-after-change-function
8305 after-change-functions))
8306 (level (save-match-data (funcall outline-level)))
8307 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8308 (diff (abs (- level (length down-head) -1))))
8309 (replace-match down-head nil t)
8310 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8311 (when org-adapt-indentation (org-fixup-indentation diff))
8312 (run-hooks 'org-after-demote-entry-hook))))
8314 (defun org-cycle-level ()
8315 "Cycle the level of an empty headline through possible states.
8316 This goes first to child, then to parent, level, then up the hierarchy.
8317 After top level, it switches back to sibling level."
8318 (interactive)
8319 (let ((org-adapt-indentation nil))
8320 (when (org-point-at-end-of-empty-headline)
8321 (setq this-command 'org-cycle-level) ; Only needed for caching
8322 (let ((cur-level (org-current-level))
8323 (prev-level (org-get-previous-line-level)))
8324 (cond
8325 ;; If first headline in file, promote to top-level.
8326 ((= prev-level 0)
8327 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8328 do (org-do-promote)))
8329 ;; If same level as prev, demote one.
8330 ((= prev-level cur-level)
8331 (org-do-demote))
8332 ;; If parent is top-level, promote to top level if not already.
8333 ((= prev-level 1)
8334 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8335 do (org-do-promote)))
8336 ;; If top-level, return to prev-level.
8337 ((= cur-level 1)
8338 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8339 do (org-do-demote)))
8340 ;; If less than prev-level, promote one.
8341 ((< cur-level prev-level)
8342 (org-do-promote))
8343 ;; If deeper than prev-level, promote until higher than
8344 ;; prev-level.
8345 ((> cur-level prev-level)
8346 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8347 do (org-do-promote))))
8348 t))))
8350 (defun org-map-tree (fun)
8351 "Call FUN for every heading underneath the current one."
8352 (org-back-to-heading t)
8353 (let ((level (funcall outline-level)))
8354 (save-excursion
8355 (funcall fun)
8356 (while (and (progn
8357 (outline-next-heading)
8358 (> (funcall outline-level) level))
8359 (not (eobp)))
8360 (funcall fun)))))
8362 (defun org-map-region (fun beg end)
8363 "Call FUN for every heading between BEG and END."
8364 (let ((org-ignore-region t))
8365 (save-excursion
8366 (setq end (copy-marker end))
8367 (goto-char beg)
8368 (when (and (re-search-forward org-outline-regexp-bol nil t)
8369 (< (point) end))
8370 (funcall fun))
8371 (while (and (progn
8372 (outline-next-heading)
8373 (< (point) end))
8374 (not (eobp)))
8375 (funcall fun)))))
8377 (defun org-fixup-indentation (diff)
8378 "Change the indentation in the current entry by DIFF.
8380 DIFF is an integer. Indentation is done according to the
8381 following rules:
8383 - Planning information and property drawers are always indented
8384 according to the new level of the headline;
8386 - Footnote definitions and their contents are ignored;
8388 - Inlinetasks' boundaries are not shifted;
8390 - Empty lines are ignored;
8392 - Other lines' indentation are shifted by DIFF columns, unless
8393 it would introduce a structural change in the document, in
8394 which case no shifting is done at all.
8396 Assume point is at a heading or an inlinetask beginning."
8397 (org-with-wide-buffer
8398 (narrow-to-region (line-beginning-position)
8399 (save-excursion
8400 (if (org-with-limited-levels (org-at-heading-p))
8401 (org-with-limited-levels (outline-next-heading))
8402 (org-inlinetask-goto-end))
8403 (point)))
8404 (forward-line)
8405 ;; Indent properly planning info and property drawer.
8406 (when (looking-at-p org-planning-line-re)
8407 (org-indent-line)
8408 (forward-line))
8409 (when (looking-at org-property-drawer-re)
8410 (goto-char (match-end 0))
8411 (forward-line)
8412 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8413 (catch 'no-shift
8414 (when (zerop diff) (throw 'no-shift nil))
8415 ;; If DIFF is negative, first check if a shift is possible at all
8416 ;; (e.g., it doesn't break structure). This can only happen if
8417 ;; some contents are not properly indented.
8418 (let ((case-fold-search t))
8419 (when (< diff 0)
8420 (let ((diff (- diff))
8421 (forbidden-re (concat org-outline-regexp
8422 "\\|"
8423 (substring org-footnote-definition-re 1))))
8424 (save-excursion
8425 (while (not (eobp))
8426 (cond
8427 ((looking-at-p "[ \t]*$") (forward-line))
8428 ((and (looking-at-p org-footnote-definition-re)
8429 (let ((e (org-element-at-point)))
8430 (and (eq (org-element-type e) 'footnote-definition)
8431 (goto-char (org-element-property :end e))))))
8432 ((looking-at-p org-outline-regexp) (forward-line))
8433 ;; Give up if shifting would move before column 0 or
8434 ;; if it would introduce a headline or a footnote
8435 ;; definition.
8437 (skip-chars-forward " \t")
8438 (let ((ind (current-column)))
8439 (when (or (< ind diff)
8440 (and (= ind diff) (looking-at-p forbidden-re)))
8441 (throw 'no-shift nil)))
8442 ;; Ignore contents of example blocks and source
8443 ;; blocks if their indentation is meant to be
8444 ;; preserved. Jump to block's closing line.
8445 (beginning-of-line)
8446 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8447 (let ((e (org-element-at-point)))
8448 (and (memq (org-element-type e)
8449 '(example-block src-block))
8450 (or org-src-preserve-indentation
8451 (org-element-property :preserve-indent e))
8452 (goto-char (org-element-property :end e))
8453 (progn (skip-chars-backward " \r\t\n")
8454 (beginning-of-line)
8455 t))))
8456 (forward-line))))))))
8457 ;; Shift lines but footnote definitions, inlinetasks boundaries
8458 ;; by DIFF. Also skip contents of source or example blocks
8459 ;; when indentation is meant to be preserved.
8460 (while (not (eobp))
8461 (cond
8462 ((and (looking-at-p org-footnote-definition-re)
8463 (let ((e (org-element-at-point)))
8464 (and (eq (org-element-type e) 'footnote-definition)
8465 (goto-char (org-element-property :end e))))))
8466 ((looking-at-p org-outline-regexp) (forward-line))
8467 ((looking-at-p "[ \t]*$") (forward-line))
8469 (indent-line-to (+ (org-get-indentation) diff))
8470 (beginning-of-line)
8471 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8472 (let ((e (org-element-at-point)))
8473 (and (memq (org-element-type e)
8474 '(example-block src-block))
8475 (or org-src-preserve-indentation
8476 (org-element-property :preserve-indent e))
8477 (goto-char (org-element-property :end e))
8478 (progn (skip-chars-backward " \r\t\n")
8479 (beginning-of-line)
8480 t))))
8481 (forward-line)))))))))
8483 (defun org-convert-to-odd-levels ()
8484 "Convert an Org file with all levels allowed to one with odd levels.
8485 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8486 level 5 etc."
8487 (interactive)
8488 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8489 (let ((outline-level 'org-outline-level)
8490 (org-odd-levels-only nil) n)
8491 (save-excursion
8492 (goto-char (point-min))
8493 (while (re-search-forward "^\\*\\*+ " nil t)
8494 (setq n (- (length (match-string 0)) 2))
8495 (while (>= (setq n (1- n)) 0)
8496 (org-demote))
8497 (end-of-line 1))))))
8499 (defun org-convert-to-oddeven-levels ()
8500 "Convert an Org file with only odd levels to one with odd/even levels.
8501 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8502 file contains a section with an even level, conversion would
8503 destroy the structure of the file. An error is signaled in this
8504 case."
8505 (interactive)
8506 (goto-char (point-min))
8507 ;; First check if there are no even levels
8508 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8509 (org-show-set-visibility 'canonical)
8510 (error "Not all levels are odd in this file. Conversion not possible"))
8511 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8512 (let ((outline-regexp org-outline-regexp)
8513 (outline-level 'org-outline-level)
8514 (org-odd-levels-only nil) n)
8515 (save-excursion
8516 (goto-char (point-min))
8517 (while (re-search-forward "^\\*\\*+ " nil t)
8518 (setq n (/ (1- (length (match-string 0))) 2))
8519 (while (>= (setq n (1- n)) 0)
8520 (org-promote))
8521 (end-of-line 1))))))
8523 (defun org-tr-level (n)
8524 "Make N odd if required."
8525 (if org-odd-levels-only (1+ (/ n 2)) n))
8527 ;;; Vertical tree motion, cutting and pasting of subtrees
8529 (defun org-move-subtree-up (&optional arg)
8530 "Move the current subtree up past ARG headlines of the same level."
8531 (interactive "p")
8532 (org-move-subtree-down (- (prefix-numeric-value arg))))
8534 (defun org-move-subtree-down (&optional arg)
8535 "Move the current subtree down past ARG headlines of the same level."
8536 (interactive "p")
8537 (setq arg (prefix-numeric-value arg))
8538 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8539 'org-get-last-sibling))
8540 (ins-point (make-marker))
8541 (cnt (abs arg))
8542 (col (current-column))
8543 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8544 ;; Select the tree
8545 (org-back-to-heading)
8546 (setq beg0 (point))
8547 (save-excursion
8548 (setq ne-beg (org-back-over-empty-lines))
8549 (setq beg (point)))
8550 (save-match-data
8551 (save-excursion (outline-end-of-heading)
8552 (setq folded (outline-invisible-p)))
8553 (progn (org-end-of-subtree nil t)
8554 (unless (eobp) (backward-char))))
8555 (outline-next-heading)
8556 (setq ne-end (org-back-over-empty-lines))
8557 (setq end (point))
8558 (goto-char beg0)
8559 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8560 ;; include less whitespace
8561 (save-excursion
8562 (goto-char beg)
8563 (forward-line (- ne-beg ne-end))
8564 (setq beg (point))))
8565 ;; Find insertion point, with error handling
8566 (while (> cnt 0)
8567 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8568 (progn (goto-char beg0)
8569 (user-error "Cannot move past superior level or buffer limit")))
8570 (setq cnt (1- cnt)))
8571 (when (> arg 0)
8572 ;; Moving forward - still need to move over subtree
8573 (org-end-of-subtree t t)
8574 (save-excursion
8575 (org-back-over-empty-lines)
8576 (or (bolp) (newline))))
8577 (setq ne-ins (org-back-over-empty-lines))
8578 (move-marker ins-point (point))
8579 (setq txt (buffer-substring beg end))
8580 (org-save-markers-in-region beg end)
8581 (delete-region beg end)
8582 (org-remove-empty-overlays-at beg)
8583 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8584 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8585 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8586 (let ((bbb (point)))
8587 (insert-before-markers txt)
8588 (org-reinstall-markers-in-region bbb)
8589 (move-marker ins-point bbb))
8590 (or (bolp) (insert "\n"))
8591 (setq ins-end (point))
8592 (goto-char ins-point)
8593 (org-skip-whitespace)
8594 (when (and (< arg 0)
8595 (org-first-sibling-p)
8596 (> ne-ins ne-beg))
8597 ;; Move whitespace back to beginning
8598 (save-excursion
8599 (goto-char ins-end)
8600 (let ((kill-whole-line t))
8601 (kill-line (- ne-ins ne-beg)) (point)))
8602 (insert (make-string (- ne-ins ne-beg) ?\n)))
8603 (move-marker ins-point nil)
8604 (if folded
8605 (outline-hide-subtree)
8606 (org-show-entry)
8607 (org-show-children)
8608 (org-cycle-hide-drawers 'children))
8609 (org-clean-visibility-after-subtree-move)
8610 ;; move back to the initial column we were at
8611 (move-to-column col)))
8613 (defvar org-subtree-clip ""
8614 "Clipboard for cut and paste of subtrees.
8615 This is actually only a copy of the kill, because we use the normal kill
8616 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8618 (defvar org-subtree-clip-folded nil
8619 "Was the last copied subtree folded?
8620 This is used to fold the tree back after pasting.")
8622 (defun org-cut-subtree (&optional n)
8623 "Cut the current subtree into the clipboard.
8624 With prefix arg N, cut this many sequential subtrees.
8625 This is a short-hand for marking the subtree and then cutting it."
8626 (interactive "p")
8627 (org-copy-subtree n 'cut))
8629 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8630 "Copy the current subtree it in the clipboard.
8631 With prefix arg N, copy this many sequential subtrees.
8632 This is a short-hand for marking the subtree and then copying it.
8633 If CUT is non-nil, actually cut the subtree.
8634 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8635 of some markers in the region, even if CUT is non-nil. This is
8636 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8637 (interactive "p")
8638 (let (beg end folded (beg0 (point)))
8639 (if (called-interactively-p 'any)
8640 (org-back-to-heading nil) ; take what looks like a subtree
8641 (org-back-to-heading t)) ; take what is really there
8642 (setq beg (point))
8643 (skip-chars-forward " \t\r\n")
8644 (save-match-data
8645 (if nosubtrees
8646 (outline-next-heading)
8647 (save-excursion (outline-end-of-heading)
8648 (setq folded (outline-invisible-p)))
8649 (ignore-errors (org-forward-heading-same-level (1- n) t))
8650 (org-end-of-subtree t t)))
8651 ;; Include the end of an inlinetask
8652 (when (and (featurep 'org-inlinetask)
8653 (looking-at-p (concat (org-inlinetask-outline-regexp)
8654 "END[ \t]*$")))
8655 (end-of-line))
8656 (setq end (point))
8657 (goto-char beg0)
8658 (when (> end beg)
8659 (setq org-subtree-clip-folded folded)
8660 (when (or cut force-store-markers)
8661 (org-save-markers-in-region beg end))
8662 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8663 (setq org-subtree-clip (current-kill 0))
8664 (message "%s: Subtree(s) with %d characters"
8665 (if cut "Cut" "Copied")
8666 (length org-subtree-clip)))))
8668 (defun org-paste-subtree (&optional level tree for-yank remove)
8669 "Paste the clipboard as a subtree, with modification of headline level.
8670 The entire subtree is promoted or demoted in order to match a new headline
8671 level.
8673 If the cursor is at the beginning of a headline, the same level as
8674 that headline is used to paste the tree.
8676 If not, the new level is derived from the *visible* headings
8677 before and after the insertion point, and taken to be the inferior headline
8678 level of the two. So if the previous visible heading is level 3 and the
8679 next is level 4 (or vice versa), level 4 will be used for insertion.
8680 This makes sure that the subtree remains an independent subtree and does
8681 not swallow low level entries.
8683 You can also force a different level, either by using a numeric prefix
8684 argument, or by inserting the heading marker by hand. For example, if the
8685 cursor is after \"*****\", then the tree will be shifted to level 5.
8687 If optional TREE is given, use this text instead of the kill ring.
8689 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8690 move back over whitespace before inserting, and move point to the end of
8691 the inserted text when done.
8693 When REMOVE is non-nil, remove the subtree from the clipboard."
8694 (interactive "P")
8695 (setq tree (or tree (and kill-ring (current-kill 0))))
8696 (unless (org-kill-is-subtree-p tree)
8697 (user-error "%s"
8698 (substitute-command-keys
8699 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8700 (org-with-limited-levels
8701 (let* ((visp (not (outline-invisible-p)))
8702 (txt tree)
8703 (^re_ "\\(\\*+\\)[ \t]*")
8704 (old-level (if (string-match org-outline-regexp-bol txt)
8705 (- (match-end 0) (match-beginning 0) 1)
8706 -1))
8707 (force-level (cond (level (prefix-numeric-value level))
8708 ((and (looking-at "[ \t]*$")
8709 (string-match
8710 "^\\*+$" (buffer-substring
8711 (point-at-bol) (point))))
8712 (- (match-end 0) (match-beginning 0)))
8713 ((and (bolp)
8714 (looking-at org-outline-regexp))
8715 (- (match-end 0) (point) 1))))
8716 (previous-level (save-excursion
8717 (condition-case nil
8718 (progn
8719 (outline-previous-visible-heading 1)
8720 (if (looking-at ^re_)
8721 (- (match-end 0) (match-beginning 0) 1)
8723 (error 1))))
8724 (next-level (save-excursion
8725 (condition-case nil
8726 (progn
8727 (or (looking-at org-outline-regexp)
8728 (outline-next-visible-heading 1))
8729 (if (looking-at ^re_)
8730 (- (match-end 0) (match-beginning 0) 1)
8732 (error 1))))
8733 (new-level (or force-level (max previous-level next-level)))
8734 (shift (if (or (= old-level -1)
8735 (= new-level -1)
8736 (= old-level new-level))
8738 (- new-level old-level)))
8739 (delta (if (> shift 0) -1 1))
8740 (func (if (> shift 0) 'org-demote 'org-promote))
8741 (org-odd-levels-only nil)
8742 beg end newend)
8743 ;; Remove the forced level indicator
8744 (when force-level
8745 (delete-region (point-at-bol) (point)))
8746 ;; Paste
8747 (beginning-of-line (if (bolp) 1 2))
8748 (setq beg (point))
8749 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8750 (insert-before-markers txt)
8751 (unless (string-suffix-p "\n" txt) (insert "\n"))
8752 (setq newend (point))
8753 (org-reinstall-markers-in-region beg)
8754 (setq end (point))
8755 (goto-char beg)
8756 (skip-chars-forward " \t\n\r")
8757 (setq beg (point))
8758 (when (and (outline-invisible-p) visp)
8759 (save-excursion (outline-show-heading)))
8760 ;; Shift if necessary
8761 (unless (= shift 0)
8762 (save-restriction
8763 (narrow-to-region beg end)
8764 (while (not (= shift 0))
8765 (org-map-region func (point-min) (point-max))
8766 (setq shift (+ delta shift)))
8767 (goto-char (point-min))
8768 (setq newend (point-max))))
8769 (when (or (called-interactively-p 'interactive) for-yank)
8770 (message "Clipboard pasted as level %d subtree" new-level))
8771 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8772 kill-ring
8773 (eq org-subtree-clip (current-kill 0))
8774 org-subtree-clip-folded)
8775 ;; The tree was folded before it was killed/copied
8776 (outline-hide-subtree))
8777 (and for-yank (goto-char newend))
8778 (and remove (setq kill-ring (cdr kill-ring))))))
8780 (defun org-kill-is-subtree-p (&optional txt)
8781 "Check if the current kill is an outline subtree, or a set of trees.
8782 Returns nil if kill does not start with a headline, or if the first
8783 headline level is not the largest headline level in the tree.
8784 So this will actually accept several entries of equal levels as well,
8785 which is OK for `org-paste-subtree'.
8786 If optional TXT is given, check this string instead of the current kill."
8787 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8788 (re (org-get-limited-outline-regexp))
8789 (^re (concat "^" re))
8790 (start-level (and kill
8791 (string-match
8792 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8793 kill)
8794 (- (match-end 2) (match-beginning 2) 1)))
8795 (start (1+ (or (match-beginning 2) -1))))
8796 (if (not start-level)
8797 (progn
8798 nil) ;; does not even start with a heading
8799 (catch 'exit
8800 (while (setq start (string-match ^re kill (1+ start)))
8801 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8802 (throw 'exit nil)))
8803 t))))
8805 (defvar org-markers-to-move nil
8806 "Markers that should be moved with a cut-and-paste operation.
8807 Those markers are stored together with their positions relative to
8808 the start of the region.")
8810 (defun org-save-markers-in-region (beg end)
8811 "Check markers in region.
8812 If these markers are between BEG and END, record their position relative
8813 to BEG, so that after moving the block of text, we can put the markers back
8814 into place.
8815 This function gets called just before an entry or tree gets cut from the
8816 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8817 called immediately, to move the markers with the entries."
8818 (setq org-markers-to-move nil)
8819 (when (featurep 'org-clock)
8820 (org-clock-save-markers-for-cut-and-paste beg end))
8821 (when (featurep 'org-agenda)
8822 (org-agenda-save-markers-for-cut-and-paste beg end)))
8824 (defun org-check-and-save-marker (marker beg end)
8825 "Check if MARKER is between BEG and END.
8826 If yes, remember the marker and the distance to BEG."
8827 (when (and (marker-buffer marker)
8828 (equal (marker-buffer marker) (current-buffer))
8829 (>= marker beg) (< marker end))
8830 (push (cons marker (- marker beg)) org-markers-to-move)))
8832 (defun org-reinstall-markers-in-region (beg)
8833 "Move all remembered markers to their position relative to BEG."
8834 (dolist (x org-markers-to-move)
8835 (move-marker (car x) (+ beg (cdr x))))
8836 (setq org-markers-to-move nil))
8838 (defun org-narrow-to-subtree ()
8839 "Narrow buffer to the current subtree."
8840 (interactive)
8841 (save-excursion
8842 (save-match-data
8843 (org-with-limited-levels
8844 (narrow-to-region
8845 (progn (org-back-to-heading t) (point))
8846 (progn (org-end-of-subtree t t)
8847 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8848 (point)))))))
8850 (defun org-narrow-to-block ()
8851 "Narrow buffer to the current block."
8852 (interactive)
8853 (let* ((case-fold-search t)
8854 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8855 "^[ \t]*#\\+end_.*")))
8856 (if blockp
8857 (narrow-to-region (car blockp) (cdr blockp))
8858 (user-error "Not in a block"))))
8860 (defun org-clone-subtree-with-time-shift (n &optional shift)
8861 "Clone the task (subtree) at point N times.
8862 The clones will be inserted as siblings.
8864 In interactive use, the user will be prompted for the number of
8865 clones to be produced. If the entry has a timestamp, the user
8866 will also be prompted for a time shift, which may be a repeater
8867 as used in time stamps, for example `+3d'. To disable this,
8868 you can call the function with a universal prefix argument.
8870 When a valid repeater is given and the entry contains any time
8871 stamps, the clones will become a sequence in time, with time
8872 stamps in the subtree shifted for each clone produced. If SHIFT
8873 is nil or the empty string, time stamps will be left alone. The
8874 ID property of the original subtree is removed.
8876 In each clone, all the CLOCK entries will be removed. This
8877 prevents Org from considering that the clocked times overlap.
8879 If the original subtree did contain time stamps with a repeater,
8880 the following will happen:
8881 - the repeater will be removed in each clone
8882 - an additional clone will be produced, with the current, unshifted
8883 date(s) in the entry.
8884 - the original entry will be placed *after* all the clones, with
8885 repeater intact.
8886 - the start days in the repeater in the original entry will be shifted
8887 to past the last clone.
8888 In this way you can spell out a number of instances of a repeating task,
8889 and still retain the repeater to cover future instances of the task.
8891 As described above, N+1 clones are produced when the original
8892 subtree has a repeater. Setting N to 0, then, can be used to
8893 remove the repeater from a subtree and create a shifted clone
8894 with the original repeater."
8895 (interactive "nNumber of clones to produce: ")
8896 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8897 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8898 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8899 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8900 (shift
8901 (or shift
8902 (if (and (not (equal current-prefix-arg '(4)))
8903 (save-excursion
8904 (goto-char beg)
8905 (re-search-forward org-ts-regexp-both end-of-tree t)))
8906 (read-from-minibuffer
8907 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8908 ""))) ;No time shift
8909 (doshift
8910 (and (org-string-nw-p shift)
8911 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8912 shift)
8913 (user-error "Invalid shift specification %s" shift)))))
8914 (goto-char end-of-tree)
8915 (unless (bolp) (insert "\n"))
8916 (let* ((end (point))
8917 (template (buffer-substring beg end))
8918 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8919 (shift-what (pcase (and doshift (match-string 2 shift))
8920 (`nil nil)
8921 ("d" 'day)
8922 ("w" (setq shift-n (* 7 shift-n)) 'day)
8923 ("m" 'month)
8924 ("y" 'year)
8925 (_ (error "Unsupported time unit"))))
8926 (nmin 1)
8927 (nmax n)
8928 (n-no-remove -1)
8929 (idprop (org-entry-get nil "ID")))
8930 (when (and doshift
8931 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8932 template))
8933 (delete-region beg end)
8934 (setq end beg)
8935 (setq nmin 0)
8936 (setq nmax (1+ nmax))
8937 (setq n-no-remove nmax))
8938 (goto-char end)
8939 (cl-loop for n from nmin to nmax do
8940 (insert
8941 ;; Prepare clone.
8942 (with-temp-buffer
8943 (insert template)
8944 (org-mode)
8945 (goto-char (point-min))
8946 (org-show-subtree)
8947 (and idprop (if org-clone-delete-id
8948 (org-entry-delete nil "ID")
8949 (org-id-get-create t)))
8950 (unless (= n 0)
8951 (while (re-search-forward org-clock-line-re nil t)
8952 (delete-region (line-beginning-position)
8953 (line-beginning-position 2)))
8954 (goto-char (point-min))
8955 (while (re-search-forward org-drawer-regexp nil t)
8956 (org-remove-empty-drawer-at (point))))
8957 (goto-char (point-min))
8958 (when doshift
8959 (while (re-search-forward org-ts-regexp-both nil t)
8960 (org-timestamp-change (* n shift-n) shift-what))
8961 (unless (= n n-no-remove)
8962 (goto-char (point-min))
8963 (while (re-search-forward org-ts-regexp nil t)
8964 (save-excursion
8965 (goto-char (match-beginning 0))
8966 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8967 (delete-region (match-beginning 1) (match-end 1)))))))
8968 (buffer-string)))))
8969 (goto-char beg)))
8971 ;;; Outline Sorting
8973 (defun org-sort (with-case)
8974 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8975 Optional argument WITH-CASE means sort case-sensitively."
8976 (interactive "P")
8977 (cond
8978 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8979 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8981 (org-call-with-arg 'org-sort-entries with-case))))
8983 (defun org-sort-remove-invisible (s)
8984 "Remove invisible part of links and emphasis markers from string S."
8985 (remove-text-properties 0 (length s) org-rm-props s)
8986 (replace-regexp-in-string
8987 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8988 (replace-regexp-in-string
8989 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8990 (org-link-display-format s)
8991 t t) t t))
8993 (defvar org-priority-regexp) ; defined later in the file
8995 (defvar org-after-sorting-entries-or-items-hook nil
8996 "Hook that is run after a bunch of entries or items have been sorted.
8997 When children are sorted, the cursor is in the parent line when this
8998 hook gets called. When a region or a plain list is sorted, the cursor
8999 will be in the first entry of the sorted region/list.")
9001 (defun org-sort-entries
9002 (&optional with-case sorting-type getkey-func compare-func property)
9003 "Sort entries on a certain level of an outline tree.
9004 If there is an active region, the entries in the region are sorted.
9005 Else, if the cursor is before the first entry, sort the top-level items.
9006 Else, the children of the entry at point are sorted.
9008 Sorting can be alphabetically, numerically, by date/time as given by
9009 a time stamp, by a property, by priority order, or by a custom function.
9011 The command prompts for the sorting type unless it has been given to the
9012 function through the SORTING-TYPE argument, which needs to be a character,
9013 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9014 the precise meaning of each character:
9016 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9017 c By creation time, which is assumed to be the first inactive time stamp
9018 at the beginning of a line.
9019 d By deadline date/time.
9020 k By clocking time.
9021 n Numerically, by converting the beginning of the entry/item to a number.
9022 o By order of TODO keywords.
9023 p By priority according to the cookie.
9024 r By the value of a property.
9025 s By scheduled date/time.
9026 t By date/time, either the first active time stamp in the entry, or, if
9027 none exist, by the first inactive one.
9029 Capital letters will reverse the sort order.
9031 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9032 called with point at the beginning of the record. It must return either
9033 a string or a number that should serve as the sorting key for that record.
9035 Comparing entries ignores case by default. However, with an optional argument
9036 WITH-CASE, the sorting considers case as well.
9038 Sorting is done against the visible part of the headlines, it ignores hidden
9039 links.
9041 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9042 (interactive "P")
9043 (let ((case-func (if with-case 'identity 'downcase))
9044 (cmstr
9045 ;; The clock marker is lost when using `sort-subr', let's
9046 ;; store the clocking string.
9047 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9048 (save-excursion
9049 (goto-char org-clock-marker)
9050 (buffer-substring-no-properties (line-beginning-position)
9051 (point)))))
9052 start beg end stars re re2
9053 txt what tmp)
9054 ;; Find beginning and end of region to sort
9055 (cond
9056 ((org-region-active-p)
9057 ;; we will sort the region
9058 (setq end (region-end)
9059 what "region")
9060 (goto-char (region-beginning))
9061 (unless (org-at-heading-p) (outline-next-heading))
9062 (setq start (point)))
9063 ((or (org-at-heading-p)
9064 (ignore-errors (progn (org-back-to-heading) t)))
9065 ;; we will sort the children of the current headline
9066 (org-back-to-heading)
9067 (setq start (point)
9068 end (progn (org-end-of-subtree t t)
9069 (or (bolp) (insert "\n"))
9070 (when (>= (org-back-over-empty-lines) 1)
9071 (forward-line 1))
9072 (point))
9073 what "children")
9074 (goto-char start)
9075 (outline-show-subtree)
9076 (outline-next-heading))
9078 ;; we will sort the top-level entries in this file
9079 (goto-char (point-min))
9080 (or (org-at-heading-p) (outline-next-heading))
9081 (setq start (point))
9082 (goto-char (point-max))
9083 (beginning-of-line 1)
9084 (when (looking-at ".*?\\S-")
9085 ;; File ends in a non-white line
9086 (end-of-line 1)
9087 (insert "\n"))
9088 (setq end (point-max))
9089 (setq what "top-level")
9090 (goto-char start)
9091 (outline-show-all)))
9093 (setq beg (point))
9094 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9096 (looking-at "\\(\\*+\\)")
9097 (setq stars (match-string 1)
9098 re (concat "^" (regexp-quote stars) " +")
9099 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9100 txt (buffer-substring beg end))
9101 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9102 (when (and (not (equal stars "*")) (string-match re2 txt))
9103 (user-error "Region to sort contains a level above the first entry"))
9105 (unless sorting-type
9106 (message
9107 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9108 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9109 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9110 what)
9111 (setq sorting-type (read-char-exclusive))
9113 (unless getkey-func
9114 (and (= (downcase sorting-type) ?f)
9115 (setq getkey-func
9116 (completing-read "Sort using function: "
9117 obarray 'fboundp t nil nil))
9118 (setq getkey-func (intern getkey-func))))
9120 (and (= (downcase sorting-type) ?r)
9121 (not property)
9122 (setq property
9123 (completing-read "Property: "
9124 (mapcar #'list (org-buffer-property-keys t))
9125 nil t))))
9127 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9128 (message "Sorting entries...")
9130 (save-restriction
9131 (narrow-to-region start end)
9132 (let ((dcst (downcase sorting-type))
9133 (case-fold-search nil)
9134 (now (current-time)))
9135 (sort-subr
9136 (/= dcst sorting-type)
9137 ;; This function moves to the beginning character of the "record" to
9138 ;; be sorted.
9139 (lambda nil
9140 (if (re-search-forward re nil t)
9141 (goto-char (match-beginning 0))
9142 (goto-char (point-max))))
9143 ;; This function moves to the last character of the "record" being
9144 ;; sorted.
9145 (lambda nil
9146 (save-match-data
9147 (condition-case nil
9148 (outline-forward-same-level 1)
9149 (error
9150 (goto-char (point-max))))))
9151 ;; This function returns the value that gets sorted against.
9152 (lambda nil
9153 (cond
9154 ((= dcst ?n)
9155 (if (looking-at org-complex-heading-regexp)
9156 (string-to-number (org-sort-remove-invisible (match-string 4)))
9157 nil))
9158 ((= dcst ?a)
9159 (if (looking-at org-complex-heading-regexp)
9160 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9161 nil))
9162 ((= dcst ?k)
9163 (or (get-text-property (point) :org-clock-minutes) 0))
9164 ((= dcst ?t)
9165 (let ((end (save-excursion (outline-next-heading) (point))))
9166 (if (or (re-search-forward org-ts-regexp end t)
9167 (re-search-forward org-ts-regexp-both end t))
9168 (org-time-string-to-seconds (match-string 0))
9169 (float-time now))))
9170 ((= dcst ?c)
9171 (let ((end (save-excursion (outline-next-heading) (point))))
9172 (if (re-search-forward
9173 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9174 end t)
9175 (org-time-string-to-seconds (match-string 0))
9176 (float-time now))))
9177 ((= dcst ?s)
9178 (let ((end (save-excursion (outline-next-heading) (point))))
9179 (if (re-search-forward org-scheduled-time-regexp end t)
9180 (org-time-string-to-seconds (match-string 1))
9181 (float-time now))))
9182 ((= dcst ?d)
9183 (let ((end (save-excursion (outline-next-heading) (point))))
9184 (if (re-search-forward org-deadline-time-regexp end t)
9185 (org-time-string-to-seconds (match-string 1))
9186 (float-time now))))
9187 ((= dcst ?p)
9188 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9189 (string-to-char (match-string 2))
9190 org-default-priority))
9191 ((= dcst ?r)
9192 (or (org-entry-get nil property) ""))
9193 ((= dcst ?o)
9194 (when (looking-at org-complex-heading-regexp)
9195 (let* ((m (match-string 2))
9196 (s (if (member m org-done-keywords) '- '+)))
9197 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9198 ((= dcst ?f)
9199 (if getkey-func
9200 (progn
9201 (setq tmp (funcall getkey-func))
9202 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9203 tmp)
9204 (error "Invalid key function `%s'" getkey-func)))
9205 (t (error "Invalid sorting type `%c'" sorting-type))))
9207 (cond
9208 ((= dcst ?a) 'string<)
9209 ((= dcst ?f) compare-func)
9210 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9211 (run-hooks 'org-after-sorting-entries-or-items-hook)
9212 ;; Reset the clock marker if needed
9213 (when cmstr
9214 (save-excursion
9215 (goto-char start)
9216 (search-forward cmstr nil t)
9217 (move-marker org-clock-marker (point))))
9218 (message "Sorting entries...done")))
9220 ;;; The orgstruct minor mode
9222 ;; Define a minor mode which can be used in other modes in order to
9223 ;; integrate the Org mode structure editing commands.
9225 ;; This is really a hack, because the Org mode structure commands use
9226 ;; keys which normally belong to the major mode. Here is how it
9227 ;; works: The minor mode defines all the keys necessary to operate the
9228 ;; structure commands, but wraps the commands into a function which
9229 ;; tests if the cursor is currently at a headline or a plain list
9230 ;; item. If that is the case, the structure command is used,
9231 ;; temporarily setting many Org mode variables like regular
9232 ;; expressions for filling etc. However, when any of those keys is
9233 ;; used at a different location, function uses `key-binding' to look
9234 ;; up if the key has an associated command in another currently active
9235 ;; keymap (minor modes, major mode, global), and executes that
9236 ;; command. There might be problems if any of the keys is otherwise
9237 ;; used as a prefix key.
9239 (defcustom orgstruct-heading-prefix-regexp ""
9240 "Regexp that matches the custom prefix of Org headlines in
9241 orgstruct(++)-mode."
9242 :group 'org
9243 :version "24.4"
9244 :package-version '(Org . "8.3")
9245 :type 'regexp)
9246 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9248 (defcustom orgstruct-setup-hook nil
9249 "Hook run after orgstruct-mode-map is filled."
9250 :group 'org
9251 :version "24.4"
9252 :package-version '(Org . "8.0")
9253 :type 'hook)
9255 (defvar orgstruct-initialized nil)
9257 (defvar org-local-vars nil
9258 "List of local variables, for use by `orgstruct-mode'.")
9260 ;;;###autoload
9261 (define-minor-mode orgstruct-mode
9262 "Toggle the minor mode `orgstruct-mode'.
9263 This mode is for using Org mode structure commands in other
9264 modes. The following keys behave as if Org mode were active, if
9265 the cursor is on a headline, or on a plain list item (both as
9266 defined by Org mode)."
9267 nil " OrgStruct" (make-sparse-keymap)
9268 (funcall (if orgstruct-mode
9269 'add-to-invisibility-spec
9270 'remove-from-invisibility-spec)
9271 '(outline . t))
9272 (when orgstruct-mode
9273 (org-load-modules-maybe)
9274 (unless orgstruct-initialized
9275 (orgstruct-setup)
9276 (setq orgstruct-initialized t))))
9278 ;;;###autoload
9279 (defun turn-on-orgstruct ()
9280 "Unconditionally turn on `orgstruct-mode'."
9281 (orgstruct-mode 1))
9283 (defvar-local orgstruct-is-++ nil
9284 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9285 (defvar-local org-fb-vars nil)
9286 (defun orgstruct++-mode (&optional arg)
9287 "Toggle `orgstruct-mode', the enhanced version of it.
9288 In addition to setting orgstruct-mode, this also exports all
9289 indentation and autofilling variables from Org mode into the
9290 buffer. It will also recognize item context in multiline items."
9291 (interactive "P")
9292 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9293 (if (< arg 1)
9294 (progn (orgstruct-mode -1)
9295 (dolist (v org-fb-vars)
9296 (set (make-local-variable (car v))
9297 (if (eq (car-safe (cadr v)) 'quote)
9298 (cl-cadadr v)
9299 (nth 1 v)))))
9300 (orgstruct-mode 1)
9301 (setq org-fb-vars nil)
9302 (unless org-local-vars
9303 (setq org-local-vars (org-get-local-variables)))
9304 (let (var val)
9305 (dolist (x org-local-vars)
9306 (when (string-match
9307 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9308 \\|fill-prefix\\|indent-\\)"
9309 (symbol-name (car x)))
9310 (setq var (car x) val (nth 1 x))
9311 (push (list var `(quote ,(eval var))) org-fb-vars)
9312 (set (make-local-variable var)
9313 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9314 (setq-local orgstruct-is-++ t))))
9316 ;;;###autoload
9317 (defun turn-on-orgstruct++ ()
9318 "Unconditionally turn on `orgstruct++-mode'."
9319 (orgstruct++-mode 1))
9321 (defun orgstruct-error ()
9322 "Error when there is no default binding for a structure key."
9323 (interactive)
9324 (funcall (if (fboundp 'user-error)
9325 'user-error
9326 'error)
9327 "This key has no function outside structure elements"))
9329 (defun orgstruct-setup ()
9330 "Setup orgstruct keymap."
9331 (dolist (cell '((org-demote . t)
9332 (org-metaleft . t)
9333 (org-metaright . t)
9334 (org-promote . t)
9335 (org-shiftmetaleft . t)
9336 (org-shiftmetaright . t)
9337 org-backward-element
9338 org-backward-heading-same-level
9339 org-ctrl-c-ret
9340 org-ctrl-c-minus
9341 org-ctrl-c-star
9342 org-cycle
9343 org-force-cycle-archived
9344 org-forward-heading-same-level
9345 org-insert-heading
9346 org-insert-heading-respect-content
9347 org-kill-note-or-show-branches
9348 org-mark-subtree
9349 org-meta-return
9350 org-metadown
9351 org-metaup
9352 org-narrow-to-subtree
9353 org-promote-subtree
9354 org-reveal
9355 org-shiftdown
9356 org-shiftleft
9357 org-shiftmetadown
9358 org-shiftmetaup
9359 org-shiftright
9360 org-shifttab
9361 org-shifttab
9362 org-shiftup
9363 org-show-children
9364 org-show-subtree
9365 org-sort
9366 org-up-element
9367 outline-demote
9368 outline-next-visible-heading
9369 outline-previous-visible-heading
9370 outline-promote
9371 outline-up-heading))
9372 (let ((f (or (car-safe cell) cell))
9373 (disable-when-heading-prefix (cdr-safe cell)))
9374 (when (fboundp f)
9375 (let ((new-bindings))
9376 (dolist (binding (nconc (where-is-internal f org-mode-map)
9377 (where-is-internal f outline-mode-map)))
9378 (push binding new-bindings)
9379 ;; TODO use local-function-key-map
9380 (dolist (rep '(("<tab>" . "TAB")
9381 ("<return>" . "RET")
9382 ("<escape>" . "ESC")
9383 ("<delete>" . "DEL")))
9384 (setq binding (read-kbd-macro
9385 (let ((case-fold-search))
9386 (replace-regexp-in-string
9387 (regexp-quote (cdr rep))
9388 (car rep)
9389 (key-description binding)))))
9390 (cl-pushnew binding new-bindings :test 'equal)))
9391 (dolist (binding new-bindings)
9392 (let ((key (lookup-key orgstruct-mode-map binding)))
9393 (when (or (not key) (numberp key))
9394 (ignore-errors
9395 (org-defkey orgstruct-mode-map
9396 binding
9397 (orgstruct-make-binding
9398 f binding disable-when-heading-prefix))))))))))
9399 (run-hooks 'orgstruct-setup-hook))
9401 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9402 "Create a function for binding in the structure minor mode.
9403 FUN is the command to call inside a table. KEY is the key that
9404 should be checked in for a command to execute outside of tables.
9405 Non-nil `disable-when-heading-prefix' means to disable the command
9406 if `orgstruct-heading-prefix-regexp' is not empty."
9407 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9408 (let ((nname name)
9409 (i 0))
9410 (while (fboundp (intern nname))
9411 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9412 (setq name (intern nname)))
9413 (eval
9414 (let ((bindings '((org-heading-regexp
9415 (concat "^"
9416 orgstruct-heading-prefix-regexp
9417 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9418 (org-outline-regexp
9419 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9420 (org-outline-regexp-bol
9421 (concat "^" org-outline-regexp))
9422 (outline-regexp org-outline-regexp)
9423 (outline-heading-end-regexp "\n")
9424 (outline-level 'org-outline-level)
9425 (outline-heading-alist))))
9426 `(defun ,name (arg)
9427 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9428 "Outside of structure, run the binding of `"
9429 (key-description key) "'."
9430 (when disable-when-heading-prefix
9431 (concat
9432 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9433 "back to the default binding due to limitations of Org's implementation of\n"
9434 "`" (symbol-name fun) "'.")))
9435 (interactive "p")
9436 (let* ((disable
9437 ,(and disable-when-heading-prefix
9438 '(not (string= orgstruct-heading-prefix-regexp ""))))
9439 (fallback
9440 (or disable
9441 (not
9442 (let* ,bindings
9443 (org-context-p 'headline 'item
9444 ,(when (memq fun
9445 '(org-insert-heading
9446 org-insert-heading-respect-content
9447 org-meta-return))
9448 '(when orgstruct-is-++
9449 'item-body))))))))
9450 (if fallback
9451 (let* ((orgstruct-mode)
9452 (binding
9453 (let ((key ,key))
9454 (catch 'exit
9455 (dolist
9456 (rep
9457 '(nil
9458 ("<\\([^>]*\\)tab>" . "\\1TAB")
9459 ("<\\([^>]*\\)return>" . "\\1RET")
9460 ("<\\([^>]*\\)escape>" . "\\1ESC")
9461 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9462 nil)
9463 (when rep
9464 (setq key (read-kbd-macro
9465 (let ((case-fold-search))
9466 (replace-regexp-in-string
9467 (car rep)
9468 (cdr rep)
9469 (key-description key))))))
9470 (when (key-binding key)
9471 (throw 'exit (key-binding key))))))))
9472 (if (keymapp binding)
9473 (org-set-transient-map binding)
9474 (let ((func (or binding
9475 (unless disable
9476 'orgstruct-error))))
9477 (when func
9478 (call-interactively func)))))
9479 (org-run-like-in-org-mode
9480 (lambda ()
9481 (interactive)
9482 (let* ,bindings
9483 (call-interactively ',fun)))))))))
9484 name))
9486 (defun org-contextualize-keys (alist contexts)
9487 "Return valid elements in ALIST depending on CONTEXTS.
9489 `org-agenda-custom-commands' or `org-capture-templates' are the
9490 values used for ALIST, and `org-agenda-custom-commands-contexts'
9491 or `org-capture-templates-contexts' are the associated contexts
9492 definitions."
9493 (let ((contexts
9494 ;; normalize contexts
9495 (mapcar
9496 (lambda(c) (cond ((listp (cadr c))
9497 (list (car c) (car c) (nth 1 c)))
9498 ((string= "" (cadr c))
9499 (list (car c) (car c) (nth 2 c)))
9500 (t c)))
9501 contexts))
9502 (a alist) r s)
9503 ;; loop over all commands or templates
9504 (dolist (c a)
9505 (let (vrules repl)
9506 (cond
9507 ((not (assoc (car c) contexts))
9508 (push c r))
9509 ((and (assoc (car c) contexts)
9510 (setq vrules (org-contextualize-validate-key
9511 (car c) contexts)))
9512 (mapc (lambda (vr)
9513 (unless (equal (car vr) (cadr vr))
9514 (setq repl vr)))
9515 vrules)
9516 (if (not repl) (push c r)
9517 (push (cadr repl) s)
9518 (push
9519 (cons (car c)
9520 (cdr (or (assoc (cadr repl) alist)
9521 (error "Undefined key `%s' as contextual replacement for `%s'"
9522 (cadr repl) (car c)))))
9523 r))))))
9524 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9525 (delq
9527 (delete-dups
9528 (mapcar (lambda (x)
9529 (let ((tpl (car x)))
9530 (unless (delq
9532 (mapcar (lambda (y)
9533 (equal y tpl))
9535 x)))
9536 (reverse r))))))
9538 (defun org-contextualize-validate-key (key contexts)
9539 "Check CONTEXTS for agenda or capture KEY."
9540 (let (res)
9541 (dolist (r contexts)
9542 (dolist (rr (car (last r)))
9543 (when
9544 (and (equal key (car r))
9545 (if (functionp rr) (funcall rr)
9546 (or (and (eq (car rr) 'in-file)
9547 (buffer-file-name)
9548 (string-match (cdr rr) (buffer-file-name)))
9549 (and (eq (car rr) 'in-mode)
9550 (string-match (cdr rr) (symbol-name major-mode)))
9551 (and (eq (car rr) 'in-buffer)
9552 (string-match (cdr rr) (buffer-name)))
9553 (when (and (eq (car rr) 'not-in-file)
9554 (buffer-file-name))
9555 (not (string-match (cdr rr) (buffer-file-name))))
9556 (when (eq (car rr) 'not-in-mode)
9557 (not (string-match (cdr rr) (symbol-name major-mode))))
9558 (when (eq (car rr) 'not-in-buffer)
9559 (not (string-match (cdr rr) (buffer-name)))))))
9560 (push r res))))
9561 (delete-dups (delq nil res))))
9563 (defun org-context-p (&rest contexts)
9564 "Check if local context is any of CONTEXTS.
9565 Possible values in the list of contexts are `table', `headline', and `item'."
9566 (let ((pos (point)))
9567 (goto-char (point-at-bol))
9568 (prog1 (or (and (memq 'table contexts)
9569 (looking-at "[ \t]*|"))
9570 (and (memq 'headline contexts)
9571 (looking-at org-outline-regexp))
9572 (and (memq 'item contexts)
9573 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9574 (and (memq 'item-body contexts)
9575 (org-in-item-p)))
9576 (goto-char pos))))
9578 (defconst org-unique-local-variables
9579 '(org-element--cache
9580 org-element--cache-objects
9581 org-element--cache-sync-keys
9582 org-element--cache-sync-requests
9583 org-element--cache-sync-timer)
9584 "List of local variables that cannot be transferred to another buffer.")
9586 (defun org-get-local-variables ()
9587 "Return a list of all local variables in an Org mode buffer."
9588 (delq nil
9589 (mapcar
9590 (lambda (x)
9591 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9592 (name (car binding)))
9593 (and (not (get name 'org-state))
9594 (not (memq name org-unique-local-variables))
9595 (string-match-p
9596 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9597 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9598 (symbol-name name))
9599 binding)))
9600 (with-temp-buffer
9601 (org-mode)
9602 (buffer-local-variables)))))
9604 (defun org-clone-local-variables (from-buffer &optional regexp)
9605 "Clone local variables from FROM-BUFFER.
9606 Optional argument REGEXP selects variables to clone."
9607 (dolist (pair (buffer-local-variables from-buffer))
9608 (let ((name (car pair)))
9609 (when (and (symbolp name)
9610 (not (memq name org-unique-local-variables))
9611 (or (null regexp) (string-match regexp (symbol-name name))))
9612 (set (make-local-variable name) (cdr pair))))))
9614 ;;;###autoload
9615 (defun org-run-like-in-org-mode (cmd)
9616 "Run a command, pretending that the current buffer is in Org mode.
9617 This will temporarily bind local variables that are typically bound in
9618 Org mode to the values they have in Org mode, and then interactively
9619 call CMD."
9620 (org-load-modules-maybe)
9621 (unless org-local-vars
9622 (setq org-local-vars (org-get-local-variables)))
9623 (let (binds)
9624 (dolist (var org-local-vars)
9625 (when (or (not (boundp (car var)))
9626 (eq (symbol-value (car var))
9627 (default-value (car var))))
9628 (push (list (car var) `(quote ,(cadr var))) binds)))
9629 (eval `(let ,binds
9630 (call-interactively (quote ,cmd))))))
9632 (defun org-get-category (&optional pos force-refresh)
9633 "Get the category applying to position POS."
9634 (save-match-data
9635 (when force-refresh (org-refresh-category-properties))
9636 (let ((pos (or pos (point))))
9637 (or (get-text-property pos 'org-category)
9638 (progn (org-refresh-category-properties)
9639 (get-text-property pos 'org-category))))))
9641 ;;; Refresh properties
9643 (defun org-refresh-properties (dprop tprop)
9644 "Refresh buffer text properties.
9645 DPROP is the drawer property and TPROP is either the
9646 corresponding text property to set, or an alist with each element
9647 being a text property (as a symbol) and a function to apply to
9648 the value of the drawer property."
9649 (let* ((case-fold-search t)
9650 (inhibit-read-only t)
9651 (inherit? (org-property-inherit-p dprop))
9652 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9653 (global (and inherit? (org--property-global-value dprop nil))))
9654 (org-with-silent-modifications
9655 (org-with-point-at 1
9656 ;; Set global values (e.g., values defined through
9657 ;; "#+PROPERTY:" keywords) to the whole buffer.
9658 (when global (put-text-property (point-min) (point-max) tprop global))
9659 ;; Set local values.
9660 (while (re-search-forward property-re nil t)
9661 (when (org-at-property-p)
9662 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9663 (outline-next-heading))))))
9665 (defun org-refresh-property (tprop p &optional inherit)
9666 "Refresh the buffer text property TPROP from the drawer property P.
9667 The refresh happens only for the current headline, or the whole
9668 sub-tree if optional argument INHERIT is non-nil."
9669 (unless (org-before-first-heading-p)
9670 (save-excursion
9671 (org-back-to-heading t)
9672 (let ((start (point))
9673 (end (save-excursion
9674 (if inherit (org-end-of-subtree t t)
9675 (or (outline-next-heading) (point-max))))))
9676 (if (symbolp tprop)
9677 ;; TPROP is a text property symbol.
9678 (put-text-property start end tprop p)
9679 ;; TPROP is an alist with (property . function) elements.
9680 (pcase-dolist (`(,prop . ,f) tprop)
9681 (put-text-property start end prop (funcall f p))))))))
9683 (defun org-refresh-category-properties ()
9684 "Refresh category text properties in the buffer."
9685 (let ((case-fold-search t)
9686 (inhibit-read-only t)
9687 (default-category
9688 (cond ((null org-category)
9689 (if buffer-file-name
9690 (file-name-sans-extension
9691 (file-name-nondirectory buffer-file-name))
9692 "???"))
9693 ((symbolp org-category) (symbol-name org-category))
9694 (t org-category))))
9695 (org-with-silent-modifications
9696 (org-with-wide-buffer
9697 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9698 ;; This is the default category for the buffer. If none is
9699 ;; found, fall-back to `org-category' or buffer file name.
9700 (put-text-property
9701 (point-min) (point-max)
9702 'org-category
9703 (catch 'buffer-category
9704 (goto-char (point-max))
9705 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9706 (let ((element (org-element-at-point)))
9707 (when (eq (org-element-type element) 'keyword)
9708 (throw 'buffer-category
9709 (org-element-property :value element)))))
9710 default-category))
9711 ;; Set sub-tree specific categories.
9712 (goto-char (point-min))
9713 (let ((regexp (org-re-property "CATEGORY")))
9714 (while (re-search-forward regexp nil t)
9715 (let ((value (match-string-no-properties 3)))
9716 (when (org-at-property-p)
9717 (put-text-property
9718 (save-excursion (org-back-to-heading t) (point))
9719 (save-excursion (org-end-of-subtree t t) (point))
9720 'org-category
9721 value)))))))))
9723 (defun org-refresh-stats-properties ()
9724 "Refresh stats text properties in the buffer."
9725 (let (stats)
9726 (org-with-silent-modifications
9727 (org-with-wide-buffer
9728 (goto-char (point-min))
9729 (while (re-search-forward
9730 (concat org-outline-regexp-bol ".*"
9731 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9732 nil t)
9733 (setq stats (cond ((equal (match-string 3) "0") 0)
9734 ((match-string 2)
9735 (/ (* (string-to-number (match-string 2)) 100)
9736 (string-to-number (match-string 3))))
9737 (t (string-to-number (match-string 1)))))
9738 (org-back-to-heading t)
9739 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9740 'org-stats stats))))))
9742 (defun org-refresh-effort-properties ()
9743 "Refresh effort properties"
9744 (org-refresh-properties
9745 org-effort-property
9746 '((effort . identity)
9747 (effort-minutes . org-duration-string-to-minutes))))
9749 ;;;; Link Stuff
9751 ;;; Link abbreviations
9753 (defun org-link-expand-abbrev (link)
9754 "Apply replacements as defined in `org-link-abbrev-alist'."
9755 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9756 (let* ((key (match-string 1 link))
9757 (as (or (assoc key org-link-abbrev-alist-local)
9758 (assoc key org-link-abbrev-alist)))
9759 (tag (and (match-end 2) (match-string 3 link)))
9760 rpl)
9761 (if (not as)
9762 link
9763 (setq rpl (cdr as))
9764 (cond
9765 ((symbolp rpl) (funcall rpl tag))
9766 ((string-match "%(\\([^)]+\\))" rpl)
9767 (replace-match
9768 (save-match-data
9769 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9770 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9771 ((string-match "%h" rpl)
9772 (replace-match (url-hexify-string (or tag "")) t t rpl))
9773 (t (concat rpl tag)))))
9774 link))
9776 ;;; Storing and inserting links
9778 (defvar org-insert-link-history nil
9779 "Minibuffer history for links inserted with `org-insert-link'.")
9781 (defvar org-stored-links nil
9782 "Contains the links stored with `org-store-link'.")
9784 (defvar org-store-link-plist nil
9785 "Plist with info about the most recently link created with `org-store-link'.")
9787 (defun org-store-link-functions ()
9788 "Return a list of functions that are called to create and store a link.
9789 The functions defined in the :store property of
9790 `org-link-parameters'.
9792 Each function will be called in turn until one returns a non-nil
9793 value. Each function should check if it is responsible for
9794 creating this link (for example by looking at the major mode).
9795 If not, it must exit and return nil. If yes, it should return
9796 a non-nil value after calling `org-store-link-props' with a list
9797 of properties and values. Special properties are:
9799 :type The link prefix, like \"http\". This must be given.
9800 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9801 This is obligatory as well.
9802 :description Optional default description for the second pair
9803 of brackets in an Org mode link. The user can still change
9804 this when inserting this link into an Org mode buffer.
9806 In addition to these, any additional properties can be specified
9807 and then used in capture templates."
9808 (cl-loop for link in org-link-parameters
9809 with store-func
9810 do (setq store-func (org-link-get-parameter (car link) :store))
9811 if store-func
9812 collect store-func))
9814 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9815 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9817 ;;;###autoload
9818 (defun org-store-link (arg)
9819 "Store an org-link to the current location.
9820 \\<org-mode-map>
9821 This link is added to `org-stored-links' and can later be inserted
9822 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9824 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9825 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9826 For file links, ARG negates `org-context-in-file-links'.
9828 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9829 skipping storing functions that are not
9830 part of Org core.
9832 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9833 prefix ARG forces storing a link for each line in the
9834 active region."
9835 (interactive "P")
9836 (org-load-modules-maybe)
9837 (if (and (equal arg '(64)) (org-region-active-p))
9838 (save-excursion
9839 (let ((end (region-end)))
9840 (goto-char (region-beginning))
9841 (set-mark (point))
9842 (while (< (point-at-eol) end)
9843 (move-end-of-line 1) (activate-mark)
9844 (let (current-prefix-arg)
9845 (call-interactively 'org-store-link))
9846 (move-beginning-of-line 2)
9847 (set-mark (point)))))
9848 (setq org-store-link-plist nil)
9849 (let (link cpltxt desc description search
9850 txt custom-id agenda-link sfuns sfunsn)
9851 (cond
9853 ;; Store a link using an external link type
9854 ((and (not (equal arg '(16)))
9855 (setq sfuns
9856 (delq
9857 nil (mapcar (lambda (f)
9858 (let (fs) (if (funcall f) (push f fs))))
9859 (org-store-link-functions)))
9860 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9861 (or (and (cdr sfuns)
9862 (funcall (intern
9863 (completing-read
9864 "Which function for creating the link? "
9865 sfunsn nil t (car sfunsn)))))
9866 (funcall (caar sfuns)))
9867 (setq link (plist-get org-store-link-plist :link)
9868 desc (or (plist-get org-store-link-plist
9869 :description)
9870 link))))
9872 ;; Store a link from a source code buffer.
9873 ((org-src-edit-buffer-p)
9874 (let ((coderef-format (org-src-coderef-format)))
9875 (cond ((save-excursion
9876 (beginning-of-line)
9877 (looking-at (org-src-coderef-regexp coderef-format)))
9878 (setq link (format "(%s)" (match-string-no-properties 3))))
9879 ((called-interactively-p 'any)
9880 (let ((label (read-string "Code line label: ")))
9881 (end-of-line)
9882 (setq link (format coderef-format label))
9883 (let ((gc (- 79 (length link))))
9884 (if (< (current-column) gc)
9885 (org-move-to-column gc t)
9886 (insert " ")))
9887 (insert link)
9888 (setq link (concat "(" label ")"))
9889 (setq desc nil)))
9890 (t (setq link nil)))))
9892 ;; We are in the agenda, link to referenced location
9893 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9894 (let ((m (or (get-text-property (point) 'org-hd-marker)
9895 (get-text-property (point) 'org-marker))))
9896 (when m
9897 (org-with-point-at m
9898 (setq agenda-link
9899 (if (called-interactively-p 'any)
9900 (call-interactively 'org-store-link)
9901 (org-store-link nil)))))))
9903 ((eq major-mode 'calendar-mode)
9904 (let ((cd (calendar-cursor-to-date)))
9905 (setq link
9906 (format-time-string
9907 (car org-time-stamp-formats)
9908 (apply 'encode-time
9909 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9910 nil nil nil))))
9911 (org-store-link-props :type "calendar" :date cd)))
9913 ((eq major-mode 'help-mode)
9914 (setq link (concat "help:" (save-excursion
9915 (goto-char (point-min))
9916 (looking-at "^[^ ]+")
9917 (match-string 0))))
9918 (org-store-link-props :type "help"))
9920 ((eq major-mode 'w3-mode)
9921 (setq cpltxt (if (and (buffer-name)
9922 (not (string-match "Untitled" (buffer-name))))
9923 (buffer-name)
9924 (url-view-url t))
9925 link (url-view-url t))
9926 (org-store-link-props :type "w3" :url (url-view-url t)))
9928 ((eq major-mode 'image-mode)
9929 (setq cpltxt (concat "file:"
9930 (abbreviate-file-name buffer-file-name))
9931 link cpltxt)
9932 (org-store-link-props :type "image" :file buffer-file-name))
9934 ;; In dired, store a link to the file of the current line
9935 ((derived-mode-p 'dired-mode)
9936 (let ((file (dired-get-filename nil t)))
9937 (setq file (if file
9938 (abbreviate-file-name
9939 (expand-file-name (dired-get-filename nil t)))
9940 ;; otherwise, no file so use current directory.
9941 default-directory))
9942 (setq cpltxt (concat "file:" file)
9943 link cpltxt)))
9945 ((setq search (run-hook-with-args-until-success
9946 'org-create-file-search-functions))
9947 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9948 "::" search))
9949 (setq cpltxt (or description link)))
9951 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9952 (org-with-limited-levels
9953 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9954 (cond
9955 ;; Store a link using the target at point
9956 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9957 (setq cpltxt
9958 (concat "file:"
9959 (abbreviate-file-name
9960 (buffer-file-name (buffer-base-buffer)))
9961 "::" (match-string 1))
9962 link cpltxt))
9963 ((and (featurep 'org-id)
9964 (or (eq org-id-link-to-org-use-id t)
9965 (and (called-interactively-p 'any)
9966 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9967 (and (eq org-id-link-to-org-use-id
9968 'create-if-interactive-and-no-custom-id)
9969 (not custom-id))))
9970 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9971 ;; Store a link using the ID at point
9972 (setq link (condition-case nil
9973 (prog1 (org-id-store-link)
9974 (setq desc (or (plist-get org-store-link-plist
9975 :description)
9976 "")))
9977 (error
9978 ;; Probably before first headline, link only to file
9979 (concat "file:"
9980 (abbreviate-file-name
9981 (buffer-file-name (buffer-base-buffer))))))))
9983 ;; Just link to current headline
9984 (setq cpltxt (concat "file:"
9985 (abbreviate-file-name
9986 (buffer-file-name (buffer-base-buffer)))))
9987 ;; Add a context search string
9988 (when (org-xor org-context-in-file-links arg)
9989 (let* ((element (org-element-at-point))
9990 (name (org-element-property :name element)))
9991 (setq txt (cond
9992 ((org-at-heading-p) nil)
9993 (name)
9994 ((org-region-active-p)
9995 (buffer-substring (region-beginning) (region-end)))))
9996 (when (or (null txt) (string-match "\\S-" txt))
9997 (setq cpltxt
9998 (concat cpltxt "::"
9999 (condition-case nil
10000 (org-make-org-heading-search-string txt)
10001 (error "")))
10002 desc (or name
10003 (nth 4 (ignore-errors (org-heading-components)))
10004 "NONE")))))
10005 (when (string-match "::\\'" cpltxt)
10006 (setq cpltxt (substring cpltxt 0 -2)))
10007 (setq link cpltxt)))))
10009 ((buffer-file-name (buffer-base-buffer))
10010 ;; Just link to this file here.
10011 (setq cpltxt (concat "file:"
10012 (abbreviate-file-name
10013 (buffer-file-name (buffer-base-buffer)))))
10014 ;; Add a context string.
10015 (when (org-xor org-context-in-file-links arg)
10016 (setq txt (if (org-region-active-p)
10017 (buffer-substring (region-beginning) (region-end))
10018 (buffer-substring (point-at-bol) (point-at-eol))))
10019 ;; Only use search option if there is some text.
10020 (when (string-match "\\S-" txt)
10021 (setq cpltxt
10022 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10023 desc "NONE")))
10024 (setq link cpltxt))
10026 ((called-interactively-p 'interactive)
10027 (user-error "No method for storing a link from this buffer"))
10029 (t (setq link nil)))
10031 ;; We're done setting link and desc, clean up
10032 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10033 (setq link (or link cpltxt)
10034 desc (or desc cpltxt))
10035 (cond ((not desc))
10036 ((equal desc "NONE") (setq desc nil))
10037 (t (setq desc
10038 (replace-regexp-in-string
10039 org-bracket-link-analytic-regexp
10040 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10041 desc))))
10042 ;; Return the link
10043 (if (not (and (or (called-interactively-p 'any)
10044 executing-kbd-macro)
10045 link))
10046 (or agenda-link (and link (org-make-link-string link desc)))
10047 (push (list link desc) org-stored-links)
10048 (message "Stored: %s" (or desc link))
10049 (when custom-id
10050 (setq link (concat "file:" (abbreviate-file-name
10051 (buffer-file-name)) "::#" custom-id))
10052 (push (list link desc) org-stored-links))
10053 (car org-stored-links)))))
10055 (defun org-store-link-props (&rest plist)
10056 "Store link properties, extract names, addresses and dates."
10057 (let ((x (plist-get plist :from)))
10058 (when x
10059 (let ((adr (mail-extract-address-components x)))
10060 (setq plist (plist-put plist :fromname (car adr)))
10061 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10062 (let ((x (plist-get plist :to)))
10063 (when x
10064 (let ((adr (mail-extract-address-components x)))
10065 (setq plist (plist-put plist :toname (car adr)))
10066 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10067 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10068 (when x
10069 (setq plist (plist-put plist :date-timestamp
10070 (format-time-string
10071 (org-time-stamp-format t) x)))
10072 (setq plist (plist-put plist :date-timestamp-inactive
10073 (format-time-string
10074 (org-time-stamp-format t t) x)))))
10075 (let ((from (plist-get plist :from))
10076 (to (plist-get plist :to)))
10077 (when (and from to org-from-is-user-regexp)
10078 (setq plist
10079 (plist-put plist :fromto
10080 (if (string-match org-from-is-user-regexp from)
10081 (concat "to %t")
10082 (concat "from %f"))))))
10083 (setq org-store-link-plist plist))
10085 (defun org-add-link-props (&rest plist)
10086 "Add these properties to the link property list."
10087 (let (key value)
10088 (while plist
10089 (setq key (pop plist) value (pop plist))
10090 (setq org-store-link-plist
10091 (plist-put org-store-link-plist key value)))))
10093 (defun org-email-link-description (&optional fmt)
10094 "Return the description part of an email link.
10095 This takes information from `org-store-link-plist' and formats it
10096 according to FMT (default from `org-email-link-description-format')."
10097 (setq fmt (or fmt org-email-link-description-format))
10098 (let* ((p org-store-link-plist)
10099 (to (plist-get p :toaddress))
10100 (from (plist-get p :fromaddress))
10101 (table
10102 (list
10103 (cons "%c" (plist-get p :fromto))
10104 (cons "%F" (plist-get p :from))
10105 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10106 (cons "%T" (plist-get p :to))
10107 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10108 (cons "%s" (plist-get p :subject))
10109 (cons "%d" (plist-get p :date))
10110 (cons "%m" (plist-get p :message-id)))))
10111 (when (string-match "%c" fmt)
10112 ;; Check if the user wrote this message
10113 (if (and org-from-is-user-regexp from to
10114 (save-match-data (string-match org-from-is-user-regexp from)))
10115 (setq fmt (replace-match "to %t" t t fmt))
10116 (setq fmt (replace-match "from %f" t t fmt))))
10117 (org-replace-escapes fmt table)))
10119 (defun org-make-org-heading-search-string (&optional string)
10120 "Make search string for the current headline or STRING."
10121 (let ((s (or string
10122 (and (derived-mode-p 'org-mode)
10123 (save-excursion
10124 (org-back-to-heading t)
10125 (org-element-property :raw-value (org-element-at-point))))))
10126 (lines org-context-in-file-links))
10127 (or string (setq s (concat "*" s))) ; Add * for headlines
10128 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10129 (when (and string (integerp lines) (> lines 0))
10130 (let ((slines (org-split-string s "\n")))
10131 (when (< lines (length slines))
10132 (setq s (mapconcat
10133 'identity
10134 (reverse (nthcdr (- (length slines) lines)
10135 (reverse slines))) "\n")))))
10136 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10138 (defun org-make-link-string (link &optional description)
10139 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10140 (unless (org-string-nw-p link) (error "Empty link"))
10141 (let ((uri (cond ((string-match org-link-types-re link)
10142 (concat (match-string 1 link)
10143 (org-link-escape (substring link (match-end 1)))))
10144 ;; For readability, url-encode internal links only
10145 ;; when absolutely needed (i.e, when they contain
10146 ;; square brackets). File links however, are
10147 ;; encoded since, e.g., spaces are significant.
10148 ((or (file-name-absolute-p link)
10149 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10150 (org-link-escape link))
10151 (t link)))
10152 (description
10153 (and (org-string-nw-p description)
10154 ;; Remove brackets from description, as they are fatal.
10155 (replace-regexp-in-string
10156 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10157 (org-trim description)))))
10158 (format "[[%s]%s]"
10160 (if description (format "[%s]" description) ""))))
10162 (defconst org-link-escape-chars
10163 ;;%20 %5B %5D %25
10164 '(?\s ?\[ ?\] ?%)
10165 "List of characters that should be escaped in a link when stored to Org.
10166 This is the list that is used for internal purposes.")
10168 (defun org-link-escape (text &optional table merge)
10169 "Return percent escaped representation of TEXT.
10170 TEXT is a string with the text to escape.
10171 Optional argument TABLE is a list with characters that should be
10172 escaped. When nil, `org-link-escape-chars' is used.
10173 If optional argument MERGE is set, merge TABLE into
10174 `org-link-escape-chars'."
10175 (let ((characters-to-encode
10176 (cond ((null table) org-link-escape-chars)
10177 (merge (append org-link-escape-chars table))
10178 (t table))))
10179 (mapconcat
10180 (lambda (c)
10181 (if (or (memq c characters-to-encode)
10182 (and org-url-hexify-p (or (< c 32) (> c 126))))
10183 (mapconcat (lambda (e) (format "%%%.2X" e))
10184 (or (encode-coding-char c 'utf-8)
10185 (error "Unable to percent escape character: %c" c))
10187 (char-to-string c)))
10188 text "")))
10190 (defun org-link-unescape (str)
10191 "Unhex hexified Unicode parts in string STR.
10192 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10193 reciprocal of `org-link-escape', which see."
10194 (if (org-string-nw-p str)
10195 (replace-regexp-in-string
10196 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10197 str))
10199 (defun org-link-unescape-compound (hex)
10200 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10201 Note: this function also decodes single byte encodings like
10202 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10203 (save-match-data
10204 (let* ((bytes (cdr (split-string hex "%")))
10205 (ret "")
10206 (eat 0)
10207 (sum 0))
10208 (while bytes
10209 (let* ((val (string-to-number (pop bytes) 16))
10210 (shift-xor
10211 (if (= 0 eat)
10212 (cond
10213 ((>= val 252) (cons 6 252))
10214 ((>= val 248) (cons 5 248))
10215 ((>= val 240) (cons 4 240))
10216 ((>= val 224) (cons 3 224))
10217 ((>= val 192) (cons 2 192))
10218 (t (cons 0 0)))
10219 (cons 6 128))))
10220 (when (>= val 192) (setq eat (car shift-xor)))
10221 (setq val (logxor val (cdr shift-xor)))
10222 (setq sum (+ (lsh sum (car shift-xor)) val))
10223 (when (> eat 0) (setq eat (- eat 1)))
10224 (cond
10225 ((= 0 eat) ;multi byte
10226 (setq ret (concat ret (char-to-string sum)))
10227 (setq sum 0))
10228 ((not bytes) ; single byte(s)
10229 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10230 ret)))
10232 (defun org-link-unescape-single-byte-sequence (hex)
10233 "Unhexify hex-encoded single byte character sequences."
10234 (mapconcat (lambda (byte)
10235 (char-to-string (string-to-number byte 16)))
10236 (cdr (split-string hex "%")) ""))
10238 (defun org-xor (a b)
10239 "Exclusive or."
10240 (if a (not b) b))
10242 (defun org-fixup-message-id-for-http (s)
10243 "Replace special characters in a message id, so it can be used in an http query."
10244 (when (string-match "%" s)
10245 (setq s (mapconcat (lambda (c)
10246 (if (eq c ?%)
10247 "%25"
10248 (char-to-string c)))
10249 s "")))
10250 (while (string-match "<" s)
10251 (setq s (replace-match "%3C" t t s)))
10252 (while (string-match ">" s)
10253 (setq s (replace-match "%3E" t t s)))
10254 (while (string-match "@" s)
10255 (setq s (replace-match "%40" t t s)))
10258 (defun org-link-prettify (link)
10259 "Return a human-readable representation of LINK.
10260 The car of LINK must be a raw link.
10261 The cdr of LINK must be either a link description or nil."
10262 (let ((desc (or (cadr link) "<no description>")))
10263 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10264 "<" (car link) ">")))
10266 ;;;###autoload
10267 (defun org-insert-link-global ()
10268 "Insert a link like Org mode does.
10269 This command can be called in any mode to insert a link in Org syntax."
10270 (interactive)
10271 (org-load-modules-maybe)
10272 (org-run-like-in-org-mode 'org-insert-link))
10274 (defun org-insert-all-links (arg &optional pre post)
10275 "Insert all links in `org-stored-links'.
10276 When a universal prefix, do not delete the links from `org-stored-links'.
10277 When `ARG' is a number, insert the last N link(s).
10278 `PRE' and `POST' are optional arguments to define a string to
10279 prepend or to append."
10280 (interactive "P")
10281 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10282 (links (copy-sequence org-stored-links))
10283 (pr (or pre "- "))
10284 (po (or post "\n"))
10285 (cnt 1) l)
10286 (if (null org-stored-links)
10287 (message "No link to insert")
10288 (while (and (or (listp arg) (>= arg cnt))
10289 (setq l (if (listp arg)
10290 (pop links)
10291 (pop org-stored-links))))
10292 (setq cnt (1+ cnt))
10293 (insert pr)
10294 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10295 (insert po)))))
10297 (defun org-insert-last-stored-link (arg)
10298 "Insert the last link stored in `org-stored-links'."
10299 (interactive "p")
10300 (org-insert-all-links arg "" "\n"))
10302 (defun org-link-fontify-links-to-this-file ()
10303 "Fontify links to the current file in `org-stored-links'."
10304 (let ((f (buffer-file-name)) a b)
10305 (setq a (mapcar (lambda(l)
10306 (let ((ll (car l)))
10307 (when (and (string-match "^file:\\(.+\\)::" ll)
10308 (equal f (expand-file-name (match-string 1 ll))))
10309 ll)))
10310 org-stored-links))
10311 (when (featurep 'org-id)
10312 (setq b (mapcar (lambda(l)
10313 (let ((ll (car l)))
10314 (when (and (string-match "^id:\\(.+\\)$" ll)
10315 (equal f (expand-file-name
10316 (or (org-id-find-id-file
10317 (match-string 1 ll)) ""))))
10318 ll)))
10319 org-stored-links)))
10320 (mapcar (lambda(l)
10321 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10322 (delq nil (append a b)))))
10324 (defvar org--links-history nil)
10325 (defun org-insert-link (&optional complete-file link-location default-description)
10326 "Insert a link. At the prompt, enter the link.
10328 Completion can be used to insert any of the link protocol prefixes in use.
10330 The history can be used to select a link previously stored with
10331 `org-store-link'. When the empty string is entered (i.e. if you just
10332 press `RET' at the prompt), the link defaults to the most recently
10333 stored link. As `SPC' triggers completion in the minibuffer, you need to
10334 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10336 You will also be prompted for a description, and if one is given, it will
10337 be displayed in the buffer instead of the link.
10339 If there is already a link at point, this command will allow you to edit
10340 link and description parts.
10342 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10343 file name can be
10344 selected using completion. The path to the file will be relative to the
10345 current directory if the file is in the current directory or a subdirectory.
10346 Otherwise, the link will be the absolute path as completed in the minibuffer
10347 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10348 option `org-link-file-path-type'.
10350 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10351 absolute path even if the file is in
10352 the current directory or below.
10354 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10355 prefix negates `org-keep-stored-link-after-insertion'.
10357 If `org-make-link-description-function' is non-nil, this function will be
10358 called with the link target, and the result will be the default
10359 link description.
10361 If the LINK-LOCATION parameter is non-nil, this value will be used as
10362 the link location instead of reading one interactively.
10364 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10365 as the default description."
10366 (interactive "P")
10367 (let* ((wcf (current-window-configuration))
10368 (origbuf (current-buffer))
10369 (region (when (org-region-active-p)
10370 (buffer-substring (region-beginning) (region-end))))
10371 (remove (and region (list (region-beginning) (region-end))))
10372 (desc region)
10373 (link link-location)
10374 (abbrevs org-link-abbrev-alist-local)
10375 entry all-prefixes auto-desc)
10376 (cond
10377 (link-location) ; specified by arg, just use it.
10378 ((org-in-regexp org-bracket-link-regexp 1)
10379 ;; We do have a link at point, and we are going to edit it.
10380 (setq remove (list (match-beginning 0) (match-end 0)))
10381 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10382 (setq link (read-string "Link: "
10383 (org-link-unescape
10384 (match-string-no-properties 1)))))
10385 ((or (org-in-regexp org-angle-link-re)
10386 (org-in-regexp org-plain-link-re))
10387 ;; Convert to bracket link
10388 (setq remove (list (match-beginning 0) (match-end 0))
10389 link (read-string "Link: "
10390 (org-unbracket-string "<" ">" (match-string 0)))))
10391 ((member complete-file '((4) (16)))
10392 ;; Completing read for file names.
10393 (setq link (org-file-complete-link complete-file)))
10395 ;; Read link, with completion for stored links.
10396 (org-link-fontify-links-to-this-file)
10397 (org-switch-to-buffer-other-window "*Org Links*")
10398 (with-current-buffer "*Org Links*"
10399 (erase-buffer)
10400 (insert "Insert a link.
10401 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10402 (when org-stored-links
10403 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10404 (insert (mapconcat 'org-link-prettify
10405 (reverse org-stored-links) "\n")))
10406 (goto-char (point-min)))
10407 (let ((cw (selected-window)))
10408 (select-window (get-buffer-window "*Org Links*" 'visible))
10409 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10410 (unless (pos-visible-in-window-p (point-max))
10411 (org-fit-window-to-buffer))
10412 (and (window-live-p cw) (select-window cw)))
10413 (setq all-prefixes (append (mapcar 'car abbrevs)
10414 (mapcar 'car org-link-abbrev-alist)
10415 (org-link-types)))
10416 (unwind-protect
10417 ;; Fake a link history, containing the stored links.
10418 (let ((org--links-history
10419 (append (mapcar #'car org-stored-links)
10420 org-insert-link-history)))
10421 (setq link
10422 (org-completing-read
10423 "Link: "
10424 (append
10425 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10426 (mapcar #'car org-stored-links))
10427 nil nil nil
10428 'org--links-history
10429 (caar org-stored-links)))
10430 (unless (org-string-nw-p link) (user-error "No link selected"))
10431 (dolist (l org-stored-links)
10432 (when (equal link (cadr l))
10433 (setq link (car l))
10434 (setq auto-desc t)))
10435 (when (or (member link all-prefixes)
10436 (and (equal ":" (substring link -1))
10437 (member (substring link 0 -1) all-prefixes)
10438 (setq link (substring link 0 -1))))
10439 (setq link (with-current-buffer origbuf
10440 (org-link-try-special-completion link)))))
10441 (set-window-configuration wcf)
10442 (kill-buffer "*Org Links*"))
10443 (setq entry (assoc link org-stored-links))
10444 (or entry (push link org-insert-link-history))
10445 (setq desc (or desc (nth 1 entry)))))
10447 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10448 (not org-keep-stored-link-after-insertion))
10449 (setq org-stored-links (delq (assoc link org-stored-links)
10450 org-stored-links)))
10452 (when (and (string-match org-plain-link-re link)
10453 (not (string-match org-ts-regexp link)))
10454 ;; URL-like link, normalize the use of angular brackets.
10455 (setq link (org-unbracket-string "<" ">" link)))
10457 ;; Check if we are linking to the current file with a search
10458 ;; option If yes, simplify the link by using only the search
10459 ;; option.
10460 (when (and buffer-file-name
10461 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10462 (let* ((path (match-string 1 link))
10463 (case-fold-search nil)
10464 (search (match-string 2 link)))
10465 (save-match-data
10466 (when (equal (file-truename buffer-file-name) (file-truename path))
10467 ;; We are linking to this same file, with a search option
10468 (setq link search)))))
10470 ;; Check if we can/should use a relative path. If yes, simplify the link
10471 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10472 (let* ((type (match-string 1 link))
10473 (path (match-string 2 link))
10474 (origpath path)
10475 (case-fold-search nil))
10476 (cond
10477 ((or (eq org-link-file-path-type 'absolute)
10478 (equal complete-file '(16)))
10479 (setq path (abbreviate-file-name (expand-file-name path))))
10480 ((eq org-link-file-path-type 'noabbrev)
10481 (setq path (expand-file-name path)))
10482 ((eq org-link-file-path-type 'relative)
10483 (setq path (file-relative-name path)))
10485 (save-match-data
10486 (if (string-match (concat "^" (regexp-quote
10487 (expand-file-name
10488 (file-name-as-directory
10489 default-directory))))
10490 (expand-file-name path))
10491 ;; We are linking a file with relative path name.
10492 (setq path (substring (expand-file-name path)
10493 (match-end 0)))
10494 (setq path (abbreviate-file-name (expand-file-name path)))))))
10495 (setq link (concat type path))
10496 (when (equal desc origpath)
10497 (setq desc path))))
10499 (if org-make-link-description-function
10500 (setq desc
10501 (or (condition-case nil
10502 (funcall org-make-link-description-function link desc)
10503 (error (progn (message "Can't get link description from `%s'"
10504 (symbol-name org-make-link-description-function))
10505 (sit-for 2) nil)))
10506 (read-string "Description: " default-description)))
10507 (if default-description (setq desc default-description)
10508 (setq desc (or (and auto-desc desc)
10509 (read-string "Description: " desc)))))
10511 (unless (string-match "\\S-" desc) (setq desc nil))
10512 (when remove (apply 'delete-region remove))
10513 (insert (org-make-link-string link desc))
10514 ;; Redisplay so as the new link has proper invisible characters.
10515 (sit-for 0)))
10517 (defun org-link-try-special-completion (type)
10518 "If there is completion support for link type TYPE, offer it."
10519 (let ((fun (org-link-get-parameter type :complete)))
10520 (if (functionp fun)
10521 (funcall fun)
10522 (read-string "Link (no completion support): " (concat type ":")))))
10524 (defun org-file-complete-link (&optional arg)
10525 "Create a file link using completion."
10526 (let ((file (read-file-name "File: "))
10527 (pwd (file-name-as-directory (expand-file-name ".")))
10528 (pwd1 (file-name-as-directory (abbreviate-file-name
10529 (expand-file-name ".")))))
10530 (cond ((equal arg '(16))
10531 (concat "file:"
10532 (abbreviate-file-name (expand-file-name file))))
10533 ((string-match
10534 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10535 (concat "file:" (match-string 1 file)))
10536 ((string-match
10537 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10538 (expand-file-name file))
10539 (concat "file:"
10540 (match-string 1 (expand-file-name file))))
10541 (t (concat "file:" file)))))
10543 (defun org-completing-read (&rest args)
10544 "Completing-read with SPACE being a normal character."
10545 (let ((enable-recursive-minibuffers t)
10546 (minibuffer-local-completion-map
10547 (copy-keymap minibuffer-local-completion-map)))
10548 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10549 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10550 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10551 'org-time-stamp-inactive)
10552 (apply #'completing-read args)))
10554 ;;; Opening/following a link
10556 (defvar org-link-search-failed nil)
10558 (defvar org-open-link-functions nil
10559 "Hook for functions finding a plain text link.
10560 These functions must take a single argument, the link content.
10561 They will be called for links that look like [[link text][description]]
10562 when LINK TEXT does not have a protocol like \"http:\" and does not look
10563 like a filename (e.g. \"./blue.png\").
10565 These functions will be called *before* Org attempts to resolve the
10566 link by doing text searches in the current buffer - so if you want a
10567 link \"[[target]]\" to still find \"<<target>>\", your function should
10568 handle this as a special case.
10570 When the function does handle the link, it must return a non-nil value.
10571 If it decides that it is not responsible for this link, it must return
10572 nil to indicate that that Org can continue with other options like
10573 exact and fuzzy text search.")
10575 (defun org-next-link (&optional search-backward)
10576 "Move forward to the next link.
10577 If the link is in hidden text, expose it."
10578 (interactive "P")
10579 (when (and org-link-search-failed (eq this-command last-command))
10580 (goto-char (point-min))
10581 (message "Link search wrapped back to beginning of buffer"))
10582 (setq org-link-search-failed nil)
10583 (let* ((pos (point))
10584 (ct (org-context))
10585 (a (assq :link ct))
10586 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10587 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10588 ((looking-at org-any-link-re)
10589 ;; Don't stay stuck at link without an org-link face
10590 (forward-char (if search-backward -1 1))))
10591 (if (funcall srch-fun org-any-link-re nil t)
10592 (progn
10593 (goto-char (match-beginning 0))
10594 (when (outline-invisible-p) (org-show-context)))
10595 (goto-char pos)
10596 (setq org-link-search-failed t)
10597 (message "No further link found"))))
10599 (defun org-previous-link ()
10600 "Move backward to the previous link.
10601 If the link is in hidden text, expose it."
10602 (interactive)
10603 (funcall 'org-next-link t))
10605 (defun org-translate-link (s)
10606 "Translate a link string if a translation function has been defined."
10607 (with-temp-buffer
10608 (insert (org-trim s))
10609 (org-trim (org-element-interpret-data (org-element-context)))))
10611 (defun org-translate-link-from-planner (type path)
10612 "Translate a link from Emacs Planner syntax so that Org can follow it.
10613 This is still an experimental function, your mileage may vary."
10614 (cond
10615 ((member type '("http" "https" "news" "ftp"))
10616 ;; standard Internet links are the same.
10617 nil)
10618 ((and (equal type "irc") (string-match "^//" path))
10619 ;; Planner has two / at the beginning of an irc link, we have 1.
10620 ;; We should have zero, actually....
10621 (setq path (substring path 1)))
10622 ((and (equal type "lisp") (string-match "^/" path))
10623 ;; Planner has a slash, we do not.
10624 (setq type "elisp" path (substring path 1)))
10625 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10626 ;; A typical message link. Planner has the id after the final slash,
10627 ;; we separate it with a hash mark
10628 (setq path (concat (match-string 1 path) "#"
10629 (org-unbracket-string "<" ">" (match-string 2 path))))))
10630 (cons type path))
10632 (defun org-find-file-at-mouse (ev)
10633 "Open file link or URL at mouse."
10634 (interactive "e")
10635 (mouse-set-point ev)
10636 (org-open-at-point 'in-emacs))
10638 (defun org-open-at-mouse (ev)
10639 "Open file link or URL at mouse.
10640 See the docstring of `org-open-file' for details."
10641 (interactive "e")
10642 (mouse-set-point ev)
10643 (when (eq major-mode 'org-agenda-mode)
10644 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10645 (org-open-at-point))
10647 (defvar org-window-config-before-follow-link nil
10648 "The window configuration before following a link.
10649 This is saved in case the need arises to restore it.")
10651 ;;;###autoload
10652 (defun org-open-at-point-global ()
10653 "Follow a link or time-stamp like Org mode does.
10654 This command can be called in any mode to follow an external link
10655 or a time-stamp that has Org mode syntax. Its behavior is
10656 undefined when called on internal links (e.g., fuzzy links).
10657 Raise an error when there is nothing to follow. "
10658 (interactive)
10659 (cond ((org-in-regexp org-any-link-re)
10660 (org-open-link-from-string (match-string-no-properties 0)))
10661 ((or (org-in-regexp org-ts-regexp-both nil t)
10662 (org-in-regexp org-tsr-regexp-both nil t))
10663 (org-follow-timestamp-link))
10664 (t (user-error "No link found"))))
10666 ;;;###autoload
10667 (defun org-open-link-from-string (s &optional arg reference-buffer)
10668 "Open a link in the string S, as if it was in Org mode."
10669 (interactive "sLink: \nP")
10670 (let ((reference-buffer (or reference-buffer (current-buffer))))
10671 (with-temp-buffer
10672 (let ((org-inhibit-startup (not reference-buffer)))
10673 (org-mode)
10674 (insert s)
10675 (goto-char (point-min))
10676 (when reference-buffer
10677 (setq org-link-abbrev-alist-local
10678 (with-current-buffer reference-buffer
10679 org-link-abbrev-alist-local)))
10680 (org-open-at-point arg reference-buffer)))))
10682 (defvar org-open-at-point-functions nil
10683 "Hook that is run when following a link at point.
10685 Functions in this hook must return t if they identify and follow
10686 a link at point. If they don't find anything interesting at point,
10687 they must return nil.")
10689 (defvar org-link-search-inhibit-query nil)
10690 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10691 (defun org--open-doi-link (path)
10692 "Open a \"doi\" type link.
10693 PATH is a the path to search for, as a string."
10694 (browse-url (url-encode-url (concat org-doi-server-url path))))
10696 (defun org--open-elisp-link (path)
10697 "Open a \"elisp\" type link.
10698 PATH is the sexp to evaluate, as a string."
10699 (let ((cmd path))
10700 (if (or (and (org-string-nw-p
10701 org-confirm-elisp-link-not-regexp)
10702 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10703 (not org-confirm-elisp-link-function)
10704 (funcall org-confirm-elisp-link-function
10705 (format "Execute \"%s\" as elisp? "
10706 (org-add-props cmd nil 'face 'org-warning))))
10707 (message "%s => %s" cmd
10708 (if (eq (string-to-char cmd) ?\()
10709 (eval (read cmd))
10710 (call-interactively (read cmd))))
10711 (user-error "Abort"))))
10713 (defun org--open-help-link (path)
10714 "Open a \"help\" type link.
10715 PATH is a symbol name, as a string."
10716 (pcase (intern path)
10717 ((and (pred fboundp) variable) (describe-function variable))
10718 ((and (pred boundp) function) (describe-variable function))
10719 (name (user-error "Unknown function or variable: %s" name))))
10721 (defun org--open-shell-link (path)
10722 "Open a \"shell\" type link.
10723 PATH is the command to execute, as a string."
10724 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10725 (cmd path))
10726 (if (or (and (org-string-nw-p
10727 org-confirm-shell-link-not-regexp)
10728 (string-match
10729 org-confirm-shell-link-not-regexp cmd))
10730 (not org-confirm-shell-link-function)
10731 (funcall org-confirm-shell-link-function
10732 (format "Execute \"%s\" in shell? "
10733 (org-add-props cmd nil
10734 'face 'org-warning))))
10735 (progn
10736 (message "Executing %s" cmd)
10737 (shell-command cmd buf)
10738 (when (featurep 'midnight)
10739 (setq clean-buffer-list-kill-buffer-names
10740 (cons (buffer-name buf)
10741 clean-buffer-list-kill-buffer-names))))
10742 (user-error "Abort"))))
10744 (defun org-open-at-point (&optional arg reference-buffer)
10745 "Open link, timestamp, footnote or tags at point.
10747 When point is on a link, follow it. Normally, files will be
10748 opened by an appropriate application. If the optional prefix
10749 argument ARG is non-nil, Emacs will visit the file. With
10750 a double prefix argument, try to open outside of Emacs, in the
10751 application the system uses for this file type.
10753 When point is on a timestamp, open the agenda at the day
10754 specified.
10756 When point is a footnote definition, move to the first reference
10757 found. If it is on a reference, move to the associated
10758 definition.
10760 When point is on a headline, display a list of every link in the
10761 entry, so it is possible to pick one, or all, of them. If point
10762 is on a tag, call `org-tags-view' instead.
10764 When optional argument REFERENCE-BUFFER is non-nil, it should
10765 specify a buffer from where the link search should happen. This
10766 is used internally by `org-open-link-from-string'.
10768 On top of syntactically correct links, this function will open
10769 the link at point in comments or comment blocks and the first
10770 link in a property drawer line."
10771 (interactive "P")
10772 ;; On a code block, open block's results.
10773 (unless (call-interactively 'org-babel-open-src-block-result)
10774 (org-load-modules-maybe)
10775 (setq org-window-config-before-follow-link (current-window-configuration))
10776 (org-remove-occur-highlights nil nil t)
10777 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10778 (let* ((context
10779 ;; Only consider supported types, even if they are not
10780 ;; the closest one.
10781 (org-element-lineage
10782 (org-element-context)
10783 '(clock comment comment-block footnote-definition
10784 footnote-reference headline inlinetask keyword link
10785 node-property timestamp)
10787 (type (org-element-type context))
10788 (value (org-element-property :value context)))
10789 (cond
10790 ((not context) (user-error "No link found"))
10791 ;; Exception: open timestamps and links in properties
10792 ;; drawers, keywords and comments.
10793 ((memq type '(comment comment-block keyword node-property))
10794 (call-interactively #'org-open-at-point-global))
10795 ;; On a headline or an inlinetask, but not on a timestamp,
10796 ;; a link, a footnote reference or on tags.
10797 ((and (memq type '(headline inlinetask))
10798 ;; Not on tags.
10799 (let ((case-fold-search nil))
10800 (save-excursion
10801 (beginning-of-line)
10802 (looking-at org-complex-heading-regexp))
10803 (or (not (match-beginning 5))
10804 (< (point) (match-beginning 5)))))
10805 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10806 (links (car data))
10807 (links-end (cdr data)))
10808 (if links
10809 (dolist (link (if (stringp links) (list links) links))
10810 (search-forward link nil links-end)
10811 (goto-char (match-beginning 0))
10812 (org-open-at-point))
10813 (require 'org-attach)
10814 (org-attach-reveal 'if-exists))))
10815 ;; On a clock line, make sure point is on the timestamp
10816 ;; before opening it.
10817 ((and (eq type 'clock)
10818 value
10819 (>= (point) (org-element-property :begin value))
10820 (<= (point) (org-element-property :end value)))
10821 (org-follow-timestamp-link))
10822 ;; Do nothing on white spaces after an object.
10823 ((>= (point)
10824 (save-excursion
10825 (goto-char (org-element-property :end context))
10826 (skip-chars-backward " \t")
10827 (point)))
10828 (user-error "No link found"))
10829 ((eq type 'timestamp) (org-follow-timestamp-link))
10830 ;; On tags within a headline or an inlinetask.
10831 ((and (memq type '(headline inlinetask))
10832 (let ((case-fold-search nil))
10833 (save-excursion (beginning-of-line)
10834 (looking-at org-complex-heading-regexp))
10835 (and (match-beginning 5)
10836 (>= (point) (match-beginning 5)))))
10837 (org-tags-view arg (substring (match-string 5) 0 -1)))
10838 ((eq type 'link)
10839 (let ((type (org-element-property :type context))
10840 (path (org-link-unescape (org-element-property :path context))))
10841 ;; Switch back to REFERENCE-BUFFER needed when called in
10842 ;; a temporary buffer through `org-open-link-from-string'.
10843 (with-current-buffer (or reference-buffer (current-buffer))
10844 (cond
10845 ((equal type "file")
10846 (if (string-match "[*?{]" (file-name-nondirectory path))
10847 (dired path)
10848 ;; Look into `org-link-parameters' in order to find
10849 ;; a DEDICATED-FUNCTION to open file. The function
10850 ;; will be applied on raw link instead of parsed
10851 ;; link due to the limitation in `org-add-link-type'
10852 ;; ("open" function called with a single argument).
10853 ;; If no such function is found, fallback to
10854 ;; `org-open-file'.
10855 (let* ((option (org-element-property :search-option context))
10856 (app (org-element-property :application context))
10857 (dedicated-function
10858 (org-link-get-parameter
10859 (if app (concat type "+" app) type)
10860 :follow)))
10861 (if dedicated-function
10862 (funcall dedicated-function
10863 (concat path
10864 (and option (concat "::" option))))
10865 (apply #'org-open-file
10866 path
10867 (cond (arg)
10868 ((equal app "emacs") 'emacs)
10869 ((equal app "sys") 'system))
10870 (cond ((not option) nil)
10871 ((string-match-p "\\`[0-9]+\\'" option)
10872 (list (string-to-number option)))
10873 (t (list nil
10874 (org-link-unescape option)))))))))
10875 ((functionp (org-link-get-parameter type :follow))
10876 (funcall (org-link-get-parameter type :follow) path))
10877 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10878 (unless (run-hook-with-args-until-success
10879 'org-open-link-functions path)
10880 (if (not arg) (org-mark-ring-push)
10881 (switch-to-buffer-other-window
10882 (org-get-buffer-for-internal-link (current-buffer))))
10883 (let ((destination
10884 (org-with-wide-buffer
10885 (if (equal type "radio")
10886 (org-search-radio-target
10887 (org-element-property :path context))
10888 (org-link-search
10889 (if (member type '("custom-id" "coderef"))
10890 (org-element-property :raw-link context)
10891 path)
10892 ;; Prevent fuzzy links from matching
10893 ;; themselves.
10894 (and (equal type "fuzzy")
10895 (+ 2 (org-element-property :begin context)))))
10896 (point))))
10897 (unless (and (<= (point-min) destination)
10898 (>= (point-max) destination))
10899 (widen))
10900 (goto-char destination))))
10901 (t (browse-url-at-point))))))
10902 ;; On a footnote reference or at a footnote definition's label.
10903 ((or (eq type 'footnote-reference)
10904 (and (eq type 'footnote-definition)
10905 (save-excursion
10906 ;; Do not validate action when point is on the
10907 ;; spaces right after the footnote label, in
10908 ;; order to be on par with behaviour on links.
10909 (skip-chars-forward " \t")
10910 (let ((begin
10911 (org-element-property :contents-begin context)))
10912 (if begin (< (point) begin)
10913 (= (org-element-property :post-affiliated context)
10914 (line-beginning-position)))))))
10915 (org-footnote-action))
10916 (t (user-error "No link found")))))
10917 (run-hook-with-args 'org-follow-link-hook)))
10919 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10920 "Offer links in the current entry and return the selected link.
10921 If there is only one link, return it.
10922 If NTH is an integer, return the NTH link found.
10923 If ZERO is a string, check also this string for a link, and if
10924 there is one, return it."
10925 (with-current-buffer buffer
10926 (org-with-wide-buffer
10927 (goto-char marker)
10928 (let ((cnt ?0)
10929 have-zero end links link c)
10930 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10931 (push (match-string 0 zero) links)
10932 (setq cnt (1- cnt) have-zero t))
10933 (save-excursion
10934 (org-back-to-heading t)
10935 (setq end (save-excursion (outline-next-heading) (point)))
10936 (while (re-search-forward org-any-link-re end t)
10937 (push (match-string 0) links))
10938 (setq links (org-uniquify (reverse links))))
10939 (cond
10940 ((null links)
10941 (message "No links"))
10942 ((equal (length links) 1)
10943 (setq link (car links)))
10944 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10945 (setq link (nth (if have-zero nth (1- nth)) links)))
10946 (t ; we have to select a link
10947 (save-excursion
10948 (save-window-excursion
10949 (delete-other-windows)
10950 (with-output-to-temp-buffer "*Select Link*"
10951 (dolist (l links)
10952 (cond
10953 ((not (string-match org-bracket-link-regexp l))
10954 (princ (format "[%c] %s\n" (cl-incf cnt)
10955 (org-unbracket-string "<" ">" l))))
10956 ((match-end 3)
10957 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10958 (match-string 3 l) (match-string 1 l))))
10959 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10960 (match-string 1 l)))))))
10961 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10962 (message "Select link to open, RET to open all:")
10963 (setq c (read-char-exclusive))
10964 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10965 (when (equal c ?q) (user-error "Abort"))
10966 (if (equal c ?\C-m)
10967 (setq link links)
10968 (setq nth (- c ?0))
10969 (when have-zero (setq nth (1+ nth)))
10970 (unless (and (integerp nth) (>= (length links) nth))
10971 (user-error "Invalid link selection"))
10972 (setq link (nth (1- nth) links)))))
10973 (cons link end)))))
10975 ;; TODO: These functions are deprecated since `org-open-at-point'
10976 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10977 (defun org-open-file-with-system (path)
10978 "Open file at PATH using the system way of opening it."
10979 (org-open-file path 'system))
10980 (defun org-open-file-with-emacs (path)
10981 "Open file at PATH in Emacs."
10982 (org-open-file path 'emacs))
10985 ;;; File search
10987 (defvar org-create-file-search-functions nil
10988 "List of functions to construct the right search string for a file link.
10989 These functions are called in turn with point at the location to
10990 which the link should point.
10992 A function in the hook should first test if it would like to
10993 handle this file type, for example by checking the `major-mode'
10994 or the file extension. If it decides not to handle this file, it
10995 should just return nil to give other functions a chance. If it
10996 does handle the file, it must return the search string to be used
10997 when following the link. The search string will be part of the
10998 file link, given after a double colon, and `org-open-at-point'
10999 will automatically search for it. If special measures must be
11000 taken to make the search successful, another function should be
11001 added to the companion hook `org-execute-file-search-functions',
11002 which see.
11004 A function in this hook may also use `setq' to set the variable
11005 `description' to provide a suggestion for the descriptive text to
11006 be used for this link when it gets inserted into an Org buffer
11007 with \\[org-insert-link].")
11009 (defvar org-execute-file-search-functions nil
11010 "List of functions to execute a file search triggered by a link.
11012 Functions added to this hook must accept a single argument, the
11013 search string that was part of the file link, the part after the
11014 double colon. The function must first check if it would like to
11015 handle this search, for example by checking the `major-mode' or
11016 the file extension. If it decides not to handle this search, it
11017 should just return nil to give other functions a chance. If it
11018 does handle the search, it must return a non-nil value to keep
11019 other functions from trying.
11021 Each function can access the current prefix argument through the
11022 variable `current-prefix-arg'. Note that a single prefix is used
11023 to force opening a link in Emacs, so it may be good to only use a
11024 numeric or double prefix to guide the search function.
11026 In case this is needed, a function in this hook can also restore
11027 the window configuration before `org-open-at-point' was called using:
11029 (set-window-configuration org-window-config-before-follow-link)")
11031 (defun org-search-radio-target (target)
11032 "Search a radio target matching TARGET in current buffer.
11033 White spaces are not significant."
11034 (let ((re (format "<<<%s>>>"
11035 (mapconcat #'regexp-quote
11036 (org-split-string target "[ \t\n]+")
11037 "[ \t]+\\(?:\n[ \t]*\\)?")))
11038 (origin (point)))
11039 (goto-char (point-min))
11040 (catch :radio-match
11041 (while (re-search-forward re nil t)
11042 (backward-char)
11043 (let ((object (org-element-context)))
11044 (when (eq (org-element-type object) 'radio-target)
11045 (goto-char (org-element-property :begin object))
11046 (org-show-context 'link-search)
11047 (throw :radio-match nil))))
11048 (goto-char origin)
11049 (user-error "No match for radio target: %s" target))))
11051 (defun org-link-search (s &optional avoid-pos stealth)
11052 "Search for a search string S.
11054 If S starts with \"#\", it triggers a custom ID search.
11056 If S is enclosed within parenthesis, it initiates a coderef
11057 search.
11059 If S is surrounded by forward slashes, it is interpreted as
11060 a regular expression. In Org mode files, this will create an
11061 `org-occur' sparse tree. In ordinary files, `occur' will be used
11062 to list matches. If the current buffer is in `dired-mode', grep
11063 will be used to search in all files.
11065 When AVOID-POS is given, ignore matches near that position.
11067 When optional argument STEALTH is non-nil, do not modify
11068 visibility around point, thus ignoring `org-show-context-detail'
11069 variable.
11071 Search is case-insensitive and ignores white spaces. Return type
11072 of matched result, which is either `dedicated' or `fuzzy'."
11073 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11074 (let* ((case-fold-search t)
11075 (origin (point))
11076 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11077 (starred (eq (string-to-char normalized) ?*))
11078 (words (split-string (if starred (substring s 1) s)))
11079 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11080 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11081 type)
11082 (cond
11083 ;; Check if there are any special search functions.
11084 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11085 ((eq (string-to-char s) ?#)
11086 ;; Look for a custom ID S if S starts with "#".
11087 (let* ((id (substring normalized 1))
11088 (match (org-find-property "CUSTOM_ID" id)))
11089 (if match (progn (goto-char match) (setf type 'dedicated))
11090 (error "No match for custom ID: %s" id))))
11091 ((string-match "\\`(\\(.*\\))\\'" normalized)
11092 ;; Look for coderef targets if S is enclosed within parenthesis.
11093 (let ((coderef (match-string-no-properties 1 normalized))
11094 (re (substring s-single-re 1 -1)))
11095 (goto-char (point-min))
11096 (catch :coderef-match
11097 (while (re-search-forward re nil t)
11098 (let ((element (org-element-at-point)))
11099 (when (and (memq (org-element-type element)
11100 '(example-block src-block))
11101 ;; Build proper regexp according to current
11102 ;; block's label format.
11103 (let ((label-fmt
11104 (regexp-quote
11105 (or (org-element-property :label-fmt element)
11106 org-coderef-label-format))))
11107 (save-excursion
11108 (beginning-of-line)
11109 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11110 (format label-fmt coderef))))))
11111 (setq type 'dedicated)
11112 (goto-char (match-beginning 1))
11113 (throw :coderef-match nil))))
11114 (goto-char origin)
11115 (error "No match for coderef: %s" coderef))))
11116 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11117 ;; Look for a regular expression.
11118 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11119 (match-string 1 s)))
11120 ;; From here, we handle fuzzy links.
11122 ;; Look for targets, only if not in a headline search.
11123 ((and (not starred)
11124 (let ((target (format "<<%s>>" s-multi-re)))
11125 (catch :target-match
11126 (goto-char (point-min))
11127 (while (re-search-forward target nil t)
11128 (backward-char)
11129 (let ((context (org-element-context)))
11130 (when (eq (org-element-type context) 'target)
11131 (setq type 'dedicated)
11132 (goto-char (org-element-property :begin context))
11133 (throw :target-match t))))
11134 nil))))
11135 ;; Look for elements named after S, only if not in a headline
11136 ;; search.
11137 ((and (not starred)
11138 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11139 (catch :name-match
11140 (goto-char (point-min))
11141 (while (re-search-forward name nil t)
11142 (let ((element (org-element-at-point)))
11143 (when (equal words
11144 (split-string
11145 (org-element-property :name element)))
11146 (setq type 'dedicated)
11147 (beginning-of-line)
11148 (throw :name-match t))))
11149 nil))))
11150 ;; Regular text search. Prefer headlines in Org mode buffers.
11151 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11152 ;; statistics cookies and tags.
11153 ((and (derived-mode-p 'org-mode)
11154 (let ((title-re
11155 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11156 org-outline-regexp-bol
11157 org-comment-string
11158 (mapconcat #'regexp-quote words ".+")))
11159 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11160 (comment-re (eval-when-compile
11161 (format "\\`%s[ \t]+" org-comment-string))))
11162 (goto-char (point-min))
11163 (catch :found
11164 (while (re-search-forward title-re nil t)
11165 (when (equal words
11166 (split-string
11167 (replace-regexp-in-string
11168 cookie-re ""
11169 (replace-regexp-in-string
11170 comment-re "" (org-get-heading t t t)))))
11171 (throw :found t)))
11172 nil)))
11173 (beginning-of-line)
11174 (setq type 'dedicated))
11175 ;; Offer to create non-existent headline depending on
11176 ;; `org-link-search-must-match-exact-headline'.
11177 ((and (derived-mode-p 'org-mode)
11178 (not org-link-search-inhibit-query)
11179 (eq org-link-search-must-match-exact-headline 'query-to-create)
11180 (yes-or-no-p "No match - create this as a new heading? "))
11181 (goto-char (point-max))
11182 (unless (bolp) (newline))
11183 (org-insert-heading nil t t)
11184 (insert s "\n")
11185 (beginning-of-line 0))
11186 ;; Only headlines are looked after. No need to process
11187 ;; further: throw an error.
11188 ((and (derived-mode-p 'org-mode)
11189 (or starred org-link-search-must-match-exact-headline))
11190 (goto-char origin)
11191 (error "No match for fuzzy expression: %s" normalized))
11192 ;; Regular text search.
11193 ((catch :fuzzy-match
11194 (goto-char (point-min))
11195 (while (re-search-forward s-multi-re nil t)
11196 ;; Skip match if it contains AVOID-POS or it is included in
11197 ;; a link with a description but outside the description.
11198 (unless (or (and avoid-pos
11199 (<= (match-beginning 0) avoid-pos)
11200 (> (match-end 0) avoid-pos))
11201 (and (save-match-data
11202 (org-in-regexp org-bracket-link-regexp))
11203 (match-beginning 3)
11204 (or (> (match-beginning 3) (point))
11205 (<= (match-end 3) (point)))
11206 (org-element-lineage
11207 (save-match-data (org-element-context))
11208 '(link) t)))
11209 (goto-char (match-beginning 0))
11210 (setq type 'fuzzy)
11211 (throw :fuzzy-match t)))
11212 nil))
11213 ;; All failed. Throw an error.
11214 (t (goto-char origin)
11215 (error "No match for fuzzy expression: %s" normalized)))
11216 ;; Disclose surroundings of match, if appropriate.
11217 (when (and (derived-mode-p 'org-mode) (not stealth))
11218 (org-show-context 'link-search))
11219 type))
11221 (defun org-get-buffer-for-internal-link (buffer)
11222 "Return a buffer to be used for displaying the link target of internal links."
11223 (cond
11224 ((not org-display-internal-link-with-indirect-buffer)
11225 buffer)
11226 ((string-suffix-p "(Clone)" (buffer-name buffer))
11227 (message "Buffer is already a clone, not making another one")
11228 ;; we also do not modify visibility in this case
11229 buffer)
11230 (t ; make a new indirect buffer for displaying the link
11231 (let* ((bn (buffer-name buffer))
11232 (ibn (concat bn "(Clone)"))
11233 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11234 (with-current-buffer ib (org-overview))
11235 ib))))
11237 (defun org-do-occur (regexp &optional cleanup)
11238 "Call the Emacs command `occur'.
11239 If CLEANUP is non-nil, remove the printout of the regular expression
11240 in the *Occur* buffer. This is useful if the regex is long and not useful
11241 to read."
11242 (occur regexp)
11243 (when cleanup
11244 (let ((cwin (selected-window)) win beg end)
11245 (when (setq win (get-buffer-window "*Occur*"))
11246 (select-window win))
11247 (goto-char (point-min))
11248 (when (re-search-forward "match[a-z]+" nil t)
11249 (setq beg (match-end 0))
11250 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11251 (setq end (1- (match-beginning 0)))))
11252 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11253 (goto-char (point-min))
11254 (select-window cwin))))
11256 ;;; The mark ring for links jumps
11258 (defvar org-mark-ring nil
11259 "Mark ring for positions before jumps in Org mode.")
11260 (defvar org-mark-ring-last-goto nil
11261 "Last position in the mark ring used to go back.")
11262 ;; Fill and close the ring
11263 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11264 (dotimes (_ org-mark-ring-length)
11265 (push (make-marker) org-mark-ring))
11266 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11267 org-mark-ring)
11269 (defun org-mark-ring-push (&optional pos buffer)
11270 "Put the current position or POS into the mark ring and rotate it."
11271 (interactive)
11272 (setq pos (or pos (point)))
11273 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11274 (move-marker (car org-mark-ring)
11275 (or pos (point))
11276 (or buffer (current-buffer)))
11277 (message "%s"
11278 (substitute-command-keys
11279 "Position saved to mark ring, go back with \
11280 `\\[org-mark-ring-goto]'.")))
11282 (defun org-mark-ring-goto (&optional n)
11283 "Jump to the previous position in the mark ring.
11284 With prefix arg N, jump back that many stored positions. When
11285 called several times in succession, walk through the entire ring.
11286 Org mode commands jumping to a different position in the current file,
11287 or to another Org file, automatically push the old position onto the ring."
11288 (interactive "p")
11289 (let (p m)
11290 (if (eq last-command this-command)
11291 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11292 (setq p org-mark-ring))
11293 (setq org-mark-ring-last-goto p)
11294 (setq m (car p))
11295 (pop-to-buffer-same-window (marker-buffer m))
11296 (goto-char m)
11297 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11299 (defun org-add-angle-brackets (s)
11300 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11301 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11304 ;;; Following specific links
11306 (defvar org-agenda-buffer-tmp-name)
11307 (defvar org-agenda-start-on-weekday)
11308 (defun org-follow-timestamp-link ()
11309 "Open an agenda view for the time-stamp date/range at point."
11310 (cond
11311 ((org-at-date-range-p t)
11312 (let ((org-agenda-start-on-weekday)
11313 (t1 (match-string 1))
11314 (t2 (match-string 2)) tt1 tt2)
11315 (setq tt1 (time-to-days (org-time-string-to-time t1))
11316 tt2 (time-to-days (org-time-string-to-time t2)))
11317 (let ((org-agenda-buffer-tmp-name
11318 (format "*Org Agenda(a:%s)"
11319 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11320 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11321 ((org-at-timestamp-p t)
11322 (let ((org-agenda-buffer-tmp-name
11323 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11324 (org-agenda-list nil (time-to-days (org-time-string-to-time
11325 (substring (match-string 1) 0 10)))
11326 1)))
11327 (t (error "This should not happen"))))
11330 ;;; Following file links
11331 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11332 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11333 (declare-function mailcap-mime-info
11334 "mailcap" (string &optional request no-decode))
11335 (defvar org-wait nil)
11336 (defun org-open-file (path &optional in-emacs line search)
11337 "Open the file at PATH.
11338 First, this expands any special file name abbreviations. Then the
11339 configuration variable `org-file-apps' is checked if it contains an
11340 entry for this file type, and if yes, the corresponding command is launched.
11342 If no application is found, Emacs simply visits the file.
11344 With optional prefix argument IN-EMACS, Emacs will visit the file.
11345 With a double \\[universal-argument] \\[universal-argument] \
11346 prefix arg, Org tries to avoid opening in Emacs
11347 and to use an external application to visit the file.
11349 Optional LINE specifies a line to go to, optional SEARCH a string
11350 to search for. If LINE or SEARCH is given, the file will be
11351 opened in Emacs, unless an entry from org-file-apps that makes
11352 use of groups in a regexp matches.
11354 If you want to change the way frames are used when following a
11355 link, please customize `org-link-frame-setup'.
11357 If the file does not exist, an error is thrown."
11358 (let* ((file (if (equal path "")
11359 buffer-file-name
11360 (substitute-in-file-name (expand-file-name path))))
11361 (file-apps (append org-file-apps (org-default-apps)))
11362 (apps (cl-remove-if
11363 'org-file-apps-entry-match-against-dlink-p file-apps))
11364 (apps-dlink (cl-remove-if-not
11365 'org-file-apps-entry-match-against-dlink-p file-apps))
11366 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11367 (dirp (unless remp (file-directory-p file)))
11368 (file (if (and dirp org-open-directory-means-index-dot-org)
11369 (concat (file-name-as-directory file) "index.org")
11370 file))
11371 (a-m-a-p (assq 'auto-mode apps))
11372 (dfile (downcase file))
11373 ;; Reconstruct the original link from the PATH, LINE and
11374 ;; SEARCH args.
11375 (link (cond (line (concat file "::" (number-to-string line)))
11376 (search (concat file "::" search))
11377 (t file)))
11378 (dlink (downcase link))
11379 (ext
11380 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11381 (match-string 1 dfile)))
11382 (save-position-maybe
11383 (let ((old-buffer (current-buffer))
11384 (old-pos (point))
11385 (old-mode major-mode))
11386 (lambda ()
11387 (and (derived-mode-p 'org-mode)
11388 (eq old-mode 'org-mode)
11389 (or (not (eq old-buffer (current-buffer)))
11390 (not (eq old-pos (point))))
11391 (org-mark-ring-push old-pos old-buffer)))))
11392 cmd link-match-data)
11393 (cond
11394 ((member in-emacs '((16) system))
11395 (setq cmd (cdr (assq 'system apps))))
11396 (in-emacs (setq cmd 'emacs))
11398 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11399 (and dirp (cdr (assq 'directory apps)))
11400 ;; First, try matching against apps-dlink if we
11401 ;; get a match here, store the match data for
11402 ;; later.
11403 (let ((match (assoc-default dlink apps-dlink
11404 'string-match)))
11405 (if match
11406 (progn (setq link-match-data (match-data))
11407 match)
11408 (progn (setq in-emacs (or in-emacs line search))
11409 nil))) ; if we have no match in apps-dlink,
11410 ; always open the file in emacs if line or search
11411 ; is given (for backwards compatibility)
11412 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11413 'string-match)
11414 (cdr (assoc ext apps))
11415 (cdr (assq t apps))))))
11416 (when (eq cmd 'system)
11417 (setq cmd (cdr (assq 'system apps))))
11418 (when (eq cmd 'default)
11419 (setq cmd (cdr (assoc t apps))))
11420 (when (eq cmd 'mailcap)
11421 (require 'mailcap)
11422 (mailcap-parse-mailcaps)
11423 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11424 (command (mailcap-mime-info mime-type)))
11425 (if (stringp command)
11426 (setq cmd command)
11427 (setq cmd 'emacs))))
11428 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11429 (not (file-exists-p file))
11430 (not org-open-non-existing-files))
11431 (user-error "No such file: %s" file))
11432 (cond
11433 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11434 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11435 (while (string-match "['\"]%s['\"]" cmd)
11436 (setq cmd (replace-match "%s" t t cmd)))
11437 (setq cmd (replace-regexp-in-string
11438 "%s"
11439 (shell-quote-argument (convert-standard-filename file))
11441 nil t))
11443 ;; Replace "%1", "%2" etc. in command with group matches from regex
11444 (save-match-data
11445 (let ((match-index 1)
11446 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11447 (set-match-data link-match-data)
11448 (while (<= match-index number-of-groups)
11449 (let ((regex (concat "%" (number-to-string match-index)))
11450 (replace-with (match-string match-index dlink)))
11451 (while (string-match regex cmd)
11452 (setq cmd (replace-match replace-with t t cmd))))
11453 (setq match-index (+ match-index 1)))))
11455 (save-window-excursion
11456 (message "Running %s...done" cmd)
11457 (start-process-shell-command cmd nil cmd)
11458 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11459 ((or (stringp cmd)
11460 (eq cmd 'emacs))
11461 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11462 (widen)
11463 (cond (line (org-goto-line line)
11464 (when (derived-mode-p 'org-mode) (org-reveal)))
11465 (search (condition-case err
11466 (org-link-search search)
11467 ;; Save position before error-ing out so user
11468 ;; can easily move back to the original buffer.
11469 (error (funcall save-position-maybe)
11470 (error (nth 1 err)))))))
11471 ((functionp cmd)
11472 (save-match-data
11473 (set-match-data link-match-data)
11474 (condition-case nil
11475 (funcall cmd file link)
11476 ;; FIXME: Remove this check when most default installations
11477 ;; of Emacs have at least Org 9.0.
11478 ((debug wrong-number-of-arguments wrong-type-argument
11479 invalid-function)
11480 (user-error "Please see Org News for version 9.0 about \
11481 `org-file-apps'--Lisp error: %S" cmd)))))
11482 ((consp cmd)
11483 ;; FIXME: Remove this check when most default installations of
11484 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11485 ;; fall back to `org-link-frame-setup' for an old usage of
11486 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11487 (user-error "Please see Org News for version 9.0 about \
11488 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11489 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11490 (funcall save-position-maybe)))
11492 (defun org-file-apps-entry-match-against-dlink-p (entry)
11493 "This function returns non-nil if `entry' uses a regular
11494 expression which should be matched against the whole link by
11495 org-open-file.
11497 It assumes that is the case when the entry uses a regular
11498 expression which has at least one grouping construct and the
11499 action is either a lisp form or a command string containing
11500 `%1', i.e. using at least one subexpression match as a
11501 parameter."
11502 (let ((selector (car entry))
11503 (action (cdr entry)))
11504 (if (stringp selector)
11505 (and (> (regexp-opt-depth selector) 0)
11506 (or (and (stringp action)
11507 (string-match "%[0-9]" action))
11508 (consp action)))
11509 nil)))
11511 (defun org-default-apps ()
11512 "Return the default applications for this operating system."
11513 (cond
11514 ((eq system-type 'darwin)
11515 org-file-apps-defaults-macosx)
11516 ((eq system-type 'windows-nt)
11517 org-file-apps-defaults-windowsnt)
11518 (t org-file-apps-defaults-gnu)))
11520 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11521 "Convert extensions to regular expressions in the cars of LIST.
11522 Also, weed out any non-string entries, because the return value is used
11523 only for regexp matching.
11524 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11525 point to the symbol `emacs', indicating that the file should
11526 be opened in Emacs."
11527 (append
11528 (delq nil
11529 (mapcar (lambda (x)
11530 (unless (not (stringp (car x)))
11531 (if (string-match "\\W" (car x))
11533 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11534 list))
11535 (when add-auto-mode
11536 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11538 (defvar ange-ftp-name-format)
11539 (defun org-file-remote-p (file)
11540 "Test whether FILE specifies a location on a remote system.
11541 Return non-nil if the location is indeed remote.
11543 For example, the filename \"/user@host:/foo\" specifies a location
11544 on the system \"/user@host:\"."
11545 (cond ((fboundp 'file-remote-p)
11546 (file-remote-p file))
11547 ((fboundp 'tramp-handle-file-remote-p)
11548 (tramp-handle-file-remote-p file))
11549 ((and (boundp 'ange-ftp-name-format)
11550 (string-match (car ange-ftp-name-format) file))
11551 t)))
11554 ;;;; Refiling
11556 (defun org-get-org-file ()
11557 "Read a filename, with default directory `org-directory'."
11558 (let ((default (or org-default-notes-file remember-data-file)))
11559 (read-file-name (format "File name [%s]: " default)
11560 (file-name-as-directory org-directory)
11561 default)))
11563 (defun org-notes-order-reversed-p ()
11564 "Check if the current file should receive notes in reversed order."
11565 (cond
11566 ((not org-reverse-note-order) nil)
11567 ((eq t org-reverse-note-order) t)
11568 ((not (listp org-reverse-note-order)) nil)
11569 (t (catch 'exit
11570 (dolist (entry org-reverse-note-order)
11571 (when (string-match (car entry) buffer-file-name)
11572 (throw 'exit (cdr entry))))))))
11574 (defvar org-refile-target-table nil
11575 "The list of refile targets, created by `org-refile'.")
11577 (defvar org-agenda-new-buffers nil
11578 "Buffers created to visit agenda files.")
11580 (defvar org-refile-cache nil
11581 "Cache for refile targets.")
11583 (defvar org-refile-markers nil
11584 "All the markers used for caching refile locations.")
11586 (defun org-refile-marker (pos)
11587 "Get a new refile marker, but only if caching is in use."
11588 (if (not org-refile-use-cache)
11590 (let ((m (make-marker)))
11591 (move-marker m pos)
11592 (push m org-refile-markers)
11593 m)))
11595 (defun org-refile-cache-clear ()
11596 "Clear the refile cache and disable all the markers."
11597 (dolist (m org-refile-markers) (move-marker m nil))
11598 (setq org-refile-markers nil)
11599 (setq org-refile-cache nil)
11600 (message "Refile cache has been cleared"))
11602 (defun org-refile-cache-check-set (set)
11603 "Check if all the markers in the cache still have live buffers."
11604 (let (marker)
11605 (catch 'exit
11606 (while (and set (setq marker (nth 3 (pop set))))
11607 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11608 (when (and marker (null (marker-buffer marker)))
11609 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11610 (sit-for 3)
11611 (throw 'exit nil)))
11612 t)))
11614 (defun org-refile-cache-put (set &rest identifiers)
11615 "Push the refile targets SET into the cache, under IDENTIFIERS."
11616 (let* ((key (sha1 (prin1-to-string identifiers)))
11617 (entry (assoc key org-refile-cache)))
11618 (if entry
11619 (setcdr entry set)
11620 (push (cons key set) org-refile-cache))))
11622 (defun org-refile-cache-get (&rest identifiers)
11623 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11624 (cond
11625 ((not org-refile-cache) nil)
11626 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11628 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11629 org-refile-cache))))
11630 (and set (org-refile-cache-check-set set) set)))))
11632 (defvar org-outline-path-cache nil
11633 "Alist between buffer positions and outline paths.
11634 It value is an alist (POSITION . PATH) where POSITION is the
11635 buffer position at the beginning of an entry and PATH is a list
11636 of strings describing the outline path for that entry, in reverse
11637 order.")
11639 (defun org-refile-get-targets (&optional default-buffer)
11640 "Produce a table with refile targets."
11641 (let ((case-fold-search nil)
11642 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11643 (entries (or org-refile-targets '((nil . (:level . 1)))))
11644 targets tgs files desc descre)
11645 (message "Getting targets...")
11646 (with-current-buffer (or default-buffer (current-buffer))
11647 (dolist (entry entries)
11648 (setq files (car entry) desc (cdr entry))
11649 (cond
11650 ((null files) (setq files (list (current-buffer))))
11651 ((eq files 'org-agenda-files)
11652 (setq files (org-agenda-files 'unrestricted)))
11653 ((and (symbolp files) (fboundp files))
11654 (setq files (funcall files)))
11655 ((and (symbolp files) (boundp files))
11656 (setq files (symbol-value files))))
11657 (when (stringp files) (setq files (list files)))
11658 (cond
11659 ((eq (car desc) :tag)
11660 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11661 ((eq (car desc) :todo)
11662 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11663 ((eq (car desc) :regexp)
11664 (setq descre (cdr desc)))
11665 ((eq (car desc) :level)
11666 (setq descre (concat "^\\*\\{" (number-to-string
11667 (if org-odd-levels-only
11668 (1- (* 2 (cdr desc)))
11669 (cdr desc)))
11670 "\\}[ \t]")))
11671 ((eq (car desc) :maxlevel)
11672 (setq descre (concat "^\\*\\{1," (number-to-string
11673 (if org-odd-levels-only
11674 (1- (* 2 (cdr desc)))
11675 (cdr desc)))
11676 "\\}[ \t]")))
11677 (t (error "Bad refiling target description %s" desc)))
11678 (dolist (f files)
11679 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11681 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11682 (progn
11683 (when (bufferp f)
11684 (setq f (buffer-file-name (buffer-base-buffer f))))
11685 (setq f (and f (expand-file-name f)))
11686 (when (eq org-refile-use-outline-path 'file)
11687 (push (list (file-name-nondirectory f) f nil nil) tgs))
11688 (org-with-wide-buffer
11689 (goto-char (point-min))
11690 (setq org-outline-path-cache nil)
11691 (while (re-search-forward descre nil t)
11692 (beginning-of-line)
11693 (let ((case-fold-search nil))
11694 (looking-at org-complex-heading-regexp))
11695 (let ((begin (point))
11696 (heading (match-string-no-properties 4)))
11697 (unless (or (and
11698 org-refile-target-verify-function
11699 (not
11700 (funcall org-refile-target-verify-function)))
11701 (not heading))
11702 (let ((re (format org-complex-heading-regexp-format
11703 (regexp-quote heading)))
11704 (target
11705 (if (not org-refile-use-outline-path) heading
11706 (mapconcat
11707 #'org-protect-slash
11708 (append
11709 (pcase org-refile-use-outline-path
11710 (`file (list (file-name-nondirectory
11711 (buffer-file-name
11712 (buffer-base-buffer)))))
11713 (`full-file-path
11714 (list (buffer-file-name
11715 (buffer-base-buffer))))
11716 (_ nil))
11717 (org-get-outline-path t t))
11718 "/"))))
11719 (push (list target f re (org-refile-marker (point)))
11720 tgs)))
11721 (when (= (point) begin)
11722 ;; Verification function has not moved point.
11723 (end-of-line)))))))
11724 (when org-refile-use-cache
11725 (org-refile-cache-put tgs (buffer-file-name) descre))
11726 (setq targets (append tgs targets))))))
11727 (message "Getting targets...done")
11728 (nreverse targets)))
11730 (defun org-protect-slash (s)
11731 (replace-regexp-in-string "/" "\\/" s nil t))
11733 (defun org--get-outline-path-1 (&optional use-cache)
11734 "Return outline path to current headline.
11736 Outline path is a list of strings, in reverse order. When
11737 optional argument USE-CACHE is non-nil, make use of a cache. See
11738 `org-get-outline-path' for details.
11740 Assume buffer is widened and point is on a headline."
11741 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11742 (let ((p (point))
11743 (heading (let ((case-fold-search nil))
11744 (looking-at org-complex-heading-regexp)
11745 (if (not (match-end 4)) ""
11746 ;; Remove statistics cookies.
11747 (org-trim
11748 (org-link-display-format
11749 (replace-regexp-in-string
11750 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11751 (match-string-no-properties 4))))))))
11752 (if (org-up-heading-safe)
11753 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11754 (when use-cache
11755 (push (cons p path) org-outline-path-cache))
11756 path)
11757 ;; This is a new root node. Since we assume we are moving
11758 ;; forward, we can drop previous cache so as to limit number
11759 ;; of associations there.
11760 (let ((path (list heading)))
11761 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11762 path)))))
11764 (defun org-get-outline-path (&optional with-self use-cache)
11765 "Return the outline path to the current entry.
11767 An outline path is a list of ancestors for current headline, as
11768 a list of strings. Statistics cookies are removed and links are
11769 replaced with their description, if any, or their path otherwise.
11771 When optional argument WITH-SELF is non-nil, the path also
11772 includes the current headline.
11774 When optional argument USE-CACHE is non-nil, cache outline paths
11775 between calls to this function so as to avoid backtracking. This
11776 argument is useful when planning to find more than one outline
11777 path in the same document. In that case, there are two
11778 conditions to satisfy:
11779 - `org-outline-path-cache' is set to nil before starting the
11780 process;
11781 - outline paths are computed by increasing buffer positions."
11782 (org-with-wide-buffer
11783 (and (or (and with-self (org-back-to-heading t))
11784 (org-up-heading-safe))
11785 (reverse (org--get-outline-path-1 use-cache)))))
11787 (defun org-format-outline-path (path &optional width prefix separator)
11788 "Format the outline path PATH for display.
11789 WIDTH is the maximum number of characters that is available.
11790 PREFIX is a prefix to be included in the returned string,
11791 such as the file name.
11792 SEPARATOR is inserted between the different parts of the path,
11793 the default is \"/\"."
11794 (setq width (or width 79))
11795 (setq path (delq nil path))
11796 (unless (> width 0)
11797 (user-error "Argument `width' must be positive"))
11798 (setq separator (or separator "/"))
11799 (let* ((org-odd-levels-only nil)
11800 (fpath (concat
11801 prefix (and prefix path separator)
11802 (mapconcat
11803 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11804 (cl-loop for head in path
11805 for n from 0
11806 collect (org-add-props
11807 head nil 'face
11808 (nth (% n org-n-level-faces) org-level-faces)))
11809 separator))))
11810 (when (> (length fpath) width)
11811 (if (< width 7)
11812 ;; It's unlikely that `width' will be this small, but don't
11813 ;; waste characters by adding ".." if it is.
11814 (setq fpath (substring fpath 0 width))
11815 (setf (substring fpath (- width 2)) "..")))
11816 fpath))
11818 (defun org-display-outline-path (&optional file current separator just-return-string)
11819 "Display the current outline path in the echo area.
11821 If FILE is non-nil, prepend the output with the file name.
11822 If CURRENT is non-nil, append the current heading to the output.
11823 SEPARATOR is passed through to `org-format-outline-path'. It separates
11824 the different parts of the path and defaults to \"/\".
11825 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11826 (interactive "P")
11827 (let* (case-fold-search
11828 (bfn (buffer-file-name (buffer-base-buffer)))
11829 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11830 res)
11831 (when current (setq path (append path
11832 (save-excursion
11833 (org-back-to-heading t)
11834 (when (looking-at org-complex-heading-regexp)
11835 (list (match-string 4)))))))
11836 (setq res
11837 (org-format-outline-path
11838 path
11839 (1- (frame-width))
11840 (and file bfn (concat (file-name-nondirectory bfn) separator))
11841 separator))
11842 (if just-return-string
11843 (org-no-properties res)
11844 (org-unlogged-message "%s" res))))
11846 (defvar org-refile-history nil
11847 "History for refiling operations.")
11849 (defvar org-after-refile-insert-hook nil
11850 "Hook run after `org-refile' has inserted its stuff at the new location.
11851 Note that this is still *before* the stuff will be removed from
11852 the *old* location.")
11854 (defvar org-capture-last-stored-marker)
11855 (defvar org-refile-keep nil
11856 "Non-nil means `org-refile' will copy instead of refile.")
11858 (defun org-copy ()
11859 "Like `org-refile', but copy."
11860 (interactive)
11861 (let ((org-refile-keep t))
11862 (funcall 'org-refile nil nil nil "Copy")))
11864 (defun org-refile (&optional arg default-buffer rfloc msg)
11865 "Move the entry or entries at point to another heading.
11867 The list of target headings is compiled using the information in
11868 `org-refile-targets', which see.
11870 At the target location, the entry is filed as a subitem of the
11871 target heading. Depending on `org-reverse-note-order', the new
11872 subitem will either be the first or the last subitem.
11874 If there is an active region, all entries in that region will be
11875 refiled. However, the region must fulfill the requirement that
11876 the first heading sets the top-level of the moved text.
11878 With a `\\[universal-argument]' ARG, the command will only visit the target \
11879 location
11880 and not actually move anything.
11882 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11883 location where the last
11884 refiling operation has put the subtree.
11886 With a numeric prefix argument of `2', refile to the running clock.
11888 With a numeric prefix argument of `3', emulate `org-refile-keep'
11889 being set to t and copy to the target location, don't move it.
11890 Beware that keeping refiled entries may result in duplicated ID
11891 properties.
11893 RFLOC can be a refile location obtained in a different way.
11895 MSG is a string to replace \"Refile\" in the default prompt with
11896 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11898 See also `org-refile-use-outline-path'.
11900 If you are using target caching (see `org-refile-use-cache'), you
11901 have to clear the target cache in order to find new targets.
11902 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11903 prefix argument (`C-u C-u C-u C-c C-w')."
11904 (interactive "P")
11905 (if (member arg '(0 (64)))
11906 (org-refile-cache-clear)
11907 (let* ((actionmsg (cond (msg msg)
11908 ((equal arg 3) "Refile (and keep)")
11909 (t "Refile")))
11910 (regionp (org-region-active-p))
11911 (region-start (and regionp (region-beginning)))
11912 (region-end (and regionp (region-end)))
11913 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11914 pos it nbuf file level reversed)
11915 (setq last-command nil)
11916 (when regionp
11917 (goto-char region-start)
11918 (or (bolp) (goto-char (point-at-bol)))
11919 (setq region-start (point))
11920 (unless (or (org-kill-is-subtree-p
11921 (buffer-substring region-start region-end))
11922 (prog1 org-refile-active-region-within-subtree
11923 (let ((s (point-at-eol)))
11924 (org-toggle-heading)
11925 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11926 (user-error "The region is not a (sequence of) subtree(s)")))
11927 (if (equal arg '(16))
11928 (org-refile-goto-last-stored)
11929 (when (or
11930 (and (equal arg 2)
11931 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11932 (prog1
11933 (setq it (list (or org-clock-heading "running clock")
11934 (buffer-file-name
11935 (marker-buffer org-clock-hd-marker))
11937 (marker-position org-clock-hd-marker)))
11938 (setq arg nil)))
11939 (setq it
11940 (or rfloc
11941 (let (heading-text)
11942 (save-excursion
11943 (unless (and arg (listp arg))
11944 (org-back-to-heading t)
11945 (setq heading-text
11946 (replace-regexp-in-string
11947 org-bracket-link-regexp
11948 "\\3"
11949 (or (nth 4 (org-heading-components))
11950 ""))))
11951 (org-refile-get-location
11952 (cond ((and arg (listp arg)) "Goto")
11953 (regionp (concat actionmsg " region to"))
11954 (t (concat actionmsg " subtree \""
11955 heading-text "\" to")))
11956 default-buffer
11957 (and (not (equal '(4) arg))
11958 org-refile-allow-creating-parent-nodes)))))))
11959 (setq file (nth 1 it)
11960 pos (nth 3 it))
11961 (when (and (not arg)
11963 (equal (buffer-file-name) file)
11964 (if regionp
11965 (and (>= pos region-start)
11966 (<= pos region-end))
11967 (and (>= pos (point))
11968 (< pos (save-excursion
11969 (org-end-of-subtree t t))))))
11970 (error "Cannot refile to position inside the tree or region"))
11971 (setq nbuf (or (find-buffer-visiting file)
11972 (find-file-noselect file)))
11973 (if (and arg (not (equal arg 3)))
11974 (progn
11975 (pop-to-buffer-same-window nbuf)
11976 (goto-char pos)
11977 (org-show-context 'org-goto))
11978 (if regionp
11979 (progn
11980 (org-kill-new (buffer-substring region-start region-end))
11981 (org-save-markers-in-region region-start region-end))
11982 (org-copy-subtree 1 nil t))
11983 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11984 (find-file-noselect file)))
11985 (setq reversed (org-notes-order-reversed-p))
11986 (org-with-wide-buffer
11987 (if pos
11988 (progn
11989 (goto-char pos)
11990 (setq level (org-get-valid-level (funcall outline-level) 1))
11991 (goto-char
11992 (if reversed
11993 (or (outline-next-heading) (point-max))
11994 (or (save-excursion (org-get-next-sibling))
11995 (org-end-of-subtree t t)
11996 (point-max)))))
11997 (setq level 1)
11998 (if (not reversed)
11999 (goto-char (point-max))
12000 (goto-char (point-min))
12001 (or (outline-next-heading) (goto-char (point-max)))))
12002 (unless (bolp) (newline))
12003 (org-paste-subtree level nil nil t)
12004 (when org-log-refile
12005 (org-add-log-setup 'refile nil nil org-log-refile)
12006 (unless (eq org-log-refile 'note)
12007 (save-excursion (org-add-log-note))))
12008 (and org-auto-align-tags
12009 (let ((org-loop-over-headlines-in-active-region nil))
12010 (org-set-tags nil t)))
12011 (let ((bookmark-name (plist-get org-bookmark-names-plist
12012 :last-refile)))
12013 (when bookmark-name
12014 (with-demoted-errors
12015 (bookmark-set bookmark-name))))
12016 ;; If we are refiling for capture, make sure that the
12017 ;; last-capture pointers point here
12018 (when (bound-and-true-p org-capture-is-refiling)
12019 (let ((bookmark-name (plist-get org-bookmark-names-plist
12020 :last-capture-marker)))
12021 (when bookmark-name
12022 (with-demoted-errors
12023 (bookmark-set bookmark-name))))
12024 (move-marker org-capture-last-stored-marker (point)))
12025 (when (fboundp 'deactivate-mark) (deactivate-mark))
12026 (run-hooks 'org-after-refile-insert-hook)))
12027 (unless org-refile-keep
12028 (if regionp
12029 (delete-region (point) (+ (point) (- region-end region-start)))
12030 (delete-region
12031 (and (org-back-to-heading t) (point))
12032 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12033 (when (featurep 'org-inlinetask)
12034 (org-inlinetask-remove-END-maybe))
12035 (setq org-markers-to-move nil)
12036 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12038 (defun org-refile-goto-last-stored ()
12039 "Go to the location where the last refile was stored."
12040 (interactive)
12041 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12042 (message "This is the location of the last refile"))
12044 (defun org-refile--get-location (refloc tbl)
12045 "When user refile to REFLOC, find the associated target in TBL.
12046 Also check `org-refile-target-table'."
12047 (car (delq
12049 (mapcar
12050 (lambda (r) (or (assoc r tbl)
12051 (assoc r org-refile-target-table)))
12052 (list (replace-regexp-in-string "/$" "" refloc)
12053 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12055 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12056 "Prompt the user for a refile location, using PROMPT.
12057 PROMPT should not be suffixed with a colon and a space, because
12058 this function appends the default value from
12059 `org-refile-history' automatically, if that is not empty."
12060 (let ((org-refile-targets org-refile-targets)
12061 (org-refile-use-outline-path org-refile-use-outline-path))
12062 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12063 (unless org-refile-target-table
12064 (user-error "No refile targets"))
12065 (let* ((cbuf (current-buffer))
12066 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12067 (cfunc (if (and org-refile-use-outline-path
12068 org-outline-path-complete-in-steps)
12069 #'org-olpath-completing-read
12070 #'completing-read))
12071 (extra (if org-refile-use-outline-path "/" ""))
12072 (cbnex (concat (buffer-name) extra))
12073 (filename (and cfn (expand-file-name cfn)))
12074 (tbl (mapcar
12075 (lambda (x)
12076 (if (and (not (member org-refile-use-outline-path
12077 '(file full-file-path)))
12078 (not (equal filename (nth 1 x))))
12079 (cons (concat (car x) extra " ("
12080 (file-name-nondirectory (nth 1 x)) ")")
12081 (cdr x))
12082 (cons (concat (car x) extra) (cdr x))))
12083 org-refile-target-table))
12084 (completion-ignore-case t)
12085 cdef
12086 (prompt (concat prompt
12087 (or (and (car org-refile-history)
12088 (concat " (default " (car org-refile-history) ")"))
12089 (and (assoc cbnex tbl) (setq cdef cbnex)
12090 (concat " (default " cbnex ")"))) ": "))
12091 pa answ parent-target child parent old-hist)
12092 (setq old-hist org-refile-history)
12093 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12094 nil 'org-refile-history (or cdef (car org-refile-history))))
12095 (if (setq pa (org-refile--get-location answ tbl))
12096 (progn
12097 (org-refile-check-position pa)
12098 (when (or (not org-refile-history)
12099 (not (eq old-hist org-refile-history))
12100 (not (equal (car pa) (car org-refile-history))))
12101 (setq org-refile-history
12102 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12103 org-refile-history
12104 (cdr org-refile-history))))
12105 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12106 (pop org-refile-history)))
12108 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12109 (progn
12110 (setq parent (match-string 1 answ)
12111 child (match-string 2 answ))
12112 (setq parent-target (org-refile--get-location parent tbl))
12113 (when (and parent-target
12114 (or (eq new-nodes t)
12115 (and (eq new-nodes 'confirm)
12116 (y-or-n-p (format "Create new node \"%s\"? "
12117 child)))))
12118 (org-refile-new-child parent-target child)))
12119 (user-error "Invalid target location")))))
12121 (declare-function org-string-nw-p "org-macs" (s))
12122 (defun org-refile-check-position (refile-pointer)
12123 "Check if the refile pointer matches the headline to which it points."
12124 (let* ((file (nth 1 refile-pointer))
12125 (re (nth 2 refile-pointer))
12126 (pos (nth 3 refile-pointer))
12127 buffer)
12128 (if (and (not (markerp pos)) (not file))
12129 (user-error "Please indicate a target file in the refile path")
12130 (when (org-string-nw-p re)
12131 (setq buffer (if (markerp pos)
12132 (marker-buffer pos)
12133 (or (find-buffer-visiting file)
12134 (find-file-noselect file))))
12135 (with-current-buffer buffer
12136 (org-with-wide-buffer
12137 (goto-char pos)
12138 (beginning-of-line 1)
12139 (unless (looking-at-p re)
12140 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12142 (defun org-refile-new-child (parent-target child)
12143 "Use refile target PARENT-TARGET to add new CHILD below it."
12144 (unless parent-target
12145 (error "Cannot find parent for new node"))
12146 (let ((file (nth 1 parent-target))
12147 (pos (nth 3 parent-target))
12148 level)
12149 (with-current-buffer (or (find-buffer-visiting file)
12150 (find-file-noselect file))
12151 (org-with-wide-buffer
12152 (if pos
12153 (goto-char pos)
12154 (goto-char (point-max))
12155 (unless (bolp) (newline)))
12156 (when (looking-at org-outline-regexp)
12157 (setq level (funcall outline-level))
12158 (org-end-of-subtree t t))
12159 (org-back-over-empty-lines)
12160 (insert "\n" (make-string
12161 (if pos (org-get-valid-level level 1) 1) ?*)
12162 " " child "\n")
12163 (beginning-of-line 0)
12164 (list (concat (car parent-target) "/" child) file "" (point))))))
12166 (defun org-olpath-completing-read (prompt collection &rest args)
12167 "Read an outline path like a file name."
12168 (let ((thetable collection))
12169 (apply #'completing-read
12170 prompt
12171 (lambda (string predicate &optional flag)
12172 (cond
12173 ((eq flag nil) (try-completion string thetable))
12174 ((eq flag t)
12175 (let ((l (length string)))
12176 (mapcar (lambda (x)
12177 (let ((r (substring x l))
12178 (f (if (string-match " ([^)]*)$" x)
12179 (match-string 0 x)
12180 "")))
12181 (if (string-match "/" r)
12182 (concat string (substring r 0 (match-end 0)) f)
12183 x)))
12184 (all-completions string thetable predicate))))
12185 ;; Exact match?
12186 ((eq flag 'lambda) (assoc string thetable))))
12187 args)))
12189 ;;;; Dynamic blocks
12191 (defun org-find-dblock (name)
12192 "Find the first dynamic block with name NAME in the buffer.
12193 If not found, stay at current position and return nil."
12194 (let ((case-fold-search t) pos)
12195 (save-excursion
12196 (goto-char (point-min))
12197 (setq pos (and (re-search-forward
12198 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12199 (match-beginning 0))))
12200 (when pos (goto-char pos))
12201 pos))
12203 (defun org-create-dblock (plist)
12204 "Create a dynamic block section, with parameters taken from PLIST.
12205 PLIST must contain a :name entry which is used as the name of the block."
12206 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12207 (end-of-line 1)
12208 (newline))
12209 (let ((col (current-column))
12210 (name (plist-get plist :name)))
12211 (insert "#+BEGIN: " name)
12212 (while plist
12213 (if (eq (car plist) :name)
12214 (setq plist (cddr plist))
12215 (insert " " (prin1-to-string (pop plist)))))
12216 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12217 (beginning-of-line -2)))
12219 (defun org-prepare-dblock ()
12220 "Prepare dynamic block for refresh.
12221 This empties the block, puts the cursor at the insert position and returns
12222 the property list including an extra property :name with the block name."
12223 (unless (looking-at org-dblock-start-re)
12224 (user-error "Not at a dynamic block"))
12225 (let* ((begdel (1+ (match-end 0)))
12226 (name (org-no-properties (match-string 1)))
12227 (params (append (list :name name)
12228 (read (concat "(" (match-string 3) ")")))))
12229 (save-excursion
12230 (beginning-of-line 1)
12231 (skip-chars-forward " \t")
12232 (setq params (plist-put params :indentation-column (current-column))))
12233 (unless (re-search-forward org-dblock-end-re nil t)
12234 (error "Dynamic block not terminated"))
12235 (setq params
12236 (append params
12237 (list :content (buffer-substring
12238 begdel (match-beginning 0)))))
12239 (delete-region begdel (match-beginning 0))
12240 (goto-char begdel)
12241 (open-line 1)
12242 params))
12244 (defun org-map-dblocks (&optional command)
12245 "Apply COMMAND to all dynamic blocks in the current buffer.
12246 If COMMAND is not given, use `org-update-dblock'."
12247 (let ((cmd (or command 'org-update-dblock)))
12248 (save-excursion
12249 (goto-char (point-min))
12250 (while (re-search-forward org-dblock-start-re nil t)
12251 (goto-char (match-beginning 0))
12252 (save-excursion
12253 (condition-case nil
12254 (funcall cmd)
12255 (error (message "Error during update of dynamic block"))))
12256 (unless (re-search-forward org-dblock-end-re nil t)
12257 (error "Dynamic block not terminated"))))))
12259 (defun org-dblock-update (&optional arg)
12260 "User command for updating dynamic blocks.
12261 Update the dynamic block at point. With prefix ARG, update all dynamic
12262 blocks in the buffer."
12263 (interactive "P")
12264 (if arg
12265 (org-update-all-dblocks)
12266 (or (looking-at org-dblock-start-re)
12267 (org-beginning-of-dblock))
12268 (org-update-dblock)))
12270 (defun org-update-dblock ()
12271 "Update the dynamic block at point.
12272 This means to empty the block, parse for parameters and then call
12273 the correct writing function."
12274 (interactive)
12275 (save-excursion
12276 (let* ((win (selected-window))
12277 (pos (point))
12278 (line (org-current-line))
12279 (params (org-prepare-dblock))
12280 (name (plist-get params :name))
12281 (indent (plist-get params :indentation-column))
12282 (cmd (intern (concat "org-dblock-write:" name))))
12283 (message "Updating dynamic block `%s' at line %d..." name line)
12284 (funcall cmd params)
12285 (message "Updating dynamic block `%s' at line %d...done" name line)
12286 (goto-char pos)
12287 (when (and indent (> indent 0))
12288 (setq indent (make-string indent ?\ ))
12289 (save-excursion
12290 (select-window win)
12291 (org-beginning-of-dblock)
12292 (forward-line 1)
12293 (while (not (looking-at org-dblock-end-re))
12294 (insert indent)
12295 (beginning-of-line 2))
12296 (when (looking-at org-dblock-end-re)
12297 (and (looking-at "[ \t]+")
12298 (replace-match ""))
12299 (insert indent)))))))
12301 (defun org-beginning-of-dblock ()
12302 "Find the beginning of the dynamic block at point.
12303 Error if there is no such block at point."
12304 (let ((pos (point))
12305 beg)
12306 (end-of-line 1)
12307 (if (and (re-search-backward org-dblock-start-re nil t)
12308 (setq beg (match-beginning 0))
12309 (re-search-forward org-dblock-end-re nil t)
12310 (> (match-end 0) pos))
12311 (goto-char beg)
12312 (goto-char pos)
12313 (error "Not in a dynamic block"))))
12315 (defun org-update-all-dblocks ()
12316 "Update all dynamic blocks in the buffer.
12317 This function can be used in a hook."
12318 (interactive)
12319 (when (derived-mode-p 'org-mode)
12320 (org-map-dblocks 'org-update-dblock)))
12323 ;;;; Completion
12325 (declare-function org-export-backend-options "ox" (cl-x) t)
12326 (defun org-get-export-keywords ()
12327 "Return a list of all currently understood export keywords.
12328 Export keywords include options, block names, attributes and
12329 keywords relative to each registered export back-end."
12330 (let (keywords)
12331 (dolist (backend
12332 (bound-and-true-p org-export-registered-backends)
12333 (delq nil keywords))
12334 ;; Back-end name (for keywords, like #+LATEX:)
12335 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12336 (dolist (option-entry (org-export-backend-options backend))
12337 ;; Back-end options.
12338 (push (nth 1 option-entry) keywords)))))
12340 (defconst org-options-keywords
12341 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12342 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12343 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12344 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12345 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12347 (defcustom org-structure-template-alist
12348 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12349 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12350 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12351 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12352 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12353 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12354 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12355 ("L" "#+LaTeX: ")
12356 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12357 ("H" "#+HTML: ")
12358 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12359 ("A" "#+ASCII: ")
12360 ("i" "#+INDEX: ?")
12361 ("I" "#+INCLUDE: %file ?"))
12362 "Structure completion elements.
12363 This is a list of abbreviation keys and values. The value gets inserted
12364 if you type `<' followed by the key and then press the completion key,
12365 usually `TAB'. %file will be replaced by a file name after prompting
12366 for the file using completion. The cursor will be placed at the position
12367 of the `?' in the template.
12368 There are two templates for each key, the first uses the original Org syntax,
12369 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12370 the default when the /org-mtags.el/ module has been loaded. See also the
12371 variable `org-mtags-prefer-muse-templates'."
12372 :group 'org-completion
12373 :type '(repeat
12374 (list
12375 (string :tag "Key")
12376 (string :tag "Template")))
12377 :version "26.1"
12378 :package-version '(Org . "8.3"))
12380 (defun org-try-structure-completion ()
12381 "Try to complete a structure template before point.
12382 This looks for strings like \"<e\" on an otherwise empty line and
12383 expands them."
12384 (let ((l (buffer-substring (point-at-bol) (point)))
12386 (when (and (looking-at "[ \t]*$")
12387 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12388 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12389 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12390 (match-beginning 1)) a)
12391 t)))
12393 (defun org-complete-expand-structure-template (start cell)
12394 "Expand a structure template."
12395 (let ((rpl (nth 1 cell))
12396 (ind ""))
12397 (delete-region start (point))
12398 (when (string-match "\\`[ \t]*#\\+" rpl)
12399 (cond
12400 ((bolp))
12401 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12402 (setq ind (buffer-substring (point-at-bol) (point))))
12403 (t (newline))))
12404 (setq start (point))
12405 (when (string-match "%file" rpl)
12406 (setq rpl (replace-match
12407 (concat
12408 "\""
12409 (save-match-data
12410 (abbreviate-file-name (read-file-name "Include file: ")))
12411 "\"")
12412 t t rpl)))
12413 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12414 (concat "\n" ind)))
12415 (insert rpl)
12416 (when (re-search-backward "\\?" start t) (delete-char 1))))
12418 ;;;; TODO, DEADLINE, Comments
12420 (defun org-toggle-comment ()
12421 "Change the COMMENT state of an entry."
12422 (interactive)
12423 (save-excursion
12424 (org-back-to-heading)
12425 (let ((case-fold-search nil))
12426 (looking-at org-complex-heading-regexp))
12427 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12428 (skip-chars-forward " \t")
12429 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12430 (if (org-in-commented-heading-p t)
12431 (delete-region (point)
12432 (progn (search-forward " " (line-end-position) 'move)
12433 (skip-chars-forward " \t")
12434 (point)))
12435 (insert org-comment-string)
12436 (unless (eolp) (insert " ")))))
12438 (defvar org-last-todo-state-is-todo nil
12439 "This is non-nil when the last TODO state change led to a TODO state.
12440 If the last change removed the TODO tag or switched to DONE, then
12441 this is nil.")
12443 (defvar org-setting-tags nil) ; dynamically skipped
12445 (defvar org-todo-setup-filter-hook nil
12446 "Hook for functions that pre-filter todo specs.
12447 Each function takes a todo spec and returns either nil or the spec
12448 transformed into canonical form." )
12450 (defvar org-todo-get-default-hook nil
12451 "Hook for functions that get a default item for todo.
12452 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12453 nil or a string to be used for the todo mark." )
12455 (defvar org-agenda-headline-snapshot-before-repeat)
12457 (defun org-current-effective-time ()
12458 "Return current time adjusted for `org-extend-today-until' variable."
12459 (let* ((ct (org-current-time))
12460 (dct (decode-time ct))
12461 (ct1
12462 (cond
12463 (org-use-last-clock-out-time-as-effective-time
12464 (or (org-clock-get-last-clock-out-time) ct))
12465 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12466 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12467 (t ct))))
12468 ct1))
12470 (defun org-todo-yesterday (&optional arg)
12471 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12472 (interactive "P")
12473 (if (eq major-mode 'org-agenda-mode)
12474 (apply 'org-agenda-todo-yesterday arg)
12475 (let* ((org-use-effective-time t)
12476 (hour (nth 2 (decode-time (org-current-time))))
12477 (org-extend-today-until (1+ hour)))
12478 (org-todo arg))))
12480 (defvar org-block-entry-blocking ""
12481 "First entry preventing the TODO state change.")
12483 (defun org-cancel-repeater ()
12484 "Cancel a repeater by setting its numeric value to zero."
12485 (interactive)
12486 (save-excursion
12487 (org-back-to-heading t)
12488 (let ((bound1 (point))
12489 (bound0 (save-excursion (outline-next-heading) (point))))
12490 (when (and (re-search-forward
12491 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12492 org-deadline-time-regexp "\\)\\|\\("
12493 org-ts-regexp "\\)")
12494 bound0 t)
12495 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12496 bound1 t))
12497 (replace-match "0" t nil nil 1)))))
12499 (defvar org-state) ;; dynamically scoped into this function
12500 (defun org-todo (&optional arg)
12501 "Change the TODO state of an item.
12503 The state of an item is given by a keyword at the start of the heading,
12504 like
12505 *** TODO Write paper
12506 *** DONE Call mom
12508 The different keywords are specified in the variable `org-todo-keywords'.
12509 By default the available states are \"TODO\" and \"DONE\". So, for this
12510 example: when the item starts with TODO, it is changed to DONE.
12511 When it starts with DONE, the DONE is removed. And when neither TODO nor
12512 DONE are present, add TODO at the beginning of the heading.
12514 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12515 state.
12516 With numeric prefix ARG, switch to that state.
12517 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12518 next set of TODO \
12519 keywords (nextset).
12520 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12521 prefix, circumvent any state blocking.
12522 With a numeric prefix arg of 0, inhibit note taking for the change.
12523 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12525 When called through ELisp, arg is also interpreted in the following way:
12526 `none' -> empty state
12527 \"\" -> switch to empty state
12528 `done' -> switch to DONE
12529 `nextset' -> switch to the next set of keywords
12530 `previousset' -> switch to the previous set of keywords
12531 \"WAITING\" -> switch to the specified keyword, but only if it
12532 really is a member of `org-todo-keywords'."
12533 (interactive "P")
12534 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12535 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12536 'region-start-level 'region))
12537 org-loop-over-headlines-in-active-region)
12538 (org-map-entries
12539 `(org-todo ,arg)
12540 org-loop-over-headlines-in-active-region
12541 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12542 (when (equal arg '(16)) (setq arg 'nextset))
12543 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12544 (let ((org-blocker-hook org-blocker-hook)
12545 commentp
12546 case-fold-search)
12547 (when (equal arg '(64))
12548 (setq arg nil org-blocker-hook nil))
12549 (when (and org-blocker-hook
12550 (or org-inhibit-blocking
12551 (org-entry-get nil "NOBLOCKING")))
12552 (setq org-blocker-hook nil))
12553 (save-excursion
12554 (catch 'exit
12555 (org-back-to-heading t)
12556 (when (org-in-commented-heading-p t)
12557 (org-toggle-comment)
12558 (setq commentp t))
12559 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12560 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12561 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12562 (let* ((match-data (match-data))
12563 (startpos (point-at-bol))
12564 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12565 (org-log-done org-log-done)
12566 (org-log-repeat org-log-repeat)
12567 (org-todo-log-states org-todo-log-states)
12568 (org-inhibit-logging
12569 (if (equal arg 0)
12570 (progn (setq arg nil) 'note) org-inhibit-logging))
12571 (this (match-string 1))
12572 (hl-pos (match-beginning 0))
12573 (head (org-get-todo-sequence-head this))
12574 (ass (assoc head org-todo-kwd-alist))
12575 (interpret (nth 1 ass))
12576 (done-word (nth 3 ass))
12577 (final-done-word (nth 4 ass))
12578 (org-last-state (or this ""))
12579 (completion-ignore-case t)
12580 (member (member this org-todo-keywords-1))
12581 (tail (cdr member))
12582 (org-state (cond
12583 ((and org-todo-key-trigger
12584 (or (and (equal arg '(4))
12585 (eq org-use-fast-todo-selection 'prefix))
12586 (and (not arg) org-use-fast-todo-selection
12587 (not (eq org-use-fast-todo-selection
12588 'prefix)))))
12589 ;; Use fast selection
12590 (org-fast-todo-selection))
12591 ((and (equal arg '(4))
12592 (or (not org-use-fast-todo-selection)
12593 (not org-todo-key-trigger)))
12594 ;; Read a state with completion
12595 (completing-read
12596 "State: " (mapcar #'list org-todo-keywords-1)
12597 nil t))
12598 ((eq arg 'right)
12599 (if this
12600 (if tail (car tail) nil)
12601 (car org-todo-keywords-1)))
12602 ((eq arg 'left)
12603 (unless (equal member org-todo-keywords-1)
12604 (if this
12605 (nth (- (length org-todo-keywords-1)
12606 (length tail) 2)
12607 org-todo-keywords-1)
12608 (org-last org-todo-keywords-1))))
12609 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12610 (setq arg nil))) ; hack to fall back to cycling
12611 (arg
12612 ;; user or caller requests a specific state
12613 (cond
12614 ((equal arg "") nil)
12615 ((eq arg 'none) nil)
12616 ((eq arg 'done) (or done-word (car org-done-keywords)))
12617 ((eq arg 'nextset)
12618 (or (car (cdr (member head org-todo-heads)))
12619 (car org-todo-heads)))
12620 ((eq arg 'previousset)
12621 (let ((org-todo-heads (reverse org-todo-heads)))
12622 (or (car (cdr (member head org-todo-heads)))
12623 (car org-todo-heads))))
12624 ((car (member arg org-todo-keywords-1)))
12625 ((stringp arg)
12626 (user-error "State `%s' not valid in this file" arg))
12627 ((nth (1- (prefix-numeric-value arg))
12628 org-todo-keywords-1))))
12629 ((null member) (or head (car org-todo-keywords-1)))
12630 ((equal this final-done-word) nil) ;; -> make empty
12631 ((null tail) nil) ;; -> first entry
12632 ((memq interpret '(type priority))
12633 (if (eq this-command last-command)
12634 (car tail)
12635 (if (> (length tail) 0)
12636 (or done-word (car org-done-keywords))
12637 nil)))
12639 (car tail))))
12640 (org-state (or
12641 (run-hook-with-args-until-success
12642 'org-todo-get-default-hook org-state org-last-state)
12643 org-state))
12644 (next (if org-state (concat " " org-state " ") " "))
12645 (change-plist (list :type 'todo-state-change :from this :to org-state
12646 :position startpos))
12647 dolog now-done-p)
12648 (when org-blocker-hook
12649 (setq org-last-todo-state-is-todo
12650 (not (member this org-done-keywords)))
12651 (unless (save-excursion
12652 (save-match-data
12653 (org-with-wide-buffer
12654 (run-hook-with-args-until-failure
12655 'org-blocker-hook change-plist))))
12656 (if (called-interactively-p 'interactive)
12657 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12658 this org-state org-block-entry-blocking)
12659 ;; fail silently
12660 (message "TODO state change from %s to %s blocked (by \"%s\")"
12661 this org-state org-block-entry-blocking)
12662 (throw 'exit nil))))
12663 (store-match-data match-data)
12664 (replace-match next t t)
12665 (cond ((equal this org-state)
12666 (message "TODO state was already %s" (org-trim next)))
12667 ((pos-visible-in-window-p hl-pos)
12668 (message "TODO state changed to %s" (org-trim next))))
12669 (unless head
12670 (setq head (org-get-todo-sequence-head org-state)
12671 ass (assoc head org-todo-kwd-alist)
12672 interpret (nth 1 ass)
12673 done-word (nth 3 ass)
12674 final-done-word (nth 4 ass)))
12675 (when (memq arg '(nextset previousset))
12676 (message "Keyword-Set %d/%d: %s"
12677 (- (length org-todo-sets) -1
12678 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12679 (length org-todo-sets)
12680 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12681 (setq org-last-todo-state-is-todo
12682 (not (member org-state org-done-keywords)))
12683 (setq now-done-p (and (member org-state org-done-keywords)
12684 (not (member this org-done-keywords))))
12685 (and logging (org-local-logging logging))
12686 (when (and (or org-todo-log-states org-log-done)
12687 (not (eq org-inhibit-logging t))
12688 (not (memq arg '(nextset previousset))))
12689 ;; we need to look at recording a time and note
12690 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12691 (nth 2 (assoc this org-todo-log-states))))
12692 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12693 (setq dolog 'time))
12694 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12695 (and org-state
12696 (member org-state org-not-done-keywords)
12697 (not (member this org-not-done-keywords))))
12698 ;; This is now a todo state and was not one before
12699 ;; If there was a CLOSED time stamp, get rid of it.
12700 (org-add-planning-info nil nil 'closed))
12701 (when (and now-done-p org-log-done)
12702 ;; It is now done, and it was not done before
12703 (org-add-planning-info 'closed (org-current-effective-time))
12704 (when (and (not dolog) (eq 'note org-log-done))
12705 (org-add-log-setup 'done org-state this 'note)))
12706 (when (and org-state dolog)
12707 ;; This is a non-nil state, and we need to log it
12708 (org-add-log-setup 'state org-state this dolog)))
12709 ;; Fixup tag positioning
12710 (org-todo-trigger-tag-changes org-state)
12711 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12712 (when org-provide-todo-statistics
12713 (org-update-parent-todo-statistics))
12714 (run-hooks 'org-after-todo-state-change-hook)
12715 (when (and arg (not (member org-state org-done-keywords)))
12716 (setq head (org-get-todo-sequence-head org-state)))
12717 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12718 ;; Do we need to trigger a repeat?
12719 (when now-done-p
12720 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12721 ;; This is for the agenda, take a snapshot of the headline.
12722 (save-match-data
12723 (setq org-agenda-headline-snapshot-before-repeat
12724 (org-get-heading))))
12725 (org-auto-repeat-maybe org-state))
12726 ;; Fixup cursor location if close to the keyword
12727 (when (and (outline-on-heading-p)
12728 (not (bolp))
12729 (save-excursion (beginning-of-line 1)
12730 (looking-at org-todo-line-regexp))
12731 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12732 (goto-char (or (match-end 2) (match-end 1)))
12733 (and (looking-at " ") (just-one-space)))
12734 (when org-trigger-hook
12735 (save-excursion
12736 (run-hook-with-args 'org-trigger-hook change-plist)))
12737 (when commentp (org-toggle-comment))))))))
12739 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12740 "Block turning an entry into a TODO, using the hierarchy.
12741 This checks whether the current task should be blocked from state
12742 changes. Such blocking occurs when:
12744 1. The task has children which are not all in a completed state.
12746 2. A task has a parent with the property :ORDERED:, and there
12747 are siblings prior to the current task with incomplete
12748 status.
12750 3. The parent of the task is blocked because it has siblings that should
12751 be done first, or is child of a block grandparent TODO entry."
12753 (if (not org-enforce-todo-dependencies)
12754 t ; if locally turned off don't block
12755 (catch 'dont-block
12756 ;; If this is not a todo state change, or if this entry is already DONE,
12757 ;; do not block
12758 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12759 (member (plist-get change-plist :from)
12760 (cons 'done org-done-keywords))
12761 (member (plist-get change-plist :to)
12762 (cons 'todo org-not-done-keywords))
12763 (not (plist-get change-plist :to)))
12764 (throw 'dont-block t))
12765 ;; If this task has children, and any are undone, it's blocked
12766 (save-excursion
12767 (org-back-to-heading t)
12768 (let ((this-level (funcall outline-level)))
12769 (outline-next-heading)
12770 (let ((child-level (funcall outline-level)))
12771 (while (and (not (eobp))
12772 (> child-level this-level))
12773 ;; this todo has children, check whether they are all
12774 ;; completed
12775 (when (and (not (org-entry-is-done-p))
12776 (org-entry-is-todo-p))
12777 (setq org-block-entry-blocking (org-get-heading))
12778 (throw 'dont-block nil))
12779 (outline-next-heading)
12780 (setq child-level (funcall outline-level))))))
12781 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12782 ;; any previous siblings are undone, it's blocked
12783 (save-excursion
12784 (org-back-to-heading t)
12785 (let* ((pos (point))
12786 (parent-pos (and (org-up-heading-safe) (point)))
12787 (case-fold-search nil))
12788 (unless parent-pos (throw 'dont-block t)) ; no parent
12789 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12790 (forward-line 1)
12791 (re-search-forward org-not-done-heading-regexp pos t))
12792 (setq org-block-entry-blocking (match-string 0))
12793 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12794 ;; Search further up the hierarchy, to see if an ancestor is blocked
12795 (while t
12796 (goto-char parent-pos)
12797 (unless (looking-at org-not-done-heading-regexp)
12798 (throw 'dont-block t)) ; do not block, parent is not a TODO
12799 (setq pos (point))
12800 (setq parent-pos (and (org-up-heading-safe) (point)))
12801 (unless parent-pos (throw 'dont-block t)) ; no parent
12802 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12803 (forward-line 1)
12804 (re-search-forward org-not-done-heading-regexp pos t)
12805 (setq org-block-entry-blocking (org-get-heading)))
12806 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12808 (defcustom org-track-ordered-property-with-tag nil
12809 "Should the ORDERED property also be shown as a tag?
12810 The ORDERED property decides if an entry should require subtasks to be
12811 completed in sequence. Since a property is not very visible, setting
12812 this option means that toggling the ORDERED property with the command
12813 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12814 not relevant for the behavior, but it makes things more visible.
12816 Note that toggling the tag with tags commands will not change the property
12817 and therefore not influence behavior!
12819 This can be t, meaning the tag ORDERED should be used, It can also be a
12820 string to select a different tag for this task."
12821 :group 'org-todo
12822 :type '(choice
12823 (const :tag "No tracking" nil)
12824 (const :tag "Track with ORDERED tag" t)
12825 (string :tag "Use other tag")))
12827 (defun org-toggle-ordered-property ()
12828 "Toggle the ORDERED property of the current entry.
12829 For better visibility, you can track the value of this property with a tag.
12830 See variable `org-track-ordered-property-with-tag'."
12831 (interactive)
12832 (let* ((t1 org-track-ordered-property-with-tag)
12833 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12834 (save-excursion
12835 (org-back-to-heading)
12836 (if (org-entry-get nil "ORDERED")
12837 (progn
12838 (org-delete-property "ORDERED")
12839 (and tag (org-toggle-tag tag 'off))
12840 (message "Subtasks can be completed in arbitrary order"))
12841 (org-entry-put nil "ORDERED" "t")
12842 (and tag (org-toggle-tag tag 'on))
12843 (message "Subtasks must be completed in sequence")))))
12845 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12846 (defun org-block-todo-from-checkboxes (change-plist)
12847 "Block turning an entry into a TODO, using checkboxes.
12848 This checks whether the current task should be blocked from state
12849 changes because there are unchecked boxes in this entry."
12850 (if (not org-enforce-todo-checkbox-dependencies)
12851 t ; if locally turned off don't block
12852 (catch 'dont-block
12853 ;; If this is not a todo state change, or if this entry is already DONE,
12854 ;; do not block
12855 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12856 (member (plist-get change-plist :from)
12857 (cons 'done org-done-keywords))
12858 (member (plist-get change-plist :to)
12859 (cons 'todo org-not-done-keywords))
12860 (not (plist-get change-plist :to)))
12861 (throw 'dont-block t))
12862 ;; If this task has checkboxes that are not checked, it's blocked
12863 (save-excursion
12864 (org-back-to-heading t)
12865 (let ((beg (point)) end)
12866 (outline-next-heading)
12867 (setq end (point))
12868 (goto-char beg)
12869 (when (org-list-search-forward
12870 (concat (org-item-beginning-re)
12871 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12872 "\\[[- ]\\]")
12873 end t)
12874 (when (boundp 'org-blocked-by-checkboxes)
12875 (setq org-blocked-by-checkboxes t))
12876 (throw 'dont-block nil))))
12877 t))) ; do not block
12879 (defun org-entry-blocked-p ()
12880 "Non-nil if entry at point is blocked."
12881 (and (not (org-entry-get nil "NOBLOCKING"))
12882 (member (org-entry-get nil "TODO") org-not-done-keywords)
12883 (not (run-hook-with-args-until-failure
12884 'org-blocker-hook
12885 (list :type 'todo-state-change
12886 :position (point)
12887 :from 'todo
12888 :to 'done)))))
12890 (defun org-update-statistics-cookies (all)
12891 "Update the statistics cookie, either from TODO or from checkboxes.
12892 This should be called with the cursor in a line with a statistics
12893 cookie. When called with a \\[universal-argument] prefix, update
12894 all statistics cookies in the buffer."
12895 (interactive "P")
12896 (if all
12897 (progn
12898 (org-update-checkbox-count 'all)
12899 (org-map-entries 'org-update-parent-todo-statistics))
12900 (if (not (org-at-heading-p))
12901 (org-update-checkbox-count)
12902 (let ((pos (point-marker))
12903 end l1 l2)
12904 (ignore-errors (org-back-to-heading t))
12905 (if (not (org-at-heading-p))
12906 (org-update-checkbox-count)
12907 (setq l1 (org-outline-level))
12908 (setq end (save-excursion
12909 (outline-next-heading)
12910 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12911 (point)))
12912 (if (and (save-excursion
12913 (re-search-forward
12914 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12915 (not (save-excursion (re-search-forward
12916 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12917 (org-update-checkbox-count)
12918 (if (and l2 (> l2 l1))
12919 (progn
12920 (goto-char end)
12921 (org-update-parent-todo-statistics))
12922 (goto-char pos)
12923 (beginning-of-line 1)
12924 (while (re-search-forward
12925 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12926 (point-at-eol) t)
12927 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12928 (goto-char pos)
12929 (move-marker pos nil)))))
12931 (defvar org-entry-property-inherited-from) ;; defined below
12932 (defun org-update-parent-todo-statistics ()
12933 "Update any statistics cookie in the parent of the current headline.
12934 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12935 the entire subtree and this will travel up the hierarchy and update
12936 statistics everywhere."
12937 (let* ((prop (save-excursion (org-up-heading-safe)
12938 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12939 (recursive (or (not org-hierarchical-todo-statistics)
12940 (and prop (string-match "\\<recursive\\>" prop))))
12941 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12943 (first t)
12944 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12945 level ltoggle l1 new ndel
12946 (cnt-all 0) (cnt-done 0) is-percent kwd
12947 checkbox-beg cookie-present)
12948 (catch 'exit
12949 (save-excursion
12950 (beginning-of-line 1)
12951 (setq ltoggle (funcall outline-level))
12952 ;; Three situations are to consider:
12954 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12955 ;; to the top-level ancestor on the headline;
12957 ;; 2. If parent has "recursive" property, repeat up to the
12958 ;; headline setting that property, taking inheritance into
12959 ;; account;
12961 ;; 3. Else, move up to direct parent and proceed only once.
12962 (while (and (setq level (org-up-heading-safe))
12963 (or recursive first)
12964 (>= (point) lim))
12965 (setq first nil cookie-present nil)
12966 (unless (and level
12967 (not (string-match
12968 "\\<checkbox\\>"
12969 (downcase (or (org-entry-get nil "COOKIE_DATA")
12970 "")))))
12971 (throw 'exit nil))
12972 (while (re-search-forward box-re (point-at-eol) t)
12973 (setq cnt-all 0 cnt-done 0 cookie-present t)
12974 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12975 (save-match-data
12976 (unless (outline-next-heading) (throw 'exit nil))
12977 (while (and (looking-at org-complex-heading-regexp)
12978 (> (setq l1 (length (match-string 1))) level))
12979 (setq kwd (and (or recursive (= l1 ltoggle))
12980 (match-string 2)))
12981 (if (or (eq org-provide-todo-statistics 'all-headlines)
12982 (and (eq org-provide-todo-statistics t)
12983 (or (member kwd org-done-keywords)))
12984 (and (listp org-provide-todo-statistics)
12985 (stringp (car org-provide-todo-statistics))
12986 (or (member kwd org-provide-todo-statistics)
12987 (member kwd org-done-keywords)))
12988 (and (listp org-provide-todo-statistics)
12989 (listp (car org-provide-todo-statistics))
12990 (or (member kwd (car org-provide-todo-statistics))
12991 (and (member kwd org-done-keywords)
12992 (member kwd (cadr org-provide-todo-statistics))))))
12993 (setq cnt-all (1+ cnt-all))
12994 (and (eq org-provide-todo-statistics t)
12996 (setq cnt-all (1+ cnt-all))))
12997 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12998 (member kwd org-done-keywords))
12999 (and (listp org-provide-todo-statistics)
13000 (listp (car org-provide-todo-statistics))
13001 (member kwd org-done-keywords)
13002 (member kwd (cadr org-provide-todo-statistics)))
13003 (and (listp org-provide-todo-statistics)
13004 (stringp (car org-provide-todo-statistics))
13005 (member kwd org-done-keywords)))
13006 (setq cnt-done (1+ cnt-done)))
13007 (outline-next-heading)))
13008 (setq new
13009 (if is-percent
13010 (format "[%d%%]" (floor (* 100.0 cnt-done)
13011 (max 1 cnt-all)))
13012 (format "[%d/%d]" cnt-done cnt-all))
13013 ndel (- (match-end 0) checkbox-beg))
13014 (goto-char checkbox-beg)
13015 (insert new)
13016 (delete-region (point) (+ (point) ndel))
13017 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13018 (when cookie-present
13019 (run-hook-with-args 'org-after-todo-statistics-hook
13020 cnt-done (- cnt-all cnt-done))))))
13021 (run-hooks 'org-todo-statistics-hook)))
13023 (defvar org-after-todo-statistics-hook nil
13024 "Hook that is called after a TODO statistics cookie has been updated.
13025 Each function is called with two arguments: the number of not-done entries
13026 and the number of done entries.
13028 For example, the following function, when added to this hook, will switch
13029 an entry to DONE when all children are done, and back to TODO when new
13030 entries are set to a TODO status. Note that this hook is only called
13031 when there is a statistics cookie in the headline!
13033 (defun org-summary-todo (n-done n-not-done)
13034 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13035 (let (org-log-done org-log-states) ; turn off logging
13036 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13039 (defvar org-todo-statistics-hook nil
13040 "Hook that is run whenever Org thinks TODO statistics should be updated.
13041 This hook runs even if there is no statistics cookie present, in which case
13042 `org-after-todo-statistics-hook' would not run.")
13044 (defun org-todo-trigger-tag-changes (state)
13045 "Apply the changes defined in `org-todo-state-tags-triggers'."
13046 (let ((l org-todo-state-tags-triggers)
13047 changes)
13048 (when (or (not state) (equal state ""))
13049 (setq changes (append changes (cdr (assoc "" l)))))
13050 (when (and (stringp state) (> (length state) 0))
13051 (setq changes (append changes (cdr (assoc state l)))))
13052 (when (member state org-not-done-keywords)
13053 (setq changes (append changes (cdr (assq 'todo l)))))
13054 (when (member state org-done-keywords)
13055 (setq changes (append changes (cdr (assq 'done l)))))
13056 (dolist (c changes)
13057 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13059 (defun org-local-logging (value)
13060 "Get logging settings from a property VALUE."
13061 ;; Directly set the variables, they are already local.
13062 (setq org-log-done nil
13063 org-log-repeat nil
13064 org-todo-log-states nil)
13065 (dolist (w (org-split-string value))
13066 (let (a)
13067 (cond
13068 ((setq a (assoc w org-startup-options))
13069 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13070 (set (nth 1 a) (nth 2 a))))
13071 ((setq a (org-extract-log-state-settings w))
13072 (and (member (car a) org-todo-keywords-1)
13073 (push a org-todo-log-states)))))))
13075 (defun org-get-todo-sequence-head (kwd)
13076 "Return the head of the TODO sequence to which KWD belongs.
13077 If KWD is not set, check if there is a text property remembering the
13078 right sequence."
13079 (let (p)
13080 (cond
13081 ((not kwd)
13082 (or (get-text-property (point-at-bol) 'org-todo-head)
13083 (progn
13084 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13085 nil (point-at-eol)))
13086 (get-text-property p 'org-todo-head))))
13087 ((not (member kwd org-todo-keywords-1))
13088 (car org-todo-keywords-1))
13089 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13091 (defun org-fast-todo-selection ()
13092 "Fast TODO keyword selection with single keys.
13093 Returns the new TODO keyword, or nil if no state change should occur."
13094 (let* ((fulltable org-todo-key-alist)
13095 (done-keywords org-done-keywords) ;; needed for the faces.
13096 (maxlen (apply 'max (mapcar
13097 (lambda (x)
13098 (if (stringp (car x)) (string-width (car x)) 0))
13099 fulltable)))
13100 (expert nil)
13101 (fwidth (+ maxlen 3 1 3))
13102 (ncol (/ (- (window-width) 4) fwidth))
13103 tg cnt e c tbl
13104 groups ingroup)
13105 (save-excursion
13106 (save-window-excursion
13107 (if expert
13108 (set-buffer (get-buffer-create " *Org todo*"))
13109 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13110 (erase-buffer)
13111 (setq-local org-done-keywords done-keywords)
13112 (setq tbl fulltable cnt 0)
13113 (while (setq e (pop tbl))
13114 (cond
13115 ((equal e '(:startgroup))
13116 (push '() groups) (setq ingroup t)
13117 (unless (= cnt 0)
13118 (setq cnt 0)
13119 (insert "\n"))
13120 (insert "{ "))
13121 ((equal e '(:endgroup))
13122 (setq ingroup nil cnt 0)
13123 (insert "}\n"))
13124 ((equal e '(:newline))
13125 (unless (= cnt 0)
13126 (setq cnt 0)
13127 (insert "\n")
13128 (setq e (car tbl))
13129 (while (equal (car tbl) '(:newline))
13130 (insert "\n")
13131 (setq tbl (cdr tbl)))))
13133 (setq tg (car e) c (cdr e))
13134 (when ingroup (push tg (car groups)))
13135 (setq tg (org-add-props tg nil 'face
13136 (org-get-todo-face tg)))
13137 (when (and (= cnt 0) (not ingroup)) (insert " "))
13138 (insert "[" c "] " tg (make-string
13139 (- fwidth 4 (length tg)) ?\ ))
13140 (when (= (setq cnt (1+ cnt)) ncol)
13141 (insert "\n")
13142 (when ingroup (insert " "))
13143 (setq cnt 0)))))
13144 (insert "\n")
13145 (goto-char (point-min))
13146 (unless expert (org-fit-window-to-buffer))
13147 (message "[a-z..]:Set [SPC]:clear")
13148 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13149 (cond
13150 ((or (= c ?\C-g)
13151 (and (= c ?q) (not (rassoc c fulltable))))
13152 (setq quit-flag t))
13153 ((= c ?\ ) nil)
13154 ((setq e (rassoc c fulltable) tg (car e))
13156 (t (setq quit-flag t)))))))
13158 (defun org-entry-is-todo-p ()
13159 (member (org-get-todo-state) org-not-done-keywords))
13161 (defun org-entry-is-done-p ()
13162 (member (org-get-todo-state) org-done-keywords))
13164 (defun org-get-todo-state ()
13165 "Return the TODO keyword of the current subtree."
13166 (save-excursion
13167 (org-back-to-heading t)
13168 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13169 (match-end 2)
13170 (match-string 2))))
13172 (defun org-at-date-range-p (&optional inactive-ok)
13173 "Non-nil if point is inside a date range.
13175 When optional argument INACTIVE-OK is non-nil, also consider
13176 inactive time ranges.
13178 When this function returns a non-nil value, match data is set
13179 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13180 on INACTIVE-OK."
13181 (interactive)
13182 (save-excursion
13183 (catch 'exit
13184 (let ((pos (point)))
13185 (skip-chars-backward "^[<\r\n")
13186 (skip-chars-backward "<[")
13187 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13188 (>= (match-end 0) pos)
13189 (throw 'exit t))
13190 (skip-chars-backward "^<[\r\n")
13191 (skip-chars-backward "<[")
13192 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13193 (>= (match-end 0) pos)
13194 (throw 'exit t)))
13195 nil)))
13197 (defun org-get-repeat (&optional tagline)
13198 "Check if there is a deadline/schedule with repeater in this entry."
13199 (save-match-data
13200 (save-excursion
13201 (org-back-to-heading t)
13202 (let ((end (org-entry-end-position))
13203 (regexp (if tagline (concat tagline "\\s-*" org-repeat-re)
13204 org-repeat-re)))
13205 (catch :repeat
13206 (while (re-search-forward regexp end t)
13207 (when (org-at-timestamp-p)
13208 (throw :repeat (match-string-no-properties 1)))))))))
13210 (defvar org-last-changed-timestamp)
13211 (defvar org-last-inserted-timestamp)
13212 (defvar org-log-post-message)
13213 (defvar org-log-note-purpose)
13214 (defvar org-log-note-how nil)
13215 (defvar org-log-note-extra)
13216 (defun org-auto-repeat-maybe (done-word)
13217 "Check if the current headline contains a repeated time-stamp.
13219 If yes, set TODO state back to what it was and change the base date
13220 of repeating deadline/scheduled time stamps to new date.
13222 This function is run automatically after each state change to a DONE state."
13223 (let* ((repeat (org-get-repeat))
13224 (aa (assoc org-last-state org-todo-kwd-alist))
13225 (interpret (nth 1 aa))
13226 (head (nth 2 aa))
13227 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13228 (msg "Entry repeats: ")
13229 (org-log-done nil)
13230 (org-todo-log-states nil)
13231 (end (copy-marker (org-entry-end-position))))
13232 (unwind-protect
13233 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13234 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13235 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13236 org-todo-repeat-to-state)))
13237 (org-todo (cond
13238 ((and to-state (member to-state org-todo-keywords-1))
13239 to-state)
13240 ((eq interpret 'type) org-last-state)
13241 (head)
13242 (t 'none))))
13243 (org-back-to-heading t)
13244 (org-add-planning-info nil nil 'closed)
13245 ;; When `org-log-repeat' is non-nil or entry contains
13246 ;; a clock, set LAST_REPEAT property.
13247 (when (or org-log-repeat
13248 (catch :clock
13249 (while (re-search-forward org-clock-line-re end t)
13250 (when (org-at-clock-log-p) (throw :clock t)))))
13251 (org-entry-put nil "LAST_REPEAT" (format-time-string
13252 (org-time-stamp-format t t)
13253 (current-time))))
13254 (when org-log-repeat
13255 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13256 (memq 'org-add-log-note post-command-hook))
13257 ;; We are already setup for some record.
13258 (when (eq org-log-repeat 'note)
13259 ;; Make sure we take a note, not only a time stamp.
13260 (setq org-log-note-how 'note))
13261 ;; Set up for taking a record.
13262 (org-add-log-setup 'state
13263 (or done-word (car org-done-keywords))
13264 org-last-state
13265 org-log-repeat)))
13266 (let ((planning-re (regexp-opt
13267 (list org-scheduled-string org-deadline-string))))
13268 (while (re-search-forward org-ts-regexp end t)
13269 (let* ((ts (match-string 0))
13270 (planning? (org-at-planning-p))
13271 (type (if (not planning?) "Plain:"
13272 (save-excursion
13273 (re-search-backward
13274 planning-re (line-beginning-position) t)
13275 (match-string 0)))))
13276 (cond
13277 ;; Ignore fake time-stamps (e.g., within comments).
13278 ((not (org-at-timestamp-p t)))
13279 ;; Time-stamps without a repeater are usually
13280 ;; skipped. However, a SCHEDULED time-stamp without
13281 ;; one is removed, as they are no longer relevant.
13282 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13283 ts))
13284 (when (equal type org-scheduled-string)
13285 (org-remove-timestamp-with-keyword type)))
13287 (let ((n (string-to-number (match-string 2 ts)))
13288 (what (match-string 3 ts)))
13289 (when (equal what "w") (setq n (* n 7) what "d"))
13290 (when (and (equal what "h")
13291 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13292 ts)))
13293 (user-error
13294 "Cannot repeat in Repeat in %d hour(s) because no hour \
13295 has been set"
13297 ;; Preparation, see if we need to modify the start
13298 ;; date for the change.
13299 (when (match-end 1)
13300 (let ((time (save-match-data
13301 (org-time-string-to-time ts))))
13302 (cond
13303 ((equal (match-string 1 ts) ".")
13304 ;; Shift starting date to today
13305 (org-timestamp-change
13306 (- (org-today) (time-to-days time))
13307 'day))
13308 ((equal (match-string 1 ts) "+")
13309 (let ((nshiftmax 10)
13310 (nshift 0))
13311 (while (or (= nshift 0)
13312 (not (time-less-p (current-time) time)))
13313 (when (= (cl-incf nshift) nshiftmax)
13314 (or (y-or-n-p
13315 (format "%d repeater intervals were not \
13316 enough to shift date past today. Continue? "
13317 nshift))
13318 (user-error "Abort")))
13319 (org-timestamp-change n (cdr (assoc what whata)))
13320 (org-in-regexp org-ts-regexp3)
13321 (setq ts (match-string 1))
13322 (setq time
13323 (save-match-data
13324 (org-time-string-to-time ts)))))
13325 (org-timestamp-change (- n) (cdr (assoc what whata)))
13326 ;; Rematch, so that we have everything in place
13327 ;; for the real shift.
13328 (org-in-regexp org-ts-regexp3)
13329 (setq ts (match-string 1))
13330 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13331 ts)))))
13332 (save-excursion
13333 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13334 (setq msg
13335 (concat
13336 msg type " " org-last-changed-timestamp " "))))))))
13337 (setq org-log-post-message msg)
13338 (message "%s" msg))
13339 (set-marker end nil))))
13341 (defun org-show-todo-tree (arg)
13342 "Make a compact tree which shows all headlines marked with TODO.
13343 The tree will show the lines where the regexp matches, and all higher
13344 headlines above the match.
13345 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13346 With a numeric prefix N, construct a sparse tree for the Nth element
13347 of `org-todo-keywords-1'."
13348 (interactive "P")
13349 (let ((case-fold-search nil)
13350 (kwd-re
13351 (cond ((null arg) org-not-done-regexp)
13352 ((equal arg '(4))
13353 (let ((kwd
13354 (completing-read "Keyword (or KWD1|KWD2|...): "
13355 (mapcar #'list org-todo-keywords-1))))
13356 (concat "\\("
13357 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13358 "\\)\\>")))
13359 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13360 (regexp-quote (nth (1- (prefix-numeric-value arg))
13361 org-todo-keywords-1)))
13362 (t (user-error "Invalid prefix argument: %s" arg)))))
13363 (message "%d TODO entries found"
13364 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13366 (defun org--deadline-or-schedule (arg type time)
13367 "Insert DEADLINE or SCHEDULE information in current entry.
13368 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13369 `org-schedule' for information about ARG and TIME arguments."
13370 (let* ((deadline? (eq type 'deadline))
13371 (keyword (if deadline? org-deadline-string org-scheduled-string))
13372 (log (if deadline? org-log-redeadline org-log-reschedule))
13373 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13374 (old-date-time (and old-date (org-time-string-to-time old-date)))
13375 ;; Save repeater cookie from either TIME or current scheduled
13376 ;; time stamp. We are going to insert it back at the end of
13377 ;; the process.
13378 (repeater (or (and (org-string-nw-p time)
13379 ;; We use `org-repeat-re' because we need
13380 ;; to tell the difference between a real
13381 ;; repeater and a time delta, e.g. "+2d".
13382 (string-match org-repeat-re time)
13383 (match-string 1 time))
13384 (and (org-string-nw-p old-date)
13385 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13386 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13387 old-date)
13388 (match-string 1 old-date)))))
13389 (pcase arg
13390 (`(4)
13391 (when (and old-date log)
13392 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13393 nil old-date log))
13394 (org-remove-timestamp-with-keyword keyword)
13395 (message (if deadline? "Item no longer has a deadline."
13396 "Item is no longer scheduled.")))
13397 (`(16)
13398 (save-excursion
13399 (org-back-to-heading t)
13400 (let ((regexp (if deadline? org-deadline-time-regexp
13401 org-scheduled-time-regexp)))
13402 (if (not (re-search-forward regexp (line-end-position 2) t))
13403 (user-error (if deadline? "No deadline information to update"
13404 "No scheduled information to update"))
13405 (let* ((rpl0 (match-string 1))
13406 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13407 (msg (if deadline? "Warn starting from" "Delay until")))
13408 (replace-match
13409 (concat keyword
13410 " <" rpl
13411 (format " -%dd"
13412 (abs (- (time-to-days
13413 (save-match-data
13414 (org-read-date
13415 nil t nil msg old-date-time)))
13416 (time-to-days old-date-time))))
13417 ">") t t))))))
13419 (org-add-planning-info type time 'closed)
13420 (when (and old-date
13422 (not (equal old-date org-last-inserted-timestamp)))
13423 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13424 org-last-inserted-timestamp
13425 old-date
13426 log))
13427 (when repeater
13428 (save-excursion
13429 (org-back-to-heading t)
13430 (when (re-search-forward
13431 (concat keyword " " org-last-inserted-timestamp)
13432 (line-end-position 2)
13434 (goto-char (1- (match-end 0)))
13435 (insert " " repeater)
13436 (setq org-last-inserted-timestamp
13437 (concat (substring org-last-inserted-timestamp 0 -1)
13438 " " repeater
13439 (substring org-last-inserted-timestamp -1))))))
13440 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13441 org-last-inserted-timestamp)))))
13443 (defun org-deadline (arg &optional time)
13444 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13445 With one universal prefix argument, remove any deadline from the item.
13446 With two universal prefix arguments, prompt for a warning delay.
13447 With argument TIME, set the deadline at the corresponding date. TIME
13448 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13449 (interactive "P")
13450 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13451 (org-map-entries
13452 (lambda () (org--deadline-or-schedule arg 'deadline time))
13454 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13455 'region-start-level
13456 'region)
13457 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13458 (org--deadline-or-schedule arg 'deadline time)))
13460 (defun org-schedule (arg &optional time)
13461 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13462 With one universal prefix argument, remove any scheduling date from the item.
13463 With two universal prefix arguments, prompt for a delay cookie.
13464 With argument TIME, scheduled at the corresponding date. TIME can
13465 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13466 (interactive "P")
13467 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13468 (org-map-entries
13469 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13471 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13472 'region-start-level
13473 'region)
13474 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13475 (org--deadline-or-schedule arg 'scheduled time)))
13477 (defun org-get-scheduled-time (pom &optional inherit)
13478 "Get the scheduled time as a time tuple, of a format suitable
13479 for calling org-schedule with, or if there is no scheduling,
13480 returns nil."
13481 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13482 (when time
13483 (apply 'encode-time (org-parse-time-string time)))))
13485 (defun org-get-deadline-time (pom &optional inherit)
13486 "Get the deadline as a time tuple, of a format suitable for
13487 calling org-deadline with, or if there is no scheduling, returns
13488 nil."
13489 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13490 (when time
13491 (apply 'encode-time (org-parse-time-string time)))))
13493 (defun org-remove-timestamp-with-keyword (keyword)
13494 "Remove all time stamps with KEYWORD in the current entry."
13495 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13496 beg)
13497 (save-excursion
13498 (org-back-to-heading t)
13499 (setq beg (point))
13500 (outline-next-heading)
13501 (while (re-search-backward re beg t)
13502 (replace-match "")
13503 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13504 (equal (char-before) ?\ ))
13505 (backward-delete-char 1)
13506 (when (string-match "^[ \t]*$" (buffer-substring
13507 (point-at-bol) (point-at-eol)))
13508 (delete-region (point-at-bol)
13509 (min (point-max) (1+ (point-at-eol))))))))))
13511 (defvar org-time-was-given) ; dynamically scoped parameter
13512 (defvar org-end-time-was-given) ; dynamically scoped parameter
13514 (defun org-at-planning-p ()
13515 "Non-nil when point is on a planning info line."
13516 ;; This is as accurate and faster than `org-element-at-point' since
13517 ;; planning info location is fixed in the section.
13518 (org-with-wide-buffer
13519 (beginning-of-line)
13520 (and (looking-at-p org-planning-line-re)
13521 (eq (point)
13522 (ignore-errors
13523 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13524 (org-back-to-heading t)
13525 (org-with-limited-levels (org-back-to-heading t)))
13526 (line-beginning-position 2))))))
13528 (defun org-add-planning-info (what &optional time &rest remove)
13529 "Insert new timestamp with keyword in the planning line.
13530 WHAT indicates what kind of time stamp to add. It is a symbol
13531 among `closed', `deadline', `scheduled' and nil. TIME indicates
13532 the time to use. If none is given, the user is prompted for
13533 a date. REMOVE indicates what kind of entries to remove. An old
13534 WHAT entry will also be removed."
13535 (let (org-time-was-given org-end-time-was-given default-time default-input)
13536 (catch 'exit
13537 (when (and (memq what '(scheduled deadline))
13538 (or (not time)
13539 (and (stringp time)
13540 (string-match "^[-+]+[0-9]" time))))
13541 ;; Try to get a default date/time from existing timestamp
13542 (save-excursion
13543 (org-back-to-heading t)
13544 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13545 (when (re-search-forward (if (eq what 'scheduled)
13546 org-scheduled-time-regexp
13547 org-deadline-time-regexp)
13548 end t)
13549 (setq ts (match-string 1)
13550 default-time (apply 'encode-time (org-parse-time-string ts))
13551 default-input (and ts (org-get-compact-tod ts)))))))
13552 (when what
13553 (setq time
13554 (if (stringp time)
13555 ;; This is a string (relative or absolute), set
13556 ;; proper date.
13557 (apply #'encode-time
13558 (org-read-date-analyze
13559 time default-time (decode-time default-time)))
13560 ;; If necessary, get the time from the user
13561 (or time (org-read-date nil 'to-time nil nil
13562 default-time default-input)))))
13564 (org-with-wide-buffer
13565 (org-back-to-heading t)
13566 (forward-line)
13567 (unless (bolp) (insert "\n"))
13568 (cond ((looking-at-p org-planning-line-re)
13569 ;; Move to current indentation.
13570 (skip-chars-forward " \t")
13571 ;; Check if we have to remove something.
13572 (dolist (type (if what (cons what remove) remove))
13573 (save-excursion
13574 (when (re-search-forward
13575 (cl-case type
13576 (closed org-closed-time-regexp)
13577 (deadline org-deadline-time-regexp)
13578 (scheduled org-scheduled-time-regexp)
13579 (otherwise
13580 (error "Invalid planning type: %s" type)))
13581 (line-end-position) t)
13582 ;; Delete until next keyword or end of line.
13583 (delete-region
13584 (match-beginning 0)
13585 (if (re-search-forward org-keyword-time-not-clock-regexp
13586 (line-end-position)
13588 (match-beginning 0)
13589 (line-end-position))))))
13590 ;; If there is nothing more to add and no more keyword
13591 ;; is left, remove the line completely.
13592 (if (and (looking-at-p "[ \t]*$") (not what))
13593 (delete-region (line-beginning-position)
13594 (line-beginning-position 2))
13595 ;; If we removed last keyword, do not leave trailing
13596 ;; white space at the end of line.
13597 (let ((p (point)))
13598 (save-excursion
13599 (end-of-line)
13600 (unless (= (skip-chars-backward " \t" p) 0)
13601 (delete-region (point) (line-end-position)))))))
13602 ((not what) (throw 'exit nil)) ; Nothing to do.
13603 (t (insert-before-markers "\n")
13604 (backward-char 1)
13605 (when org-adapt-indentation
13606 (indent-to-column (1+ (org-outline-level))))))
13607 (when what
13608 ;; Insert planning keyword.
13609 (insert (cl-case what
13610 (closed org-closed-string)
13611 (deadline org-deadline-string)
13612 (scheduled org-scheduled-string)
13613 (otherwise (error "Invalid planning type: %s" what)))
13614 " ")
13615 ;; Insert associated timestamp.
13616 (let ((ts (org-insert-time-stamp
13617 time
13618 (or org-time-was-given
13619 (and (eq what 'closed) org-log-done-with-time))
13620 (eq what 'closed)
13621 nil nil (list org-end-time-was-given))))
13622 (unless (eolp) (insert " "))
13623 ts))))))
13625 (defvar org-log-note-marker (make-marker)
13626 "Marker pointing at the entry where the note is to be inserted.")
13627 (defvar org-log-note-purpose nil)
13628 (defvar org-log-note-state nil)
13629 (defvar org-log-note-previous-state nil)
13630 (defvar org-log-note-extra nil)
13631 (defvar org-log-note-window-configuration nil)
13632 (defvar org-log-note-return-to (make-marker))
13633 (defvar org-log-note-effective-time nil
13634 "Remembered current time so that dynamically scoped
13635 `org-extend-today-until' affects timestamps in state change log")
13637 (defvar org-log-post-message nil
13638 "Message to be displayed after a log note has been stored.
13639 The auto-repeater uses this.")
13641 (defun org-add-note ()
13642 "Add a note to the current entry.
13643 This is done in the same way as adding a state change note."
13644 (interactive)
13645 (org-add-log-setup 'note))
13647 (defun org-log-beginning (&optional create)
13648 "Return expected start of log notes in current entry.
13649 When optional argument CREATE is non-nil, the function creates
13650 a drawer to store notes, if necessary. Returned position ignores
13651 narrowing."
13652 (org-with-wide-buffer
13653 (let ((drawer (org-log-into-drawer)))
13654 (cond
13655 (drawer
13656 (org-end-of-meta-data)
13657 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13658 (end (if (org-at-heading-p) (point)
13659 (save-excursion (outline-next-heading) (point))))
13660 (case-fold-search t))
13661 (catch 'exit
13662 ;; Try to find existing drawer.
13663 (while (re-search-forward regexp end t)
13664 (let ((element (org-element-at-point)))
13665 (when (eq (org-element-type element) 'drawer)
13666 (let ((cend (org-element-property :contents-end element)))
13667 (when (and (not org-log-states-order-reversed) cend)
13668 (goto-char cend)))
13669 (throw 'exit nil))))
13670 ;; No drawer found. Create one, if permitted.
13671 (when create
13672 (unless (bolp) (insert "\n"))
13673 (let ((beg (point)))
13674 (insert ":" drawer ":\n:END:\n")
13675 (org-indent-region beg (point)))
13676 (end-of-line -1)))))
13678 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13679 (skip-chars-forward " \t\n")
13680 (beginning-of-line)
13681 (unless org-log-states-order-reversed
13682 (org-skip-over-state-notes)
13683 (skip-chars-backward " \t\n")
13684 (forward-line)))))
13685 (if (bolp) (point) (line-beginning-position 2))))
13687 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13688 "Set up the post command hook to take a note.
13689 If this is about to TODO state change, the new state is expected in STATE.
13690 HOW is an indicator what kind of note should be created.
13691 EXTRA is additional text that will be inserted into the notes buffer."
13692 (move-marker org-log-note-marker (point))
13693 (setq org-log-note-purpose purpose
13694 org-log-note-state state
13695 org-log-note-previous-state prev-state
13696 org-log-note-how how
13697 org-log-note-extra extra
13698 org-log-note-effective-time (org-current-effective-time))
13699 (add-hook 'post-command-hook 'org-add-log-note 'append))
13701 (defun org-skip-over-state-notes ()
13702 "Skip past the list of State notes in an entry."
13703 (when (ignore-errors (goto-char (org-in-item-p)))
13704 (let* ((struct (org-list-struct))
13705 (prevs (org-list-prevs-alist struct))
13706 (regexp
13707 (concat "[ \t]*- +"
13708 (replace-regexp-in-string
13709 " +" " +"
13710 (org-replace-escapes
13711 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13712 `(("%d" . ,org-ts-regexp-inactive)
13713 ("%D" . ,org-ts-regexp)
13714 ("%s" . "\"\\S-+\"")
13715 ("%S" . "\"\\S-+\"")
13716 ("%t" . ,org-ts-regexp-inactive)
13717 ("%T" . ,org-ts-regexp)
13718 ("%u" . ".*?")
13719 ("%U" . ".*?")))))))
13720 (while (looking-at-p regexp)
13721 (goto-char (or (org-list-get-next-item (point) struct prevs)
13722 (org-list-get-item-end (point) struct)))))))
13724 (defun org-add-log-note (&optional _purpose)
13725 "Pop up a window for taking a note, and add this note later."
13726 (remove-hook 'post-command-hook 'org-add-log-note)
13727 (setq org-log-note-window-configuration (current-window-configuration))
13728 (delete-other-windows)
13729 (move-marker org-log-note-return-to (point))
13730 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13731 (goto-char org-log-note-marker)
13732 (org-switch-to-buffer-other-window "*Org Note*")
13733 (erase-buffer)
13734 (if (memq org-log-note-how '(time state))
13735 (let (current-prefix-arg) (org-store-log-note))
13736 (let ((org-inhibit-startup t)) (org-mode))
13737 (insert (format "# Insert note for %s.
13738 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13739 (cond
13740 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13741 ((eq org-log-note-purpose 'done) "closed todo item")
13742 ((eq org-log-note-purpose 'state)
13743 (format "state change from \"%s\" to \"%s\""
13744 (or org-log-note-previous-state "")
13745 (or org-log-note-state "")))
13746 ((eq org-log-note-purpose 'reschedule)
13747 "rescheduling")
13748 ((eq org-log-note-purpose 'delschedule)
13749 "no longer scheduled")
13750 ((eq org-log-note-purpose 'redeadline)
13751 "changing deadline")
13752 ((eq org-log-note-purpose 'deldeadline)
13753 "removing deadline")
13754 ((eq org-log-note-purpose 'refile)
13755 "refiling")
13756 ((eq org-log-note-purpose 'note)
13757 "this entry")
13758 (t (error "This should not happen")))))
13759 (when org-log-note-extra (insert org-log-note-extra))
13760 (setq-local org-finish-function 'org-store-log-note)
13761 (run-hooks 'org-log-buffer-setup-hook)))
13763 (defvar org-note-abort nil) ; dynamically scoped
13764 (defun org-store-log-note ()
13765 "Finish taking a log note, and insert it to where it belongs."
13766 (let ((txt (prog1 (buffer-string)
13767 (kill-buffer)))
13768 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13769 lines)
13770 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13771 (setq txt (replace-match "" t t txt)))
13772 (when (string-match "\\s-+\\'" txt)
13773 (setq txt (replace-match "" t t txt)))
13774 (setq lines (org-split-string txt "\n"))
13775 (when (org-string-nw-p note)
13776 (setq note
13777 (org-replace-escapes
13778 note
13779 (list (cons "%u" (user-login-name))
13780 (cons "%U" user-full-name)
13781 (cons "%t" (format-time-string
13782 (org-time-stamp-format 'long 'inactive)
13783 org-log-note-effective-time))
13784 (cons "%T" (format-time-string
13785 (org-time-stamp-format 'long nil)
13786 org-log-note-effective-time))
13787 (cons "%d" (format-time-string
13788 (org-time-stamp-format nil 'inactive)
13789 org-log-note-effective-time))
13790 (cons "%D" (format-time-string
13791 (org-time-stamp-format nil nil)
13792 org-log-note-effective-time))
13793 (cons "%s" (cond
13794 ((not org-log-note-state) "")
13795 ((string-match-p org-ts-regexp
13796 org-log-note-state)
13797 (format "\"[%s]\""
13798 (substring org-log-note-state 1 -1)))
13799 (t (format "\"%s\"" org-log-note-state))))
13800 (cons "%S"
13801 (cond
13802 ((not org-log-note-previous-state) "")
13803 ((string-match-p org-ts-regexp
13804 org-log-note-previous-state)
13805 (format "\"[%s]\""
13806 (substring
13807 org-log-note-previous-state 1 -1)))
13808 (t (format "\"%s\""
13809 org-log-note-previous-state)))))))
13810 (when lines (setq note (concat note " \\\\")))
13811 (push note lines))
13812 (when (and lines (not (or current-prefix-arg org-note-abort)))
13813 (with-current-buffer (marker-buffer org-log-note-marker)
13814 (org-with-wide-buffer
13815 ;; Find location for the new note.
13816 (goto-char org-log-note-marker)
13817 (set-marker org-log-note-marker nil)
13818 (goto-char (org-log-beginning t))
13819 ;; Make sure point is at the beginning of an empty line.
13820 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13821 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13822 ;; In an existing list, add a new item at the top level.
13823 ;; Otherwise, indent line like a regular one.
13824 (let ((itemp (org-in-item-p)))
13825 (if itemp
13826 (indent-line-to
13827 (let ((struct (save-excursion
13828 (goto-char itemp) (org-list-struct))))
13829 (org-list-get-ind (org-list-get-top-point struct) struct)))
13830 (org-indent-line)))
13831 (insert (org-list-bullet-string "-") (pop lines))
13832 (let ((ind (org-list-item-body-column (line-beginning-position))))
13833 (dolist (line lines)
13834 (insert "\n")
13835 (indent-line-to ind)
13836 (insert line)))
13837 (message "Note stored")
13838 (org-back-to-heading t)
13839 (org-cycle-hide-drawers 'children))
13840 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13841 ;; from within `org-add-log-note' because `buffer-undo-list'
13842 ;; is then modified outside of `org-with-remote-undo'.
13843 (when (eq this-command 'org-agenda-todo)
13844 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13845 ;; Don't add undo information when called from `org-agenda-todo'.
13846 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13847 (set-window-configuration org-log-note-window-configuration)
13848 (with-current-buffer (marker-buffer org-log-note-return-to)
13849 (goto-char org-log-note-return-to))
13850 (move-marker org-log-note-return-to nil)
13851 (when org-log-post-message (message "%s" org-log-post-message))))
13853 (defun org-remove-empty-drawer-at (pos)
13854 "Remove an empty drawer at position POS.
13855 POS may also be a marker."
13856 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13857 (org-with-wide-buffer
13858 (goto-char pos)
13859 (let ((drawer (org-element-at-point)))
13860 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13861 (not (org-element-property :contents-begin drawer)))
13862 (delete-region (org-element-property :begin drawer)
13863 (progn (goto-char (org-element-property :end drawer))
13864 (skip-chars-backward " \r\t\n")
13865 (forward-line)
13866 (point))))))))
13868 (defvar org-ts-type nil)
13869 (defun org-sparse-tree (&optional arg type)
13870 "Create a sparse tree, prompt for the details.
13871 This command can create sparse trees. You first need to select the type
13872 of match used to create the tree:
13874 t Show all TODO entries.
13875 T Show entries with a specific TODO keyword.
13876 m Show entries selected by a tags/property match.
13877 p Enter a property name and its value (both with completion on existing
13878 names/values) and show entries with that property.
13879 r Show entries matching a regular expression (`/' can be used as well).
13880 b Show deadlines and scheduled items before a date.
13881 a Show deadlines and scheduled items after a date.
13882 d Show deadlines due within `org-deadline-warning-days'.
13883 D Show deadlines and scheduled items between a date range."
13884 (interactive "P")
13885 (setq type (or type org-sparse-tree-default-date-type))
13886 (setq org-ts-type type)
13887 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13888 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13889 \[c]ycle through date types: %s"
13890 (cl-case type
13891 (all "all timestamps")
13892 (scheduled "only scheduled")
13893 (deadline "only deadline")
13894 (active "only active timestamps")
13895 (inactive "only inactive timestamps")
13896 (closed "with a closed time-stamp")
13897 (otherwise "scheduled/deadline")))
13898 (let ((answer (read-char-exclusive)))
13899 (cl-case answer
13901 (org-sparse-tree
13903 (cadr
13904 (memq type '(nil all scheduled deadline active inactive closed)))))
13905 (?d (call-interactively 'org-check-deadlines))
13906 (?b (call-interactively 'org-check-before-date))
13907 (?a (call-interactively 'org-check-after-date))
13908 (?D (call-interactively 'org-check-dates-range))
13909 (?t (call-interactively 'org-show-todo-tree))
13910 (?T (org-show-todo-tree '(4)))
13911 (?m (call-interactively 'org-match-sparse-tree))
13912 ((?p ?P)
13913 (let* ((kwd (completing-read
13914 "Property: " (mapcar #'list (org-buffer-property-keys))))
13915 (value (completing-read
13916 "Value: " (mapcar #'list (org-property-values kwd)))))
13917 (unless (string-match "\\`{.*}\\'" value)
13918 (setq value (concat "\"" value "\"")))
13919 (org-match-sparse-tree arg (concat kwd "=" value))))
13920 ((?r ?R ?/) (call-interactively 'org-occur))
13921 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13923 (defvar-local org-occur-highlights nil
13924 "List of overlays used for occur matches.")
13925 (defvar-local org-occur-parameters nil
13926 "Parameters of the active org-occur calls.
13927 This is a list, each call to org-occur pushes as cons cell,
13928 containing the regular expression and the callback, onto the list.
13929 The list can contain several entries if `org-occur' has been called
13930 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13931 will only contain one set of parameters. When the highlights are
13932 removed (for example with `C-c C-c', or with the next edit (depending
13933 on `org-remove-highlights-with-change'), this variable is emptied
13934 as well.")
13936 (defun org-occur (regexp &optional keep-previous callback)
13937 "Make a compact tree which shows all matches of REGEXP.
13939 The tree will show the lines where the regexp matches, and any other context
13940 defined in `org-show-context-detail', which see.
13942 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13943 done by a previous call to `org-occur' will be kept, to allow stacking of
13944 calls to this command.
13946 Optional argument CALLBACK can be a function of no argument. In this case,
13947 it is called with point at the end of the match, match data being set
13948 accordingly. Current match is shown only if the return value is non-nil.
13949 The function must neither move point nor alter narrowing."
13950 (interactive "sRegexp: \nP")
13951 (when (equal regexp "")
13952 (user-error "Regexp cannot be empty"))
13953 (unless keep-previous
13954 (org-remove-occur-highlights nil nil t))
13955 (push (cons regexp callback) org-occur-parameters)
13956 (let ((cnt 0))
13957 (save-excursion
13958 (goto-char (point-min))
13959 (when (or (not keep-previous) ; do not want to keep
13960 (not org-occur-highlights)) ; no previous matches
13961 ;; hide everything
13962 (org-overview))
13963 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13964 (isearch-no-upper-case-p regexp t)
13965 org-occur-case-fold-search)))
13966 (while (re-search-forward regexp nil t)
13967 (when (or (not callback)
13968 (save-match-data (funcall callback)))
13969 (setq cnt (1+ cnt))
13970 (when org-highlight-sparse-tree-matches
13971 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13972 (org-show-context 'occur-tree)))))
13973 (when org-remove-highlights-with-change
13974 (add-hook 'before-change-functions 'org-remove-occur-highlights
13975 nil 'local))
13976 (unless org-sparse-tree-open-archived-trees
13977 (org-hide-archived-subtrees (point-min) (point-max)))
13978 (run-hooks 'org-occur-hook)
13979 (when (called-interactively-p 'interactive)
13980 (message "%d match(es) for regexp %s" cnt regexp))
13981 cnt))
13983 (defun org-occur-next-match (&optional n _reset)
13984 "Function for `next-error-function' to find sparse tree matches.
13985 N is the number of matches to move, when negative move backwards.
13986 This function always goes back to the starting point when no
13987 match is found."
13988 (let* ((limit (if (< n 0) (point-min) (point-max)))
13989 (search-func (if (< n 0)
13990 'previous-single-char-property-change
13991 'next-single-char-property-change))
13992 (n (abs n))
13993 (pos (point))
13995 (catch 'exit
13996 (while (setq p1 (funcall search-func (point) 'org-type))
13997 (when (equal p1 limit)
13998 (goto-char pos)
13999 (user-error "No more matches"))
14000 (when (equal (get-char-property p1 'org-type) 'org-occur)
14001 (setq n (1- n))
14002 (when (= n 0)
14003 (goto-char p1)
14004 (throw 'exit (point))))
14005 (goto-char p1))
14006 (goto-char p1)
14007 (user-error "No more matches"))))
14009 (defun org-show-context (&optional key)
14010 "Make sure point and context are visible.
14011 Optional argument KEY, when non-nil, is a symbol. See
14012 `org-show-context-detail' for allowed values and how much is to
14013 be shown."
14014 (org-show-set-visibility
14015 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14016 ((cdr (assq key org-show-context-detail)))
14017 (t (cdr (assq 'default org-show-context-detail))))))
14019 (defun org-show-set-visibility (detail)
14020 "Set visibility around point according to DETAIL.
14021 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14022 `tree', `canonical' or t. See `org-show-context-detail' for more
14023 information."
14024 ;; Show current heading and possibly its entry, following headline
14025 ;; or all children.
14026 (if (and (org-at-heading-p) (not (eq detail 'local)))
14027 (org-flag-heading nil)
14028 (org-show-entry)
14029 ;; If point is hidden within a drawer or a block, make sure to
14030 ;; expose it.
14031 (dolist (o (overlays-at (point)))
14032 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14033 (delete-overlay o)))
14034 (unless (org-before-first-heading-p)
14035 (org-with-limited-levels
14036 (cl-case detail
14037 ((tree canonical t) (org-show-children))
14038 ((nil minimal ancestors))
14039 (t (save-excursion
14040 (outline-next-heading)
14041 (org-flag-heading nil)))))))
14042 ;; Show all siblings.
14043 (when (eq detail 'lineage) (org-show-siblings))
14044 ;; Show ancestors, possibly with their children.
14045 (when (memq detail '(ancestors lineage tree canonical t))
14046 (save-excursion
14047 (while (org-up-heading-safe)
14048 (org-flag-heading nil)
14049 (when (memq detail '(canonical t)) (org-show-entry))
14050 (when (memq detail '(tree canonical t)) (org-show-children))))))
14052 (defvar org-reveal-start-hook nil
14053 "Hook run before revealing a location.")
14055 (defun org-reveal (&optional siblings)
14056 "Show current entry, hierarchy above it, and the following headline.
14058 This can be used to show a consistent set of context around
14059 locations exposed with `org-show-context'.
14061 With optional argument SIBLINGS, on each level of the hierarchy all
14062 siblings are shown. This repairs the tree structure to what it would
14063 look like when opened with hierarchical calls to `org-cycle'.
14065 With a \\[universal-argument] \\[universal-argument] prefix, \
14066 go to the parent and show the entire tree."
14067 (interactive "P")
14068 (run-hooks 'org-reveal-start-hook)
14069 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14070 ((equal siblings '(16))
14071 (save-excursion
14072 (when (org-up-heading-safe)
14073 (org-show-subtree)
14074 (run-hook-with-args 'org-cycle-hook 'subtree))))
14075 (t (org-show-set-visibility 'lineage))))
14077 (defun org-highlight-new-match (beg end)
14078 "Highlight from BEG to END and mark the highlight is an occur headline."
14079 (let ((ov (make-overlay beg end)))
14080 (overlay-put ov 'face 'secondary-selection)
14081 (overlay-put ov 'org-type 'org-occur)
14082 (push ov org-occur-highlights)))
14084 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14085 "Remove the occur highlights from the buffer.
14086 BEG and END are ignored. If NOREMOVE is nil, remove this function
14087 from the `before-change-functions' in the current buffer."
14088 (interactive)
14089 (unless org-inhibit-highlight-removal
14090 (mapc #'delete-overlay org-occur-highlights)
14091 (setq org-occur-highlights nil)
14092 (setq org-occur-parameters nil)
14093 (unless noremove
14094 (remove-hook 'before-change-functions
14095 'org-remove-occur-highlights 'local))))
14097 ;;;; Priorities
14099 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14100 "Regular expression matching the priority indicator.")
14102 (defvar org-remove-priority-next-time nil)
14104 (defun org-priority-up ()
14105 "Increase the priority of the current item."
14106 (interactive)
14107 (org-priority 'up))
14109 (defun org-priority-down ()
14110 "Decrease the priority of the current item."
14111 (interactive)
14112 (org-priority 'down))
14114 (defun org-priority (&optional action _show)
14115 "Change the priority of an item.
14116 ACTION can be `set', `up', `down', or a character."
14117 (interactive "P")
14118 (if (equal action '(4))
14119 (org-show-priority)
14120 (unless org-enable-priority-commands
14121 (user-error "Priority commands are disabled"))
14122 (setq action (or action 'set))
14123 (let (current new news have remove)
14124 (save-excursion
14125 (org-back-to-heading t)
14126 (when (looking-at org-priority-regexp)
14127 (setq current (string-to-char (match-string 2))
14128 have t))
14129 (cond
14130 ((eq action 'remove)
14131 (setq remove t new ?\ ))
14132 ((or (eq action 'set)
14133 (integerp action))
14134 (if (not (eq action 'set))
14135 (setq new action)
14136 (message "Priority %c-%c, SPC to remove: "
14137 org-highest-priority org-lowest-priority)
14138 (save-match-data
14139 (setq new (read-char-exclusive))))
14140 (when (and (= (upcase org-highest-priority) org-highest-priority)
14141 (= (upcase org-lowest-priority) org-lowest-priority))
14142 (setq new (upcase new)))
14143 (cond ((equal new ?\ ) (setq remove t))
14144 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14145 (user-error "Priority must be between `%c' and `%c'"
14146 org-highest-priority org-lowest-priority))))
14147 ((eq action 'up)
14148 (setq new (if have
14149 (1- current) ; normal cycling
14150 ;; last priority was empty
14151 (if (eq last-command this-command)
14152 org-lowest-priority ; wrap around empty to lowest
14153 ;; default
14154 (if org-priority-start-cycle-with-default
14155 org-default-priority
14156 (1- org-default-priority))))))
14157 ((eq action 'down)
14158 (setq new (if have
14159 (1+ current) ; normal cycling
14160 ;; last priority was empty
14161 (if (eq last-command this-command)
14162 org-highest-priority ; wrap around empty to highest
14163 ;; default
14164 (if org-priority-start-cycle-with-default
14165 org-default-priority
14166 (1+ org-default-priority))))))
14167 (t (user-error "Invalid action")))
14168 (when (or (< (upcase new) org-highest-priority)
14169 (> (upcase new) org-lowest-priority))
14170 (if (and (memq action '(up down))
14171 (not have) (not (eq last-command this-command)))
14172 ;; `new' is from default priority
14173 (error
14174 "The default can not be set, see `org-default-priority' why")
14175 ;; normal cycling: `new' is beyond highest/lowest priority
14176 ;; and is wrapped around to the empty priority
14177 (setq remove t)))
14178 (setq news (format "%c" new))
14179 (if have
14180 (if remove
14181 (replace-match "" t t nil 1)
14182 (replace-match news t t nil 2))
14183 (if remove
14184 (user-error "No priority cookie found in line")
14185 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14186 (if (match-end 2)
14187 (progn
14188 (goto-char (match-end 2))
14189 (insert " [#" news "]"))
14190 (goto-char (match-beginning 3))
14191 (insert "[#" news "] "))))
14192 (org-set-tags nil 'align))
14193 (if remove
14194 (message "Priority removed")
14195 (message "Priority of current item set to %s" news)))))
14197 (defun org-show-priority ()
14198 "Show the priority of the current item.
14199 This priority is composed of the main priority given with the [#A] cookies,
14200 and by additional input from the age of a schedules or deadline entry."
14201 (interactive)
14202 (let ((pri (if (eq major-mode 'org-agenda-mode)
14203 (org-get-at-bol 'priority)
14204 (save-excursion
14205 (save-match-data
14206 (beginning-of-line)
14207 (and (looking-at org-heading-regexp)
14208 (org-get-priority (match-string 0))))))))
14209 (message "Priority is %d" (if pri pri -1000))))
14211 (defun org-get-priority (s)
14212 "Find priority cookie and return priority."
14213 (save-match-data
14214 (if (functionp org-get-priority-function)
14215 (funcall org-get-priority-function)
14216 (if (not (string-match org-priority-regexp s))
14217 (* 1000 (- org-lowest-priority org-default-priority))
14218 (* 1000 (- org-lowest-priority
14219 (string-to-char (match-string 2 s))))))))
14221 ;;;; Tags
14223 (defvar org-agenda-archives-mode)
14224 (defvar org-map-continue-from nil
14225 "Position from where mapping should continue.
14226 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14228 (defvar org-scanner-tags nil
14229 "The current tag list while the tags scanner is running.")
14231 (defvar org-trust-scanner-tags nil
14232 "Should `org-get-tags-at' use the tags for the scanner.
14233 This is for internal dynamical scoping only.
14234 When this is non-nil, the function `org-get-tags-at' will return the value
14235 of `org-scanner-tags' instead of building the list by itself. This
14236 can lead to large speed-ups when the tags scanner is used in a file with
14237 many entries, and when the list of tags is retrieved, for example to
14238 obtain a list of properties. Building the tags list for each entry in such
14239 a file becomes an N^2 operation - but with this variable set, it scales
14240 as N.")
14242 (defvar org--matcher-tags-todo-only nil)
14244 (defun org-scan-tags (action matcher todo-only &optional start-level)
14245 "Scan headline tags with inheritance and produce output ACTION.
14247 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14248 or `agenda' to produce an entry list for an agenda view. It can also be
14249 a Lisp form or a function that should be called at each matched headline, in
14250 this case the return value is a list of all return values from these calls.
14252 MATCHER is a function accepting three arguments, returning
14253 a non-nil value whenever a given set of tags qualifies a headline
14254 for inclusion. See `org-make-tags-matcher' for more information.
14255 As a special case, it can also be set to t (respectively nil) in
14256 order to match all (respectively none) headline.
14258 When TODO-ONLY is non-nil, only lines with a not-done TODO
14259 keyword are included in the output.
14261 START-LEVEL can be a string with asterisks, reducing the scope to
14262 headlines matching this string."
14263 (require 'org-agenda)
14264 (let* ((re (concat "^"
14265 (if start-level
14266 ;; Get the correct level to match
14267 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14268 org-outline-regexp)
14269 " *\\(\\<\\("
14270 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14271 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14272 (props (list 'face 'default
14273 'done-face 'org-agenda-done
14274 'undone-face 'default
14275 'mouse-face 'highlight
14276 'org-not-done-regexp org-not-done-regexp
14277 'org-todo-regexp org-todo-regexp
14278 'org-complex-heading-regexp org-complex-heading-regexp
14279 'help-echo
14280 (format "mouse-2 or RET jump to org file %s"
14281 (abbreviate-file-name
14282 (or (buffer-file-name (buffer-base-buffer))
14283 (buffer-name (buffer-base-buffer)))))))
14284 (org-map-continue-from nil)
14285 lspos tags tags-list
14286 (tags-alist (list (cons 0 org-file-tags)))
14287 (llast 0) rtn rtn1 level category i txt
14288 todo marker entry priority
14289 ts-date ts-date-type ts-date-pair)
14290 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14291 (setq action (list 'lambda nil action)))
14292 (save-excursion
14293 (goto-char (point-min))
14294 (when (eq action 'sparse-tree)
14295 (org-overview)
14296 (org-remove-occur-highlights))
14297 (while (let (case-fold-search)
14298 (re-search-forward re nil t))
14299 (setq org-map-continue-from nil)
14300 (catch :skip
14301 (setq todo
14302 ;; TODO: is the 1-2 difference a bug?
14303 (when (match-end 1) (match-string-no-properties 2))
14304 tags (when (match-end 4) (match-string-no-properties 4)))
14305 (goto-char (setq lspos (match-beginning 0)))
14306 (setq level (org-reduced-level (org-outline-level))
14307 category (org-get-category))
14308 (when (eq action 'agenda)
14309 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14310 ts-date (car ts-date-pair)
14311 ts-date-type (cdr ts-date-pair)))
14312 (setq i llast llast level)
14313 ;; remove tag lists from same and sublevels
14314 (while (>= i level)
14315 (when (setq entry (assoc i tags-alist))
14316 (setq tags-alist (delete entry tags-alist)))
14317 (setq i (1- i)))
14318 ;; add the next tags
14319 (when tags
14320 (setq tags (org-split-string tags ":")
14321 tags-alist
14322 (cons (cons level tags) tags-alist)))
14323 ;; compile tags for current headline
14324 (setq tags-list
14325 (if org-use-tag-inheritance
14326 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14327 tags)
14328 org-scanner-tags tags-list)
14329 (when org-use-tag-inheritance
14330 (setcdr (car tags-alist)
14331 (mapcar (lambda (x)
14332 (setq x (copy-sequence x))
14333 (org-add-prop-inherited x))
14334 (cdar tags-alist))))
14335 (when (and tags org-use-tag-inheritance
14336 (or (not (eq t org-use-tag-inheritance))
14337 org-tags-exclude-from-inheritance))
14338 ;; Selective inheritance, remove uninherited ones.
14339 (setcdr (car tags-alist)
14340 (org-remove-uninherited-tags (cdar tags-alist))))
14341 (when (and
14343 ;; eval matcher only when the todo condition is OK
14344 (and (or (not todo-only) (member todo org-not-done-keywords))
14345 (if (functionp matcher)
14346 (let ((case-fold-search t) (org-trust-scanner-tags t))
14347 (funcall matcher todo tags-list level))
14348 matcher))
14350 ;; Call the skipper, but return t if it does not
14351 ;; skip, so that the `and' form continues evaluating.
14352 (progn
14353 (unless (eq action 'sparse-tree) (org-agenda-skip))
14356 ;; Check if timestamps are deselecting this entry
14357 (or (not todo-only)
14358 (and (member todo org-not-done-keywords)
14359 (or (not org-agenda-tags-todo-honor-ignore-options)
14360 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14362 ;; select this headline
14363 (cond
14364 ((eq action 'sparse-tree)
14365 (and org-highlight-sparse-tree-matches
14366 (org-get-heading) (match-end 0)
14367 (org-highlight-new-match
14368 (match-beginning 1) (match-end 1)))
14369 (org-show-context 'tags-tree))
14370 ((eq action 'agenda)
14371 (setq txt (org-agenda-format-item
14373 (concat
14374 (if (eq org-tags-match-list-sublevels 'indented)
14375 (make-string (1- level) ?.) "")
14376 (org-get-heading))
14377 (make-string level ?\s)
14378 category
14379 tags-list)
14380 priority (org-get-priority txt))
14381 (goto-char lspos)
14382 (setq marker (org-agenda-new-marker))
14383 (org-add-props txt props
14384 'org-marker marker 'org-hd-marker marker 'org-category category
14385 'todo-state todo
14386 'ts-date ts-date
14387 'priority priority
14388 'type (concat "tagsmatch" ts-date-type))
14389 (push txt rtn))
14390 ((functionp action)
14391 (setq org-map-continue-from nil)
14392 (save-excursion
14393 (setq rtn1 (funcall action))
14394 (push rtn1 rtn)))
14395 (t (user-error "Invalid action")))
14397 ;; if we are to skip sublevels, jump to end of subtree
14398 (unless org-tags-match-list-sublevels
14399 (org-end-of-subtree t)
14400 (backward-char 1))))
14401 ;; Get the correct position from where to continue
14402 (if org-map-continue-from
14403 (goto-char org-map-continue-from)
14404 (and (= (point) lspos) (end-of-line 1)))))
14405 (when (and (eq action 'sparse-tree)
14406 (not org-sparse-tree-open-archived-trees))
14407 (org-hide-archived-subtrees (point-min) (point-max)))
14408 (nreverse rtn)))
14410 (defun org-remove-uninherited-tags (tags)
14411 "Remove all tags that are not inherited from the list TAGS."
14412 (cond
14413 ((eq org-use-tag-inheritance t)
14414 (if org-tags-exclude-from-inheritance
14415 (org-delete-all org-tags-exclude-from-inheritance tags)
14416 tags))
14417 ((not org-use-tag-inheritance) nil)
14418 ((stringp org-use-tag-inheritance)
14419 (delq nil (mapcar
14420 (lambda (x)
14421 (if (and (string-match org-use-tag-inheritance x)
14422 (not (member x org-tags-exclude-from-inheritance)))
14423 x nil))
14424 tags)))
14425 ((listp org-use-tag-inheritance)
14426 (delq nil (mapcar
14427 (lambda (x)
14428 (if (member x org-use-tag-inheritance) x nil))
14429 tags)))))
14431 (defun org-match-sparse-tree (&optional todo-only match)
14432 "Create a sparse tree according to tags string MATCH.
14434 MATCH is a string with match syntax. It can contain a selection
14435 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14436 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14437 those. See the manual for details.
14439 If optional argument TODO-ONLY is non-nil, only select lines that
14440 are also TODO tasks."
14441 (interactive "P")
14442 (org-agenda-prepare-buffers (list (current-buffer)))
14443 (let ((org--matcher-tags-todo-only todo-only))
14444 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14445 org--matcher-tags-todo-only)))
14447 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14449 (defvar org-cached-props nil)
14450 (defun org-cached-entry-get (pom property)
14451 (if (or (eq t org-use-property-inheritance)
14452 (and (stringp org-use-property-inheritance)
14453 (let ((case-fold-search t))
14454 (string-match-p org-use-property-inheritance property)))
14455 (and (listp org-use-property-inheritance)
14456 (member-ignore-case property org-use-property-inheritance)))
14457 ;; Caching is not possible, check it directly.
14458 (org-entry-get pom property 'inherit)
14459 ;; Get all properties, so we can do complicated checks easily.
14460 (cdr (assoc-string property
14461 (or org-cached-props
14462 (setq org-cached-props (org-entry-properties pom)))
14463 t))))
14465 (defun org-global-tags-completion-table (&optional files)
14466 "Return the list of all tags in all agenda buffer/files.
14467 Optional FILES argument is a list of files which can be used
14468 instead of the agenda files."
14469 (save-excursion
14470 (org-uniquify
14471 (delq nil
14472 (apply #'append
14473 (mapcar
14474 (lambda (file)
14475 (set-buffer (find-file-noselect file))
14476 (mapcar (lambda (x)
14477 (and (stringp (car-safe x))
14478 (list (car-safe x))))
14479 (or org-current-tag-alist (org-get-buffer-tags))))
14480 (if (car-safe files) files
14481 (org-agenda-files))))))))
14483 (defun org-make-tags-matcher (match)
14484 "Create the TAGS/TODO matcher form for the selection string MATCH.
14486 Returns a cons of the selection string MATCH and a function
14487 implementing the matcher.
14489 The matcher is to be called at an Org entry, with point on the
14490 headline, and returns non-nil if the entry matches the selection
14491 string MATCH. It must be called with three arguments: the TODO
14492 keyword at the entry (or nil if none), the list of all tags at
14493 the entry including inherited ones and the reduced level of the
14494 headline. Additionally, the category of the entry, if any, must
14495 be specified as the text property `org-category' on the headline.
14497 This function sets the variable `org--matcher-tags-todo-only' to
14498 a non-nil value if the matcher restricts matching to TODO
14499 entries, otherwise it is not touched.
14501 See also `org-scan-tags'."
14502 (unless match
14503 ;; Get a new match request, with completion against the global
14504 ;; tags table and the local tags in current buffer.
14505 (let ((org-last-tags-completion-table
14506 (org-uniquify
14507 (delq nil (append (org-get-buffer-tags)
14508 (org-global-tags-completion-table))))))
14509 (setq match
14510 (completing-read
14511 "Match: "
14512 'org-tags-completion-function nil nil nil 'org-tags-history))))
14514 (let ((match0 match)
14515 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14516 (start 0)
14517 tagsmatch todomatch tagsmatcher todomatcher)
14519 ;; Expand group tags.
14520 (setq match (org-tags-expand match))
14522 ;; Check if there is a TODO part of this match, which would be the
14523 ;; part after a "/". To make sure that this slash is not part of
14524 ;; a property value to be matched against, we also check that
14525 ;; there is no / after that slash. First, find the last slash.
14526 (let ((s 0))
14527 (while (string-match "/+" match s)
14528 (setq start (match-beginning 0))
14529 (setq s (match-end 0))))
14530 (if (and (string-match "/+" match start)
14531 (not (string-match-p "\"" match start)))
14532 ;; Match contains also a TODO-matching request.
14533 (progn
14534 (setq tagsmatch (substring match 0 (match-beginning 0)))
14535 (setq todomatch (substring match (match-end 0)))
14536 (when (string-prefix-p "!" todomatch)
14537 (setq org--matcher-tags-todo-only t)
14538 (setq todomatch (substring todomatch 1)))
14539 (when (string-match "\\`\\s-*\\'" todomatch)
14540 (setq todomatch nil)))
14541 ;; Only matching tags.
14542 (setq tagsmatch match)
14543 (setq todomatch nil))
14545 ;; Make the tags matcher.
14546 (when (org-string-nw-p tagsmatch)
14547 (let ((orlist nil)
14548 (orterms (org-split-string tagsmatch "|"))
14549 term)
14550 (while (setq term (pop orterms))
14551 (while (and (equal (substring term -1) "\\") orterms)
14552 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14553 (while (string-match re term)
14554 (let* ((rest (substring term (match-end 0)))
14555 (minus (and (match-end 1)
14556 (equal (match-string 1 term) "-")))
14557 (tag (save-match-data
14558 (replace-regexp-in-string
14559 "\\\\-" "-" (match-string 2 term))))
14560 (regexp (eq (string-to-char tag) ?{))
14561 (levelp (match-end 4))
14562 (propp (match-end 5))
14564 (cond
14565 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14566 (levelp
14567 `(,(org-op-to-function (match-string 3 term))
14568 level
14569 ,(string-to-number (match-string 4 term))))
14570 (propp
14571 (let* ((gv (pcase (upcase (match-string 5 term))
14572 ("CATEGORY"
14573 '(get-text-property (point) 'org-category))
14574 ("TODO" 'todo)
14575 (p `(org-cached-entry-get nil ,p))))
14576 (pv (match-string 7 term))
14577 (regexp (eq (string-to-char pv) ?{))
14578 (strp (eq (string-to-char pv) ?\"))
14579 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14580 (po (org-op-to-function (match-string 6 term)
14581 (if timep 'time strp))))
14582 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14583 (when timep (setq pv (org-matcher-time pv)))
14584 (cond ((and regexp (eq po 'org<>))
14585 `(not (string-match ,pv (or ,gv ""))))
14586 (regexp `(string-match ,pv (or ,gv "")))
14587 (strp `(,po (or ,gv "") ,pv))
14589 `(,po
14590 (string-to-number (or ,gv ""))
14591 ,(string-to-number pv))))))
14592 (t `(member ,tag tags-list)))))
14593 (push (if minus `(not ,mm) mm) tagsmatcher)
14594 (setq term rest)))
14595 (push `(and ,@tagsmatcher) orlist)
14596 (setq tagsmatcher nil))
14597 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14599 ;; Make the TODO matcher.
14600 (when (org-string-nw-p todomatch)
14601 (let ((orlist nil))
14602 (dolist (term (org-split-string todomatch "|"))
14603 (while (string-match re term)
14604 (let* ((minus (and (match-end 1)
14605 (equal (match-string 1 term) "-")))
14606 (kwd (match-string 2 term))
14607 (regexp (eq (string-to-char kwd) ?{))
14608 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14609 `(equal todo ,kwd))))
14610 (push (if minus `(not ,mm) mm) todomatcher))
14611 (setq term (substring term (match-end 0))))
14612 (push (if (> (length todomatcher) 1)
14613 (cons 'and todomatcher)
14614 (car todomatcher))
14615 orlist)
14616 (setq todomatcher nil))
14617 (setq todomatcher (cons 'or orlist))))
14619 ;; Return the string and function of the matcher. If no
14620 ;; tags-specific or todo-specific matcher exists, match
14621 ;; everything.
14622 (let ((matcher (if (and tagsmatcher todomatcher)
14623 `(and ,tagsmatcher ,todomatcher)
14624 (or tagsmatcher todomatcher t))))
14625 (when org--matcher-tags-todo-only
14626 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14627 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14629 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14630 "Expand group tags in MATCH.
14632 This replaces every group tag in MATCH with a regexp tag search.
14633 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14634 will be replaced like this:
14636 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14637 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14638 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14640 Replacing by a regexp preserves the structure of the match.
14641 E.g., this expansion
14643 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14645 will match anything tagged with \"Lab\" and \"Home\", or tagged
14646 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14648 A group tag in MATCH can contain regular expressions of its own.
14649 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14650 will be replaced like this:
14652 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14654 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14655 assumed to be a single group tag, and the function will return
14656 the list of tags in this group.
14658 When DOWNCASE is non-nil, expand downcased TAGS."
14659 (if org-group-tags
14660 (let* ((case-fold-search t)
14661 (stable org-mode-syntax-table)
14662 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14663 (taggroups (if downcased
14664 (mapcar (lambda (tg) (mapcar #'downcase tg))
14665 taggroups)
14666 taggroups))
14667 (taggroups-keys (mapcar #'car taggroups))
14668 (return-match (if downcased (downcase match) match))
14669 (count 0)
14670 (work-already-expanded tags-already-expanded)
14671 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14672 ;; @ and _ are allowed as word-components in tags.
14673 (modify-syntax-entry ?@ "w" stable)
14674 (modify-syntax-entry ?_ "w" stable)
14675 ;; Temporarily replace regexp-expressions in the match-expression.
14676 (while (string-match "{.+?}" return-match)
14677 (cl-incf count)
14678 (push (match-string 0 return-match) regexps-in-match)
14679 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14680 (while (and taggroups-keys
14681 (with-syntax-table stable
14682 (string-match
14683 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14684 (regexp-opt taggroups-keys) "\\>\\)")
14685 return-match)))
14686 (let* ((dir (match-string 1 return-match))
14687 (tag (match-string 2 return-match))
14688 (tag (if downcased (downcase tag) tag)))
14689 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14690 (member tag work-already-expanded))
14691 (setq tags-in-group (assoc tag taggroups))
14692 (push tag work-already-expanded)
14693 ;; Recursively expand each tag in the group, if the tag hasn't
14694 ;; already been expanded. Restore the match-data after all recursive calls.
14695 (save-match-data
14696 (let (tags-expanded)
14697 (dolist (x (cdr tags-in-group))
14698 (if (and (member x taggroups-keys)
14699 (not (member x work-already-expanded)))
14700 (setq tags-expanded
14701 (delete-dups
14702 (append
14703 (org-tags-expand x t downcased
14704 work-already-expanded)
14705 tags-expanded)))
14706 (setq tags-expanded
14707 (append (list x) tags-expanded)))
14708 (setq work-already-expanded
14709 (delete-dups
14710 (append tags-expanded
14711 work-already-expanded))))
14712 (setq tags-in-group
14713 (delete-dups (cons (car tags-in-group)
14714 tags-expanded)))))
14715 ;; Filter tag-regexps from tags.
14716 (setq regexp-in-group-escaped
14717 (delq nil (mapcar (lambda (x)
14718 (if (stringp x)
14719 (and (equal "{" (substring x 0 1))
14720 (equal "}" (substring x -1))
14723 tags-in-group))
14724 regexp-in-group
14725 (mapcar (lambda (x)
14726 (substring x 1 -1))
14727 regexp-in-group-escaped)
14728 tags-in-group
14729 (delq nil (mapcar (lambda (x)
14730 (if (stringp x)
14731 (and (not (equal "{" (substring x 0 1)))
14732 (not (equal "}" (substring x -1)))
14735 tags-in-group)))
14736 ;; If single-as-list, do no more in the while-loop.
14737 (if (not single-as-list)
14738 (progn
14739 (when regexp-in-group
14740 (setq regexp-in-group
14741 (concat "\\|"
14742 (mapconcat 'identity regexp-in-group
14743 "\\|"))))
14744 (setq tags-in-group
14745 (concat dir
14746 "{\\<"
14747 (regexp-opt tags-in-group)
14748 "\\>"
14749 regexp-in-group
14750 "}"))
14751 (when (stringp tags-in-group)
14752 (org-add-props tags-in-group '(grouptag t)))
14753 (setq return-match
14754 (replace-match tags-in-group t t return-match)))
14755 (setq tags-in-group
14756 (append regexp-in-group-escaped tags-in-group))))
14757 (setq taggroups-keys (delete tag taggroups-keys))))
14758 ;; Add the regular expressions back into the match-expression again.
14759 (while regexps-in-match
14760 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14761 (pop regexps-in-match)
14762 return-match t t))
14763 (cl-decf count))
14764 (if single-as-list
14765 (if tags-in-group tags-in-group (list return-match))
14766 return-match))
14767 (if single-as-list
14768 (list (if downcased (downcase match) match))
14769 match)))
14771 (defun org-op-to-function (op &optional stringp)
14772 "Turn an operator into the appropriate function."
14773 (setq op
14774 (cond
14775 ((equal op "<" ) '(< string< org-time<))
14776 ((equal op ">" ) '(> org-string> org-time>))
14777 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14778 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14779 ((member op '("=" "==")) '(= string= org-time=))
14780 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14781 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14783 (defun org<> (a b) (not (= a b)))
14784 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14785 (defun org-string>= (a b) (not (string< a b)))
14786 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14787 (defun org-string<> (a b) (not (string= a b)))
14788 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14789 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14790 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14791 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14792 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14793 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14794 (defun org-2ft (s)
14795 "Convert S to a floating point time.
14796 If S is already a number, just return it. If it is a string, parse
14797 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14798 (cond
14799 ((numberp s) s)
14800 ((stringp s)
14801 (condition-case nil
14802 (float-time (apply 'encode-time (org-parse-time-string s)))
14803 (error 0.)))
14804 (t 0.)))
14806 (defun org-time-today ()
14807 "Time in seconds today at 0:00.
14808 Returns the float number of seconds since the beginning of the
14809 epoch to the beginning of today (00:00)."
14810 (float-time (apply 'encode-time
14811 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14813 (defun org-matcher-time (s)
14814 "Interpret a time comparison value."
14815 (save-match-data
14816 (cond
14817 ((string= s "<now>") (float-time))
14818 ((string= s "<today>") (org-time-today))
14819 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14820 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14821 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14822 (+ (org-time-today)
14823 (* (string-to-number (match-string 1 s))
14824 (cdr (assoc (match-string 2 s)
14825 '(("d" . 86400.0) ("w" . 604800.0)
14826 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14827 (t (org-2ft s)))))
14829 (defun org-match-any-p (re list)
14830 "Does re match any element of list?"
14831 (setq list (mapcar (lambda (x) (string-match re x)) list))
14832 (delq nil list))
14834 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14835 (defvar org-tags-overlay (make-overlay 1 1))
14836 (delete-overlay org-tags-overlay)
14838 (defun org-get-local-tags-at (&optional pos)
14839 "Get a list of tags defined in the current headline."
14840 (org-get-tags-at pos 'local))
14842 (defun org-get-local-tags ()
14843 "Get a list of tags defined in the current headline."
14844 (org-get-tags-at nil 'local))
14846 (defun org-get-tags-at (&optional pos local)
14847 "Get a list of all headline tags applicable at POS.
14848 POS defaults to point. If tags are inherited, the list contains
14849 the targets in the same sequence as the headlines appear, i.e.
14850 the tags of the current headline come last.
14851 When LOCAL is non-nil, only return tags from the current headline,
14852 ignore inherited ones."
14853 (interactive)
14854 (if (and org-trust-scanner-tags
14855 (or (not pos) (equal pos (point)))
14856 (not local))
14857 org-scanner-tags
14858 (let (tags ltags lastpos parent)
14859 (save-excursion
14860 (save-restriction
14861 (widen)
14862 (goto-char (or pos (point)))
14863 (save-match-data
14864 (catch 'done
14865 (condition-case nil
14866 (progn
14867 (org-back-to-heading t)
14868 (while (not (equal lastpos (point)))
14869 (setq lastpos (point))
14870 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14871 (setq ltags (org-split-string
14872 (match-string-no-properties 1) ":"))
14873 (when parent
14874 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14875 (setq tags (append
14876 (if parent
14877 (org-remove-uninherited-tags ltags)
14878 ltags)
14879 tags)))
14880 (or org-use-tag-inheritance (throw 'done t))
14881 (when local (throw 'done t))
14882 (or (org-up-heading-safe) (error nil))
14883 (setq parent t)))
14884 (error nil)))))
14885 (if local
14886 tags
14887 (reverse (delete-dups
14888 (reverse (append
14889 (org-remove-uninherited-tags
14890 org-file-tags)
14891 tags)))))))))
14893 (defun org-add-prop-inherited (s)
14894 (add-text-properties 0 (length s) '(inherited t) s)
14897 (defun org-toggle-tag (tag &optional onoff)
14898 "Toggle the tag TAG for the current line.
14899 If ONOFF is `on' or `off', don't toggle but set to this state."
14900 (let (res current)
14901 (save-excursion
14902 (org-back-to-heading t)
14903 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14904 (point-at-eol) t)
14905 (progn
14906 (setq current (match-string 1))
14907 (replace-match ""))
14908 (setq current ""))
14909 (setq current (nreverse (org-split-string current ":")))
14910 (cond
14911 ((eq onoff 'on)
14912 (setq res t)
14913 (or (member tag current) (push tag current)))
14914 ((eq onoff 'off)
14915 (or (not (member tag current)) (setq current (delete tag current))))
14916 (t (if (member tag current)
14917 (setq current (delete tag current))
14918 (setq res t)
14919 (push tag current))))
14920 (end-of-line 1)
14921 (if current
14922 (progn
14923 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14924 (org-set-tags nil t))
14925 (delete-horizontal-space))
14926 (run-hooks 'org-after-tags-change-hook))
14927 res))
14929 (defun org--align-tags-here (to-col)
14930 "Align tags on the current headline to TO-COL.
14931 Assume point is on a headline."
14932 (let ((pos (point)))
14933 (beginning-of-line)
14934 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14935 (>= pos (match-beginning 2)))
14936 ;; No tags or point within tags: do not align.
14937 (goto-char pos)
14938 (goto-char (match-beginning 1))
14939 (let ((shift (max (- (if (>= to-col 0) to-col
14940 (- (abs to-col) (string-width (match-string 2))))
14941 (current-column))
14942 1)))
14943 (replace-match (make-string shift ?\s) nil nil nil 1)
14944 ;; Preserve initial position, if possible. In any case, stop
14945 ;; before tags.
14946 (when (< pos (point)) (goto-char pos))))))
14948 (defun org-set-tags-command (&optional arg just-align)
14949 "Call the set-tags command for the current entry."
14950 (interactive "P")
14951 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14952 (org-set-tags arg just-align)
14953 (save-excursion
14954 (unless (and (org-region-active-p)
14955 org-loop-over-headlines-in-active-region)
14956 (org-back-to-heading t))
14957 (org-set-tags arg just-align))))
14959 (defun org-set-tags-to (data)
14960 "Set the tags of the current entry to DATA, replacing the current tags.
14961 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14962 If DATA is nil or the empty string, any tags will be removed."
14963 (interactive "sTags: ")
14964 (setq data
14965 (cond
14966 ((eq data nil) "")
14967 ((equal data "") "")
14968 ((stringp data)
14969 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14970 ":"))
14971 ((listp data)
14972 (concat ":" (mapconcat 'identity data ":") ":"))))
14973 (when data
14974 (save-excursion
14975 (org-back-to-heading t)
14976 (when (let ((case-fold-search nil))
14977 (looking-at org-complex-heading-regexp))
14978 (if (match-end 5)
14979 (progn
14980 (goto-char (match-beginning 5))
14981 (insert data)
14982 (delete-region (point) (point-at-eol))
14983 (org-set-tags nil 'align))
14984 (goto-char (point-at-eol))
14985 (insert " " data)
14986 (org-set-tags nil 'align)))
14987 (beginning-of-line 1)
14988 (when (looking-at ".*?\\([ \t]+\\)$")
14989 (delete-region (match-beginning 1) (match-end 1))))))
14991 (defun org-align-all-tags ()
14992 "Align the tags in all headings."
14993 (interactive)
14994 (save-excursion
14995 (or (ignore-errors (org-back-to-heading t))
14996 (outline-next-heading))
14997 (if (org-at-heading-p)
14998 (org-set-tags t)
14999 (message "No headings"))))
15001 (defvar org-indent-indentation-per-level)
15002 (defun org-set-tags (&optional arg just-align)
15003 "Set the tags for the current headline.
15004 With prefix ARG, realign all tags in headings in the current buffer.
15005 When JUST-ALIGN is non-nil, only align tags."
15006 (interactive "P")
15007 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15008 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15009 'region-start-level
15010 'region))
15011 org-loop-over-headlines-in-active-region)
15012 (org-map-entries
15013 ;; We don't use ARG and JUST-ALIGN here because these args
15014 ;; are not useful when looping over headlines.
15015 #'org-set-tags
15016 org-loop-over-headlines-in-active-region
15018 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15019 (let ((org-setting-tags t))
15020 (if arg
15021 (save-excursion
15022 (goto-char (point-min))
15023 (while (re-search-forward org-outline-regexp-bol nil t)
15024 (org-set-tags nil t)
15025 (end-of-line))
15026 (message "All tags realigned to column %d" org-tags-column))
15027 (let* ((current (org-get-tags-string))
15028 (tags
15029 (if just-align current
15030 ;; Get a new set of tags from the user.
15031 (save-excursion
15032 (let* ((seen)
15033 (table
15034 (setq
15035 org-last-tags-completion-table
15036 ;; Uniquify tags in alists, yet preserve
15037 ;; structure (i.e., keywords).
15038 (delq nil
15039 (mapcar
15040 (lambda (pair)
15041 (let ((head (car pair)))
15042 (cond ((symbolp head) pair)
15043 ((member head seen) nil)
15044 (t (push head seen)
15045 pair))))
15046 (append
15047 (or org-current-tag-alist
15048 (org-get-buffer-tags))
15049 (and
15050 org-complete-tags-always-offer-all-agenda-tags
15051 (org-global-tags-completion-table
15052 (org-agenda-files))))))))
15053 (current-tags (org-split-string current ":"))
15054 (inherited-tags
15055 (nreverse (nthcdr (length current-tags)
15056 (nreverse (org-get-tags-at))))))
15057 (replace-regexp-in-string
15058 "\\([-+&]+\\|,\\)"
15060 (if (or (eq t org-use-fast-tag-selection)
15061 (and org-use-fast-tag-selection
15062 (delq nil (mapcar #'cdr table))))
15063 (org-fast-tag-selection
15064 current-tags inherited-tags table
15065 (and org-fast-tag-selection-include-todo
15066 org-todo-key-alist))
15067 (let ((org-add-colon-after-tag-completion
15068 (< 1 (length table))))
15069 (org-trim
15070 (completing-read
15071 "Tags: "
15072 #'org-tags-completion-function
15073 nil nil current 'org-tags-history))))))))))
15075 (when org-tags-sort-function
15076 (setq tags
15077 (mapconcat
15078 #'identity
15079 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15080 org-tags-sort-function)
15081 ":")))
15083 (if (not (org-string-nw-p tags)) (setq tags "")
15084 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15085 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15087 ;; Insert new tags at the correct column.
15088 (unless (equal current tags)
15089 (save-excursion
15090 (beginning-of-line)
15091 (let ((case-fold-search nil))
15092 (looking-at org-complex-heading-regexp))
15093 ;; Remove current tags, if any.
15094 (when (match-end 5) (replace-match "" nil nil nil 5))
15095 ;; Insert new tags, if any. Otherwise, remove trailing
15096 ;; white spaces.
15097 (end-of-line)
15098 (if (not (equal tags ""))
15099 ;; When text is being inserted on an invisible
15100 ;; region boundary, it can be inadvertently sucked
15101 ;; into invisibility.
15102 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15103 (skip-chars-backward " \t")
15104 (delete-region (point) (line-end-position)))))
15105 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15106 ;; is on.
15107 (unless (equal tags "")
15108 (let* ((level (save-excursion
15109 (beginning-of-line)
15110 (skip-chars-forward "\\*")))
15111 (offset (if (bound-and-true-p org-indent-mode)
15112 (* (1- org-indent-indentation-per-level)
15113 (1- level))
15115 (tags-column
15116 (+ org-tags-column
15117 (if (> org-tags-column 0) (- offset) offset))))
15118 (org--align-tags-here tags-column))))
15119 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15121 (defun org-change-tag-in-region (beg end tag off)
15122 "Add or remove TAG for each entry in the region.
15123 This works in the agenda, and also in an Org buffer."
15124 (interactive
15125 (list (region-beginning) (region-end)
15126 (let ((org-last-tags-completion-table
15127 (if (derived-mode-p 'org-mode)
15128 (org-uniquify
15129 (delq nil (append (org-get-buffer-tags)
15130 (org-global-tags-completion-table))))
15131 (org-global-tags-completion-table))))
15132 (completing-read
15133 "Tag: " 'org-tags-completion-function nil nil nil
15134 'org-tags-history))
15135 (progn
15136 (message "[s]et or [r]emove? ")
15137 (equal (read-char-exclusive) ?r))))
15138 (when (fboundp 'deactivate-mark) (deactivate-mark))
15139 (let ((agendap (equal major-mode 'org-agenda-mode))
15140 l1 l2 m buf pos newhead (cnt 0))
15141 (goto-char end)
15142 (setq l2 (1- (org-current-line)))
15143 (goto-char beg)
15144 (setq l1 (org-current-line))
15145 (cl-loop for l from l1 to l2 do
15146 (org-goto-line l)
15147 (setq m (get-text-property (point) 'org-hd-marker))
15148 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15149 (and agendap m))
15150 (setq buf (if agendap (marker-buffer m) (current-buffer))
15151 pos (if agendap m (point)))
15152 (with-current-buffer buf
15153 (save-excursion
15154 (save-restriction
15155 (goto-char pos)
15156 (setq cnt (1+ cnt))
15157 (org-toggle-tag tag (if off 'off 'on))
15158 (setq newhead (org-get-heading)))))
15159 (and agendap (org-agenda-change-all-lines newhead m))))
15160 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15162 (defun org-tags-completion-function (string _predicate &optional flag)
15163 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15164 (confirm (lambda (x) (stringp (car x)))))
15165 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15166 (setq s1 (match-string 1 string)
15167 s2 (match-string 2 string))
15168 (setq s1 "" s2 string))
15169 (cond
15170 ((eq flag nil)
15171 ;; try completion
15172 (setq rtn (try-completion s2 ctable confirm))
15173 (when (stringp rtn)
15174 (setq rtn
15175 (concat s1 s2 (substring rtn (length s2))
15176 (if (and org-add-colon-after-tag-completion
15177 (assoc rtn ctable))
15178 ":" ""))))
15179 rtn)
15180 ((eq flag t)
15181 ;; all-completions
15182 (all-completions s2 ctable confirm))
15183 ((eq flag 'lambda)
15184 ;; exact match?
15185 (assoc s2 ctable)))))
15187 (defun org-fast-tag-insert (kwd tags face &optional end)
15188 "Insert KDW, and the TAGS, the latter with face FACE.
15189 Also insert END."
15190 (insert (format "%-12s" (concat kwd ":"))
15191 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15192 (or end "")))
15194 (defun org-fast-tag-show-exit (flag)
15195 (save-excursion
15196 (org-goto-line 3)
15197 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15198 (replace-match ""))
15199 (when flag
15200 (end-of-line 1)
15201 (org-move-to-column (- (window-width) 19) t)
15202 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15204 (defun org-set-current-tags-overlay (current prefix)
15205 "Add an overlay to CURRENT tag with PREFIX."
15206 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15207 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15208 (org-overlay-display org-tags-overlay (concat prefix s))))
15210 (defvar org-last-tag-selection-key nil)
15211 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15212 "Fast tag selection with single keys.
15213 CURRENT is the current list of tags in the headline, INHERITED is the
15214 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15215 possibly with grouping information. TODO-TABLE is a similar table with
15216 TODO keywords, should these have keys assigned to them.
15217 If the keys are nil, a-z are automatically assigned.
15218 Returns the new tags string, or nil to not change the current settings."
15219 (let* ((fulltable (append table todo-table))
15220 (maxlen (apply 'max (mapcar
15221 (lambda (x)
15222 (if (stringp (car x)) (string-width (car x)) 0))
15223 fulltable)))
15224 (buf (current-buffer))
15225 (expert (eq org-fast-tag-selection-single-key 'expert))
15226 (buffer-tags nil)
15227 (fwidth (+ maxlen 3 1 3))
15228 (ncol (/ (- (window-width) 4) fwidth))
15229 (i-face 'org-done)
15230 (c-face 'org-todo)
15231 tg cnt e c char c1 c2 ntable tbl rtn
15232 ov-start ov-end ov-prefix
15233 (exit-after-next org-fast-tag-selection-single-key)
15234 (done-keywords org-done-keywords)
15235 groups ingroup intaggroup)
15236 (save-excursion
15237 (beginning-of-line 1)
15238 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15239 (setq ov-start (match-beginning 1)
15240 ov-end (match-end 1)
15241 ov-prefix "")
15242 (setq ov-start (1- (point-at-eol))
15243 ov-end (1+ ov-start))
15244 (skip-chars-forward "^\n\r")
15245 (setq ov-prefix
15246 (concat
15247 (buffer-substring (1- (point)) (point))
15248 (if (> (current-column) org-tags-column)
15250 (make-string (- org-tags-column (current-column)) ?\ ))))))
15251 (move-overlay org-tags-overlay ov-start ov-end)
15252 (save-window-excursion
15253 (if expert
15254 (set-buffer (get-buffer-create " *Org tags*"))
15255 (delete-other-windows)
15256 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15257 (org-switch-to-buffer-other-window " *Org tags*"))
15258 (erase-buffer)
15259 (setq-local org-done-keywords done-keywords)
15260 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15261 (org-fast-tag-insert "Current" current c-face "\n\n")
15262 (org-fast-tag-show-exit exit-after-next)
15263 (org-set-current-tags-overlay current ov-prefix)
15264 (setq tbl fulltable char ?a cnt 0)
15265 (while (setq e (pop tbl))
15266 (cond
15267 ((eq (car e) :startgroup)
15268 (push '() groups) (setq ingroup t)
15269 (unless (zerop cnt)
15270 (setq cnt 0)
15271 (insert "\n"))
15272 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15273 ((eq (car e) :endgroup)
15274 (setq ingroup nil cnt 0)
15275 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15276 ((eq (car e) :startgrouptag)
15277 (setq intaggroup t)
15278 (unless (zerop cnt)
15279 (setq cnt 0)
15280 (insert "\n"))
15281 (insert "[ "))
15282 ((eq (car e) :endgrouptag)
15283 (setq intaggroup nil cnt 0)
15284 (insert "]\n"))
15285 ((equal e '(:newline))
15286 (unless (zerop cnt)
15287 (setq cnt 0)
15288 (insert "\n")
15289 (setq e (car tbl))
15290 (while (equal (car tbl) '(:newline))
15291 (insert "\n")
15292 (setq tbl (cdr tbl)))))
15293 ((equal e '(:grouptags)) (insert " : "))
15295 (setq tg (copy-sequence (car e)) c2 nil)
15296 (if (cdr e)
15297 (setq c (cdr e))
15298 ;; automatically assign a character.
15299 (setq c1 (string-to-char
15300 (downcase (substring
15301 tg (if (= (string-to-char tg) ?@) 1 0)))))
15302 (if (or (rassoc c1 ntable) (rassoc c1 table))
15303 (while (or (rassoc char ntable) (rassoc char table))
15304 (setq char (1+ char)))
15305 (setq c2 c1))
15306 (setq c (or c2 char)))
15307 (when ingroup (push tg (car groups)))
15308 (setq tg (org-add-props tg nil 'face
15309 (cond
15310 ((not (assoc tg table))
15311 (org-get-todo-face tg))
15312 ((member tg current) c-face)
15313 ((member tg inherited) i-face))))
15314 (when (equal (caar tbl) :grouptags)
15315 (org-add-props tg nil 'face 'org-tag-group))
15316 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15317 (insert "[" c "] " tg (make-string
15318 (- fwidth 4 (length tg)) ?\ ))
15319 (push (cons tg c) ntable)
15320 (when (= (cl-incf cnt) ncol)
15321 (insert "\n")
15322 (when (or ingroup intaggroup) (insert " "))
15323 (setq cnt 0)))))
15324 (setq ntable (nreverse ntable))
15325 (insert "\n")
15326 (goto-char (point-min))
15327 (unless expert (org-fit-window-to-buffer))
15328 (setq rtn
15329 (catch 'exit
15330 (while t
15331 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15332 (if (not groups) "no " "")
15333 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15334 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15335 (setq org-last-tag-selection-key c)
15336 (cond
15337 ((= c ?\r) (throw 'exit t))
15338 ((= c ?!)
15339 (setq groups (not groups))
15340 (goto-char (point-min))
15341 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15342 ((= c ?\C-c)
15343 (if (not expert)
15344 (org-fast-tag-show-exit
15345 (setq exit-after-next (not exit-after-next)))
15346 (setq expert nil)
15347 (delete-other-windows)
15348 (set-window-buffer (split-window-vertically) " *Org tags*")
15349 (org-switch-to-buffer-other-window " *Org tags*")
15350 (org-fit-window-to-buffer)))
15351 ((or (= c ?\C-g)
15352 (and (= c ?q) (not (rassoc c ntable))))
15353 (delete-overlay org-tags-overlay)
15354 (setq quit-flag t))
15355 ((= c ?\ )
15356 (setq current nil)
15357 (when exit-after-next (setq exit-after-next 'now)))
15358 ((= c ?\t)
15359 (condition-case nil
15360 (setq tg (completing-read
15361 "Tag: "
15362 (or buffer-tags
15363 (with-current-buffer buf
15364 (setq buffer-tags
15365 (org-get-buffer-tags))))))
15366 (quit (setq tg "")))
15367 (when (string-match "\\S-" tg)
15368 (cl-pushnew (list tg) buffer-tags :test #'equal)
15369 (if (member tg current)
15370 (setq current (delete tg current))
15371 (push tg current)))
15372 (when exit-after-next (setq exit-after-next 'now)))
15373 ((setq e (rassoc c todo-table) tg (car e))
15374 (with-current-buffer buf
15375 (save-excursion (org-todo tg)))
15376 (when exit-after-next (setq exit-after-next 'now)))
15377 ((setq e (rassoc c ntable) tg (car e))
15378 (if (member tg current)
15379 (setq current (delete tg current))
15380 (cl-loop for g in groups do
15381 (when (member tg g)
15382 (dolist (x g) (setq current (delete x current)))))
15383 (push tg current))
15384 (when exit-after-next (setq exit-after-next 'now))))
15386 ;; Create a sorted list
15387 (setq current
15388 (sort current
15389 (lambda (a b)
15390 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15391 (when (eq exit-after-next 'now) (throw 'exit t))
15392 (goto-char (point-min))
15393 (beginning-of-line 2)
15394 (delete-region (point) (point-at-eol))
15395 (org-fast-tag-insert "Current" current c-face)
15396 (org-set-current-tags-overlay current ov-prefix)
15397 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15398 (setq tg (match-string 1))
15399 (add-text-properties
15400 (match-beginning 1) (match-end 1)
15401 (list 'face
15402 (cond
15403 ((member tg current) c-face)
15404 ((member tg inherited) i-face)
15405 (t (get-text-property (match-beginning 1) 'face))))))
15406 (goto-char (point-min)))))
15407 (delete-overlay org-tags-overlay)
15408 (if rtn
15409 (mapconcat 'identity current ":")
15410 nil))))
15412 (defun org-get-tags-string ()
15413 "Get the TAGS string in the current headline."
15414 (unless (org-at-heading-p t)
15415 (user-error "Not on a heading"))
15416 (save-excursion
15417 (beginning-of-line 1)
15418 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15419 (match-string-no-properties 1)
15420 "")))
15422 (defun org-get-tags ()
15423 "Get the list of tags specified in the current headline."
15424 (org-split-string (org-get-tags-string) ":"))
15426 (defun org-get-buffer-tags ()
15427 "Get a table of all tags used in the buffer, for completion."
15428 (org-with-wide-buffer
15429 (goto-char (point-min))
15430 (let ((tag-re (concat org-outline-regexp-bol
15431 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15432 tags)
15433 (while (re-search-forward tag-re nil t)
15434 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15435 (push tag tags)))
15436 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15438 ;;;; The mapping API
15440 (defvar org-agenda-skip-comment-trees)
15441 (defvar org-agenda-skip-function)
15442 (defun org-map-entries (func &optional match scope &rest skip)
15443 "Call FUNC at each headline selected by MATCH in SCOPE.
15445 FUNC is a function or a lisp form. The function will be called without
15446 arguments, with the cursor positioned at the beginning of the headline.
15447 The return values of all calls to the function will be collected and
15448 returned as a list.
15450 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15451 does not need to preserve point. After evaluation, the cursor will be
15452 moved to the end of the line (presumably of the headline of the
15453 processed entry) and search continues from there. Under some
15454 circumstances, this may not produce the wanted results. For example,
15455 if you have removed (e.g. archived) the current (sub)tree it could
15456 mean that the next entry will be skipped entirely. In such cases, you
15457 can specify the position from where search should continue by making
15458 FUNC set the variable `org-map-continue-from' to the desired buffer
15459 position.
15461 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15462 Only headlines that are matched by this query will be considered during
15463 the iteration. When MATCH is nil or t, all headlines will be
15464 visited by the iteration.
15466 SCOPE determines the scope of this command. It can be any of:
15468 nil The current buffer, respecting the restriction if any
15469 tree The subtree started with the entry at point
15470 region The entries within the active region, if any
15471 region-start-level
15472 The entries within the active region, but only those at
15473 the same level than the first one.
15474 file The current buffer, without restriction
15475 file-with-archives
15476 The current buffer, and any archives associated with it
15477 agenda All agenda files
15478 agenda-with-archives
15479 All agenda files with any archive files associated with them
15480 \(file1 file2 ...)
15481 If this is a list, all files in the list will be scanned
15483 The remaining args are treated as settings for the skipping facilities of
15484 the scanner. The following items can be given here:
15486 archive skip trees with the archive tag
15487 comment skip trees with the COMMENT keyword
15488 function or Emacs Lisp form:
15489 will be used as value for `org-agenda-skip-function', so
15490 whenever the function returns a position, FUNC will not be
15491 called for that entry and search will continue from the
15492 position returned
15494 If your function needs to retrieve the tags including inherited tags
15495 at the *current* entry, you can use the value of the variable
15496 `org-scanner-tags' which will be much faster than getting the value
15497 with `org-get-tags-at'. If your function gets properties with
15498 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15499 to t around the call to `org-entry-properties' to get the same speedup.
15500 Note that if your function moves around to retrieve tags and properties at
15501 a *different* entry, you cannot use these techniques."
15502 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15503 (not (org-region-active-p)))
15504 (let* ((org-agenda-archives-mode nil) ; just to make sure
15505 (org-agenda-skip-archived-trees (memq 'archive skip))
15506 (org-agenda-skip-comment-trees (memq 'comment skip))
15507 (org-agenda-skip-function
15508 (car (org-delete-all '(comment archive) skip)))
15509 (org-tags-match-list-sublevels t)
15510 (start-level (eq scope 'region-start-level))
15511 matcher res
15512 org-todo-keywords-for-agenda
15513 org-done-keywords-for-agenda
15514 org-todo-keyword-alist-for-agenda
15515 org-tag-alist-for-agenda
15516 org--matcher-tags-todo-only)
15518 (cond
15519 ((eq match t) (setq matcher t))
15520 ((eq match nil) (setq matcher t))
15521 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15523 (save-excursion
15524 (save-restriction
15525 (cond ((eq scope 'tree)
15526 (org-back-to-heading t)
15527 (org-narrow-to-subtree)
15528 (setq scope nil))
15529 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15530 (org-region-active-p))
15531 ;; If needed, set start-level to a string like "2"
15532 (when start-level
15533 (save-excursion
15534 (goto-char (region-beginning))
15535 (unless (org-at-heading-p) (outline-next-heading))
15536 (setq start-level (org-current-level))))
15537 (narrow-to-region (region-beginning)
15538 (save-excursion
15539 (goto-char (region-end))
15540 (unless (and (bolp) (org-at-heading-p))
15541 (outline-next-heading))
15542 (point)))
15543 (setq scope nil)))
15545 (if (not scope)
15546 (progn
15547 (org-agenda-prepare-buffers
15548 (and buffer-file-name (list buffer-file-name)))
15549 (setq res
15550 (org-scan-tags
15551 func matcher org--matcher-tags-todo-only start-level)))
15552 ;; Get the right scope
15553 (cond
15554 ((and scope (listp scope) (symbolp (car scope)))
15555 (setq scope (eval scope)))
15556 ((eq scope 'agenda)
15557 (setq scope (org-agenda-files t)))
15558 ((eq scope 'agenda-with-archives)
15559 (setq scope (org-agenda-files t))
15560 (setq scope (org-add-archive-files scope)))
15561 ((eq scope 'file)
15562 (setq scope (and buffer-file-name (list buffer-file-name))))
15563 ((eq scope 'file-with-archives)
15564 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15565 (org-agenda-prepare-buffers scope)
15566 (dolist (file scope)
15567 (with-current-buffer (org-find-base-buffer-visiting file)
15568 (org-with-wide-buffer
15569 (goto-char (point-min))
15570 (setq res
15571 (append
15573 (org-scan-tags
15574 func matcher org--matcher-tags-todo-only)))))))))
15575 res)))
15577 ;;; Properties API
15579 (defconst org-special-properties
15580 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15581 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15582 "The special properties valid in Org mode.
15583 These are properties that are not defined in the property drawer,
15584 but in some other way.")
15586 (defconst org-default-properties
15587 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15588 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15589 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15590 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15591 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15592 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15593 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15594 "Some properties that are used by Org mode for various purposes.
15595 Being in this list makes sure that they are offered for completion.")
15597 (defun org--valid-property-p (property)
15598 "Non nil when string PROPERTY is a valid property name."
15599 (not
15600 (or (equal property "")
15601 (string-match-p "\\s-" property))))
15603 (defun org--update-property-plist (key val props)
15604 "Associate KEY to VAL in alist PROPS.
15605 Modifications are made by side-effect. Return new alist."
15606 (let* ((appending (string= (substring key -1) "+"))
15607 (key (if appending (substring key 0 -1) key))
15608 (old (assoc-string key props t)))
15609 (if (not old) (cons (cons key val) props)
15610 (setcdr old (if appending (concat (cdr old) " " val) val))
15611 props)))
15613 (defun org-get-property-block (&optional beg force)
15614 "Return the (beg . end) range of the body of the property drawer.
15615 BEG is the beginning of the current subtree, or of the part
15616 before the first headline. If it is not given, it will be found.
15617 If the drawer does not exist, create it if FORCE is non-nil, or
15618 return nil."
15619 (org-with-wide-buffer
15620 (when beg (goto-char beg))
15621 (unless (org-before-first-heading-p)
15622 (let ((beg (cond (beg)
15623 ((or (not (featurep 'org-inlinetask))
15624 (org-inlinetask-in-task-p))
15625 (org-back-to-heading t))
15626 (t (org-with-limited-levels (org-back-to-heading t))))))
15627 (forward-line)
15628 (when (looking-at-p org-planning-line-re) (forward-line))
15629 (cond ((looking-at org-property-drawer-re)
15630 (forward-line)
15631 (cons (point) (progn (goto-char (match-end 0))
15632 (line-beginning-position))))
15633 (force
15634 (goto-char beg)
15635 (org-insert-property-drawer)
15636 (let ((pos (save-excursion (search-forward ":END:")
15637 (line-beginning-position))))
15638 (cons pos pos))))))))
15640 (defun org-at-property-p ()
15641 "Non-nil when point is inside a property drawer.
15642 See `org-property-re' for match data, if applicable."
15643 (save-excursion
15644 (beginning-of-line)
15645 (and (looking-at org-property-re)
15646 (let ((property-drawer (save-match-data (org-get-property-block))))
15647 (and property-drawer
15648 (>= (point) (car property-drawer))
15649 (< (point) (cdr property-drawer)))))))
15651 (defun org-property-action ()
15652 "Do an action on properties."
15653 (interactive)
15654 (unless (org-at-property-p) (user-error "Not at a property"))
15655 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15656 (let ((c (read-char-exclusive)))
15657 (cl-case c
15658 (?s (call-interactively #'org-set-property))
15659 (?d (call-interactively #'org-delete-property))
15660 (?D (call-interactively #'org-delete-property-globally))
15661 (?c (call-interactively #'org-compute-property-at-point))
15662 (otherwise (user-error "No such property action %c" c)))))
15664 (defun org-inc-effort ()
15665 "Increment the value of the effort property in the current entry."
15666 (interactive)
15667 (org-set-effort nil t))
15669 (defvar org-clock-effort) ; Defined in org-clock.el.
15670 (defvar org-clock-current-task) ; Defined in org-clock.el.
15671 (defun org-set-effort (&optional value increment)
15672 "Set the effort property of the current entry.
15673 With numerical prefix arg, use the nth allowed value, 0 stands for the
15674 10th allowed value.
15676 When INCREMENT is non-nil, set the property to the next allowed value."
15677 (interactive "P")
15678 (when (equal value 0) (setq value 10))
15679 (let* ((completion-ignore-case t)
15680 (prop org-effort-property)
15681 (cur (org-entry-get nil prop))
15682 (allowed (org-property-get-allowed-values nil prop 'table))
15683 (existing (mapcar 'list (org-property-values prop)))
15684 (heading (nth 4 (org-heading-components)))
15686 (val (cond
15687 ((stringp value) value)
15688 ((and allowed (integerp value))
15689 (or (car (nth (1- value) allowed))
15690 (car (org-last allowed))))
15691 ((and allowed increment)
15692 (or (cl-caadr (member (list cur) allowed))
15693 (user-error "Allowed effort values are not set")))
15694 (allowed
15695 (message "Select 1-9,0, [RET%s]: %s"
15696 (if cur (concat "=" cur) "")
15697 (mapconcat 'car allowed " "))
15698 (setq rpl (read-char-exclusive))
15699 (if (equal rpl ?\r)
15701 (setq rpl (- rpl ?0))
15702 (when (equal rpl 0) (setq rpl 10))
15703 (if (and (> rpl 0) (<= rpl (length allowed)))
15704 (car (nth (1- rpl) allowed))
15705 (org-completing-read "Effort: " allowed nil))))
15707 (org-completing-read
15708 (concat "Effort" (and cur (string-match "\\S-" cur)
15709 (concat " [" cur "]"))
15710 ": ")
15711 existing nil nil "" nil cur)))))
15712 (unless (equal (org-entry-get nil prop) val)
15713 (org-entry-put nil prop val))
15714 (org-refresh-property
15715 '((effort . identity)
15716 (effort-minutes . org-duration-string-to-minutes))
15717 val)
15718 (when (equal heading (bound-and-true-p org-clock-current-task))
15719 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15720 (org-clock-update-mode-line))
15721 (message "%s is now %s" prop val)))
15723 (defun org-entry-properties (&optional pom which)
15724 "Get all properties of the current entry.
15726 When POM is a buffer position, get all properties from the entry
15727 there instead.
15729 This includes the TODO keyword, the tags, time strings for
15730 deadline, scheduled, and clocking, and any additional properties
15731 defined in the entry.
15733 If WHICH is nil or `all', get all properties. If WHICH is
15734 `special' or `standard', only get that subclass. If WHICH is
15735 a string, only get that property.
15737 Return value is an alist. Keys are properties, as upcased
15738 strings."
15739 (org-with-point-at pom
15740 (when (and (derived-mode-p 'org-mode)
15741 (ignore-errors (org-back-to-heading t)))
15742 (catch 'exit
15743 (let* ((beg (point))
15744 (specific (and (stringp which) (upcase which)))
15745 (which (cond ((not specific) which)
15746 ((member specific org-special-properties) 'special)
15747 (t 'standard)))
15748 props)
15749 ;; Get the special properties, like TODO and TAGS.
15750 (when (memq which '(nil all special))
15751 (when (or (not specific) (string= specific "CLOCKSUM"))
15752 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15753 (when clocksum
15754 (push (cons "CLOCKSUM"
15755 (org-minutes-to-clocksum-string clocksum))
15756 props)))
15757 (when specific (throw 'exit props)))
15758 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15759 (let ((clocksumt (get-text-property (point)
15760 :org-clock-minutes-today)))
15761 (when clocksumt
15762 (push (cons "CLOCKSUM_T"
15763 (org-minutes-to-clocksum-string clocksumt))
15764 props)))
15765 (when specific (throw 'exit props)))
15766 (when (or (not specific) (string= specific "ITEM"))
15767 (let ((case-fold-search nil))
15768 (when (looking-at org-complex-heading-regexp)
15769 (push (cons "ITEM"
15770 (let ((title (match-string-no-properties 4)))
15771 (if (org-string-nw-p title)
15772 (org-remove-tabs title)
15773 "")))
15774 props)))
15775 (when specific (throw 'exit props)))
15776 (when (or (not specific) (string= specific "TODO"))
15777 (let ((case-fold-search nil))
15778 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15779 (push (cons "TODO" (match-string-no-properties 2)) props)))
15780 (when specific (throw 'exit props)))
15781 (when (or (not specific) (string= specific "PRIORITY"))
15782 (push (cons "PRIORITY"
15783 (if (looking-at org-priority-regexp)
15784 (match-string-no-properties 2)
15785 (char-to-string org-default-priority)))
15786 props)
15787 (when specific (throw 'exit props)))
15788 (when (or (not specific) (string= specific "FILE"))
15789 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15790 props)
15791 (when specific (throw 'exit props)))
15792 (when (or (not specific) (string= specific "TAGS"))
15793 (let ((value (org-string-nw-p (org-get-tags-string))))
15794 (when value (push (cons "TAGS" value) props)))
15795 (when specific (throw 'exit props)))
15796 (when (or (not specific) (string= specific "ALLTAGS"))
15797 (let ((value (org-get-tags-at)))
15798 (when value
15799 (push (cons "ALLTAGS"
15800 (format ":%s:" (mapconcat #'identity value ":")))
15801 props)))
15802 (when specific (throw 'exit props)))
15803 (when (or (not specific) (string= specific "BLOCKED"))
15804 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15805 (when specific (throw 'exit props)))
15806 (when (or (not specific)
15807 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15808 (forward-line)
15809 (when (looking-at-p org-planning-line-re)
15810 (end-of-line)
15811 (let ((bol (line-beginning-position))
15812 ;; Backward compatibility: time keywords used to
15813 ;; be configurable (before 8.3). Make sure we
15814 ;; get the correct keyword.
15815 (key-assoc `(("CLOSED" . ,org-closed-string)
15816 ("DEADLINE" . ,org-deadline-string)
15817 ("SCHEDULED" . ,org-scheduled-string))))
15818 (dolist (pair (if specific (list (assoc specific key-assoc))
15819 key-assoc))
15820 (save-excursion
15821 (when (search-backward (cdr pair) bol t)
15822 (goto-char (match-end 0))
15823 (skip-chars-forward " \t")
15824 (and (looking-at org-ts-regexp-both)
15825 (push (cons (car pair)
15826 (match-string-no-properties 0))
15827 props)))))))
15828 (when specific (throw 'exit props)))
15829 (when (or (not specific)
15830 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15831 (let ((find-ts
15832 (lambda (end ts)
15833 ;; Fix next time-stamp before END. TS is the
15834 ;; list of time-stamps found so far.
15835 (let ((ts ts)
15836 (regexp (cond
15837 ((string= specific "TIMESTAMP")
15838 org-ts-regexp)
15839 ((string= specific "TIMESTAMP_IA")
15840 org-ts-regexp-inactive)
15841 ((assoc "TIMESTAMP_IA" ts)
15842 org-ts-regexp)
15843 ((assoc "TIMESTAMP" ts)
15844 org-ts-regexp-inactive)
15845 (t org-ts-regexp-both))))
15846 (catch 'next
15847 (while (re-search-forward regexp end t)
15848 (backward-char)
15849 (let ((object (org-element-context)))
15850 ;; Accept to match timestamps in node
15851 ;; properties, too.
15852 (when (memq (org-element-type object)
15853 '(node-property timestamp))
15854 (let ((type
15855 (org-element-property :type object)))
15856 (cond
15857 ((and (memq type '(active active-range))
15858 (not (equal specific "TIMESTAMP_IA")))
15859 (unless (assoc "TIMESTAMP" ts)
15860 (push (cons "TIMESTAMP"
15861 (org-element-property
15862 :raw-value object))
15864 (when specific (throw 'exit ts))))
15865 ((and (memq type '(inactive inactive-range))
15866 (not (string= specific "TIMESTAMP")))
15867 (unless (assoc "TIMESTAMP_IA" ts)
15868 (push (cons "TIMESTAMP_IA"
15869 (org-element-property
15870 :raw-value object))
15872 (when specific (throw 'exit ts))))))
15873 ;; Both timestamp types are found,
15874 ;; move to next part.
15875 (when (= (length ts) 2) (throw 'next ts)))))
15876 ts)))))
15877 (goto-char beg)
15878 ;; First look for timestamps within headline.
15879 (let ((ts (funcall find-ts (line-end-position) nil)))
15880 (if (= (length ts) 2) (setq props (nconc ts props))
15881 ;; Then find timestamps in the section, skipping
15882 ;; planning line.
15883 (let ((end (save-excursion (outline-next-heading))))
15884 (forward-line)
15885 (when (looking-at-p org-planning-line-re) (forward-line))
15886 (setq props (nconc (funcall find-ts end ts) props))))))))
15887 ;; Get the standard properties, like :PROP:.
15888 (when (memq which '(nil all standard))
15889 ;; If we are looking after a specific property, delegate
15890 ;; to `org-entry-get', which is faster. However, make an
15891 ;; exception for "CATEGORY", since it can be also set
15892 ;; through keywords (i.e. #+CATEGORY).
15893 (if (and specific (not (equal specific "CATEGORY")))
15894 (let ((value (org-entry-get beg specific nil t)))
15895 (throw 'exit (and value (list (cons specific value)))))
15896 (let ((range (org-get-property-block beg)))
15897 (when range
15898 (let ((end (cdr range)) seen-base)
15899 (goto-char (car range))
15900 ;; Unlike to `org--update-property-plist', we
15901 ;; handle the case where base values is found
15902 ;; after its extension. We also forbid standard
15903 ;; properties to be named as special properties.
15904 (while (re-search-forward org-property-re end t)
15905 (let* ((key (upcase (match-string-no-properties 2)))
15906 (extendp (string-match-p "\\+\\'" key))
15907 (key-base (if extendp (substring key 0 -1) key))
15908 (value (match-string-no-properties 3)))
15909 (cond
15910 ((member-ignore-case key-base org-special-properties))
15911 (extendp
15912 (setq props
15913 (org--update-property-plist key value props)))
15914 ((member key seen-base))
15915 (t (push key seen-base)
15916 (let ((p (assoc-string key props t)))
15917 (if p (setcdr p (concat value " " (cdr p)))
15918 (push (cons key value) props))))))))))))
15919 (unless (assoc "CATEGORY" props)
15920 (push (cons "CATEGORY" (org-get-category beg)) props)
15921 (when (string= specific "CATEGORY") (throw 'exit props)))
15922 ;; Return value.
15923 props)))))
15925 (defun org--property-local-values (property literal-nil)
15926 "Return value for PROPERTY in current entry.
15927 Value is a list whose car is the base value for PROPERTY and cdr
15928 a list of accumulated values. Return nil if neither is found in
15929 the entry. Also return nil when PROPERTY is set to \"nil\",
15930 unless LITERAL-NIL is non-nil."
15931 (let ((range (org-get-property-block)))
15932 (when range
15933 (goto-char (car range))
15934 (let* ((case-fold-search t)
15935 (end (cdr range))
15936 (value
15937 ;; Base value.
15938 (save-excursion
15939 (let ((v (and (re-search-forward
15940 (org-re-property property nil t) end t)
15941 (match-string-no-properties 3))))
15942 (list (if literal-nil v (org-not-nil v)))))))
15943 ;; Find additional values.
15944 (let* ((property+ (org-re-property (concat property "+") nil t)))
15945 (while (re-search-forward property+ end t)
15946 (push (match-string-no-properties 3) value)))
15947 ;; Return final values.
15948 (and (not (equal value '(nil))) (nreverse value))))))
15950 (defun org--property-global-value (property literal-nil)
15951 "Return value for PROPERTY in current buffer.
15952 Return value is a string. Return nil if property is not set
15953 globally. Also return nil when PROPERTY is set to \"nil\",
15954 unless LITERAL-NIL is non-nil."
15955 (let ((global
15956 (cdr (or (assoc-string property org-file-properties t)
15957 (assoc-string property org-global-properties t)
15958 (assoc-string property org-global-properties-fixed t)))))
15959 (if literal-nil global (org-not-nil global))))
15961 (defun org-entry-get (pom property &optional inherit literal-nil)
15962 "Get value of PROPERTY for entry or content at point-or-marker POM.
15964 If INHERIT is non-nil and the entry does not have the property,
15965 then also check higher levels of the hierarchy. If INHERIT is
15966 the symbol `selective', use inheritance only if the setting in
15967 `org-use-property-inheritance' selects PROPERTY for inheritance.
15969 If the property is present but empty, the return value is the
15970 empty string. If the property is not present at all, nil is
15971 returned. In any other case, return the value as a string.
15972 Search is case-insensitive.
15974 If LITERAL-NIL is set, return the string value \"nil\" as
15975 a string, do not interpret it as the list atom nil. This is used
15976 for inheritance when a \"nil\" value can supersede a non-nil
15977 value higher up the hierarchy."
15978 (org-with-point-at pom
15979 (cond
15980 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15981 ;; We need a special property. Use `org-entry-properties' to
15982 ;; retrieve it, but specify the wanted property.
15983 (cdr (assoc-string property (org-entry-properties nil property))))
15984 ((and inherit
15985 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15986 (org-entry-get-with-inheritance property literal-nil))
15988 (let* ((local (org--property-local-values property literal-nil))
15989 (value (and local (mapconcat #'identity (delq nil local) " "))))
15990 (if literal-nil value (org-not-nil value)))))))
15992 (defun org-property-or-variable-value (var &optional inherit)
15993 "Check if there is a property fixing the value of VAR.
15994 If yes, return this value. If not, return the current value of the variable."
15995 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15996 (if (and prop (stringp prop) (string-match "\\S-" prop))
15997 (read prop)
15998 (symbol-value var))))
16000 (defun org-entry-delete (pom property)
16001 "Delete PROPERTY from entry at point-or-marker POM.
16002 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16003 non-nil when a property was removed."
16004 (org-with-point-at pom
16005 (pcase (org-get-property-block)
16006 (`(,begin . ,origin)
16007 (let* ((end (copy-marker origin))
16008 (re (org-re-property
16009 (concat (regexp-quote property) "\\+?") t t)))
16010 (goto-char begin)
16011 (while (re-search-forward re end t)
16012 (delete-region (match-beginning 0) (line-beginning-position 2)))
16013 ;; If drawer is empty, remove it altogether.
16014 (when (= begin end)
16015 (delete-region (line-beginning-position 0)
16016 (line-beginning-position 2)))
16017 ;; Return non-nil if some property was removed.
16018 (prog1 (/= end origin) (set-marker end nil))))
16019 (_ nil))))
16021 ;; Multi-values properties are properties that contain multiple values
16022 ;; These values are assumed to be single words, separated by whitespace.
16023 (defun org-entry-add-to-multivalued-property (pom property value)
16024 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16025 (let* ((old (org-entry-get pom property))
16026 (values (and old (org-split-string old "[ \t]"))))
16027 (setq value (org-entry-protect-space value))
16028 (unless (member value values)
16029 (setq values (append values (list value)))
16030 (org-entry-put pom property
16031 (mapconcat 'identity values " ")))))
16033 (defun org-entry-remove-from-multivalued-property (pom property value)
16034 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16035 (let* ((old (org-entry-get pom property))
16036 (values (and old (org-split-string old "[ \t]"))))
16037 (setq value (org-entry-protect-space value))
16038 (when (member value values)
16039 (setq values (delete value values))
16040 (org-entry-put pom property
16041 (mapconcat 'identity values " ")))))
16043 (defun org-entry-member-in-multivalued-property (pom property value)
16044 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16045 (let* ((old (org-entry-get pom property))
16046 (values (and old (org-split-string old "[ \t]"))))
16047 (setq value (org-entry-protect-space value))
16048 (member value values)))
16050 (defun org-entry-get-multivalued-property (pom property)
16051 "Return a list of values in a multivalued property."
16052 (let* ((value (org-entry-get pom property))
16053 (values (and value (org-split-string value "[ \t]"))))
16054 (mapcar 'org-entry-restore-space values)))
16056 (defun org-entry-put-multivalued-property (pom property &rest values)
16057 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16058 VALUES should be a list of strings. Spaces will be protected."
16059 (org-entry-put pom property
16060 (mapconcat 'org-entry-protect-space values " "))
16061 (let* ((value (org-entry-get pom property))
16062 (values (and value (org-split-string value "[ \t]"))))
16063 (mapcar 'org-entry-restore-space values)))
16065 (defun org-entry-protect-space (s)
16066 "Protect spaces and newline in string S."
16067 (while (string-match " " s)
16068 (setq s (replace-match "%20" t t s)))
16069 (while (string-match "\n" s)
16070 (setq s (replace-match "%0A" t t s)))
16073 (defun org-entry-restore-space (s)
16074 "Restore spaces and newline in string S."
16075 (while (string-match "%20" s)
16076 (setq s (replace-match " " t t s)))
16077 (while (string-match "%0A" s)
16078 (setq s (replace-match "\n" t t s)))
16081 (defvar org-entry-property-inherited-from (make-marker)
16082 "Marker pointing to the entry from where a property was inherited.
16083 Each call to `org-entry-get-with-inheritance' will set this marker to the
16084 location of the entry where the inheritance search matched. If there was
16085 no match, the marker will point nowhere.
16086 Note that also `org-entry-get' calls this function, if the INHERIT flag
16087 is set.")
16089 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16090 "Get PROPERTY of entry or content at point, search higher levels if needed.
16091 The search will stop at the first ancestor which has the property defined.
16092 If the value found is \"nil\", return nil to show that the property
16093 should be considered as undefined (this is the meaning of nil here).
16094 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16095 (move-marker org-entry-property-inherited-from nil)
16096 (org-with-wide-buffer
16097 (let (value)
16098 (catch 'exit
16099 (while t
16100 (let ((v (org--property-local-values property literal-nil)))
16101 (when v
16102 (setq value
16103 (concat (mapconcat #'identity (delq nil v) " ")
16104 (and value " ")
16105 value)))
16106 (cond
16107 ((car v)
16108 (org-back-to-heading t)
16109 (move-marker org-entry-property-inherited-from (point))
16110 (throw 'exit nil))
16111 ((org-up-heading-safe))
16113 (let ((global (org--property-global-value property literal-nil)))
16114 (cond ((not global))
16115 (value (setq value (concat global " " value)))
16116 (t (setq value global))))
16117 (throw 'exit nil))))))
16118 (if literal-nil value (org-not-nil value)))))
16120 (defvar org-property-changed-functions nil
16121 "Hook called when the value of a property has changed.
16122 Each hook function should accept two arguments, the name of the property
16123 and the new value.")
16125 (defun org-entry-put (pom property value)
16126 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16128 If the value is nil, it is converted to the empty string. If it
16129 is not a string, an error is raised. Also raise an error on
16130 invalid property names.
16132 PROPERTY can be any regular property (see
16133 `org-special-properties'). It can also be \"TODO\",
16134 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16136 For the last two properties, VALUE may have any of the special
16137 values \"earlier\" and \"later\". The function then increases or
16138 decreases scheduled or deadline date by one day."
16139 (cond ((null value) (setq value ""))
16140 ((not (stringp value)) (error "Properties values should be strings"))
16141 ((not (org--valid-property-p property))
16142 (user-error "Invalid property name: \"%s\"" property)))
16143 (org-with-point-at pom
16144 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16145 (org-back-to-heading t)
16146 (org-with-limited-levels (org-back-to-heading t)))
16147 (let ((beg (point)))
16148 (cond
16149 ((equal property "TODO")
16150 (cond ((not (org-string-nw-p value)) (setq value 'none))
16151 ((not (member value org-todo-keywords-1))
16152 (user-error "\"%s\" is not a valid TODO state" value)))
16153 (org-todo value)
16154 (org-set-tags nil 'align))
16155 ((equal property "PRIORITY")
16156 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16157 (org-set-tags nil 'align))
16158 ((equal property "SCHEDULED")
16159 (forward-line)
16160 (if (and (looking-at-p org-planning-line-re)
16161 (re-search-forward
16162 org-scheduled-time-regexp (line-end-position) t))
16163 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16164 ((string= value "later") (org-timestamp-change 1 'day))
16165 ((string= value "") (org-schedule '(4)))
16166 (t (org-schedule nil value)))
16167 (if (member value '("earlier" "later" ""))
16168 (call-interactively #'org-schedule)
16169 (org-schedule nil value))))
16170 ((equal property "DEADLINE")
16171 (forward-line)
16172 (if (and (looking-at-p org-planning-line-re)
16173 (re-search-forward
16174 org-deadline-time-regexp (line-end-position) t))
16175 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16176 ((string= value "later") (org-timestamp-change 1 'day))
16177 ((string= value "") (org-deadline '(4)))
16178 (t (org-deadline nil value)))
16179 (if (member value '("earlier" "later" ""))
16180 (call-interactively #'org-deadline)
16181 (org-deadline nil value))))
16182 ((member property org-special-properties)
16183 (error "The %s property cannot be set with `org-entry-put'" property))
16185 (let* ((range (org-get-property-block beg 'force))
16186 (end (cdr range))
16187 (case-fold-search t))
16188 (goto-char (car range))
16189 (if (re-search-forward (org-re-property property nil t) end t)
16190 (progn (delete-region (match-beginning 0) (match-end 0))
16191 (goto-char (match-beginning 0)))
16192 (goto-char end)
16193 (insert "\n")
16194 (backward-char))
16195 (insert ":" property ":")
16196 (when value (insert " " value))
16197 (org-indent-line)))))
16198 (run-hook-with-args 'org-property-changed-functions property value)))
16200 (defun org-buffer-property-keys
16201 (&optional specials defaults columns ignore-malformed)
16202 "Get all property keys in the current buffer.
16204 When SPECIALS is non-nil, also list the special properties that
16205 reflect things like tags and TODO state.
16207 When DEFAULTS is non-nil, also include properties that has
16208 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16209 DESCRIPTION, LOCATION, and LOGGING and others.
16211 When COLUMNS in non-nil, also include property names given in
16212 COLUMN formats in the current buffer.
16214 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16215 automatically performed, such drawers will be silently ignored."
16216 (let ((case-fold-search t)
16217 (props (append
16218 (and specials org-special-properties)
16219 (and defaults (cons org-effort-property org-default-properties))
16220 nil)))
16221 (org-with-wide-buffer
16222 (goto-char (point-min))
16223 (while (re-search-forward org-property-start-re nil t)
16224 (let ((range (org-get-property-block)))
16225 (catch 'skip
16226 (unless range
16227 (when (and (not ignore-malformed)
16228 (not (org-before-first-heading-p))
16229 (y-or-n-p (format "Malformed drawer at %d, repair?"
16230 (line-beginning-position))))
16231 (org-get-property-block nil t))
16232 (throw 'skip nil))
16233 (goto-char (car range))
16234 (let ((begin (car range))
16235 (end (cdr range)))
16236 ;; Make sure that found property block is not located
16237 ;; before current point, as it would generate an infloop.
16238 ;; It can happen, for example, in the following
16239 ;; situation:
16241 ;; * Headline
16242 ;; :PROPERTIES:
16243 ;; ...
16244 ;; :END:
16245 ;; *************** Inlinetask
16246 ;; #+BEGIN_EXAMPLE
16247 ;; :PROPERTIES:
16248 ;; #+END_EXAMPLE
16250 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16251 (while (< (point) end)
16252 (let ((p (progn (looking-at org-property-re)
16253 (match-string-no-properties 2))))
16254 ;; Only add true property name, not extension symbol.
16255 (push (if (not (string-match-p "\\+\\'" p)) p
16256 (substring p 0 -1))
16257 props))
16258 (forward-line))))
16259 (outline-next-heading)))
16260 (when columns
16261 (goto-char (point-min))
16262 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16263 (let ((element (org-element-at-point)))
16264 (when (memq (org-element-type element) '(keyword node-property))
16265 (let ((value (org-element-property :value element))
16266 (start 0))
16267 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16268 (setq start (match-end 0))
16269 (let ((p (match-string-no-properties 1 value)))
16270 (unless (member-ignore-case p org-special-properties)
16271 (push p props))))))))))
16272 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16274 (defun org-property-values (key)
16275 "List all non-nil values of property KEY in current buffer."
16276 (org-with-wide-buffer
16277 (goto-char (point-min))
16278 (let ((case-fold-search t)
16279 (re (org-re-property key))
16280 values)
16281 (while (re-search-forward re nil t)
16282 (push (org-entry-get (point) key) values))
16283 (delete-dups values))))
16285 (defun org-insert-property-drawer ()
16286 "Insert a property drawer into the current entry."
16287 (org-with-wide-buffer
16288 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16289 (org-back-to-heading t)
16290 (org-with-limited-levels (org-back-to-heading t)))
16291 (forward-line)
16292 (when (looking-at-p org-planning-line-re) (forward-line))
16293 (unless (looking-at-p org-property-drawer-re)
16294 ;; Make sure we start editing a line from current entry, not from
16295 ;; next one. It prevents extending text properties or overlays
16296 ;; belonging to the latter.
16297 (when (bolp) (backward-char))
16298 (let ((begin (1+ (point)))
16299 (inhibit-read-only t))
16300 (insert "\n:PROPERTIES:\n:END:")
16301 (when (eobp) (insert "\n"))
16302 (org-indent-region begin (point))))))
16304 (defun org-insert-drawer (&optional arg drawer)
16305 "Insert a drawer at point.
16307 When optional argument ARG is non-nil, insert a property drawer.
16309 Optional argument DRAWER, when non-nil, is a string representing
16310 drawer's name. Otherwise, the user is prompted for a name.
16312 If a region is active, insert the drawer around that region
16313 instead.
16315 Point is left between drawer's boundaries."
16316 (interactive "P")
16317 (let* ((drawer (if arg "PROPERTIES"
16318 (or drawer (read-from-minibuffer "Drawer: ")))))
16319 (cond
16320 ;; With C-u, fall back on `org-insert-property-drawer'
16321 (arg (org-insert-property-drawer))
16322 ;; Check validity of suggested drawer's name.
16323 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16324 (user-error "Invalid drawer name"))
16325 ;; With an active region, insert a drawer at point.
16326 ((not (org-region-active-p))
16327 (progn
16328 (unless (bolp) (insert "\n"))
16329 (insert (format ":%s:\n\n:END:\n" drawer))
16330 (forward-line -2)))
16331 ;; Otherwise, insert the drawer at point
16333 (let ((rbeg (region-beginning))
16334 (rend (copy-marker (region-end))))
16335 (unwind-protect
16336 (progn
16337 (goto-char rbeg)
16338 (beginning-of-line)
16339 (when (save-excursion
16340 (re-search-forward org-outline-regexp-bol rend t))
16341 (user-error "Drawers cannot contain headlines"))
16342 ;; Position point at the beginning of the first
16343 ;; non-blank line in region. Insert drawer's opening
16344 ;; there, then indent it.
16345 (org-skip-whitespace)
16346 (beginning-of-line)
16347 (insert ":" drawer ":\n")
16348 (forward-line -1)
16349 (indent-for-tab-command)
16350 ;; Move point to the beginning of the first blank line
16351 ;; after the last non-blank line in region. Insert
16352 ;; drawer's closing, then indent it.
16353 (goto-char rend)
16354 (skip-chars-backward " \r\t\n")
16355 (insert "\n:END:")
16356 (deactivate-mark t)
16357 (indent-for-tab-command)
16358 (unless (eolp) (insert "\n")))
16359 ;; Clear marker, whatever the outcome of insertion is.
16360 (set-marker rend nil)))))))
16362 (defvar org-property-set-functions-alist nil
16363 "Property set function alist.
16364 Each entry should have the following format:
16366 (PROPERTY . READ-FUNCTION)
16368 The read function will be called with the same argument as
16369 `org-completing-read'.")
16371 (defun org-set-property-function (property)
16372 "Get the function that should be used to set PROPERTY.
16373 This is computed according to `org-property-set-functions-alist'."
16374 (or (cdr (assoc property org-property-set-functions-alist))
16375 'org-completing-read))
16377 (defun org-read-property-value (property)
16378 "Read PROPERTY value from user."
16379 (let* ((completion-ignore-case t)
16380 (allowed (org-property-get-allowed-values nil property 'table))
16381 (cur (org-entry-get nil property))
16382 (prompt (concat property " value"
16383 (if (and cur (string-match "\\S-" cur))
16384 (concat " [" cur "]") "") ": "))
16385 (set-function (org-set-property-function property))
16386 (val (if allowed
16387 (funcall set-function prompt allowed nil
16388 (not (get-text-property 0 'org-unrestricted
16389 (caar allowed))))
16390 (funcall set-function prompt
16391 (mapcar 'list (org-property-values property))
16392 nil nil "" nil cur))))
16393 (org-trim val)))
16395 (defvar org-last-set-property nil)
16396 (defvar org-last-set-property-value nil)
16397 (defun org-read-property-name ()
16398 "Read a property name."
16399 (let ((completion-ignore-case t)
16400 (default-prop (or (and (org-at-property-p)
16401 (match-string-no-properties 2))
16402 org-last-set-property)))
16403 (org-completing-read
16404 (concat "Property"
16405 (if default-prop (concat " [" default-prop "]") "")
16406 ": ")
16407 (mapcar #'list (org-buffer-property-keys nil t t))
16408 nil nil nil nil default-prop)))
16410 (defun org-set-property-and-value (use-last)
16411 "Allow to set [PROPERTY]: [value] direction from prompt.
16412 When use-default, don't even ask, just use the last
16413 \"[PROPERTY]: [value]\" string from the history."
16414 (interactive "P")
16415 (let* ((completion-ignore-case t)
16416 (pv (or (and use-last org-last-set-property-value)
16417 (org-completing-read
16418 "Enter a \"[Property]: [value]\" pair: "
16419 nil nil nil nil nil
16420 org-last-set-property-value)))
16421 prop val)
16422 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16423 (setq prop (match-string 1 pv)
16424 val (match-string 2 pv))
16425 (org-set-property prop val))))
16427 (defun org-set-property (property value)
16428 "In the current entry, set PROPERTY to VALUE.
16430 When called interactively, this will prompt for a property name, offering
16431 completion on existing and default properties. And then it will prompt
16432 for a value, offering completion either on allowed values (via an inherited
16433 xxx_ALL property) or on existing values in other instances of this property
16434 in the current file.
16436 Throw an error when trying to set a property with an invalid name."
16437 (interactive (list nil nil))
16438 (let ((property (or property (org-read-property-name))))
16439 ;; `org-entry-put' also makes the following check, but this one
16440 ;; avoids polluting `org-last-set-property' and
16441 ;; `org-last-set-property-value' needlessly.
16442 (unless (org--valid-property-p property)
16443 (user-error "Invalid property name: \"%s\"" property))
16444 (let ((value (or value (org-read-property-value property)))
16445 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16446 (setq org-last-set-property property)
16447 (setq org-last-set-property-value (concat property ": " value))
16448 ;; Possibly postprocess the inserted value:
16449 (when fn (setq value (funcall fn value)))
16450 (unless (equal (org-entry-get nil property) value)
16451 (org-entry-put nil property value)))))
16453 (defun org-find-property (property &optional value)
16454 "Find first entry in buffer that sets PROPERTY.
16456 When optional argument VALUE is non-nil, only consider an entry
16457 if it contains PROPERTY set to this value. If PROPERTY should be
16458 explicitly set to nil, use string \"nil\" for VALUE.
16460 Return position where the entry begins, or nil if there is no
16461 such entry. If narrowing is in effect, only search the visible
16462 part of the buffer."
16463 (save-excursion
16464 (goto-char (point-min))
16465 (let ((case-fold-search t)
16466 (re (org-re-property property nil (not value) value)))
16467 (catch 'exit
16468 (while (re-search-forward re nil t)
16469 (when (if value (org-at-property-p)
16470 (org-entry-get (point) property nil t))
16471 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16473 (defun org-delete-property (property)
16474 "In the current entry, delete PROPERTY."
16475 (interactive
16476 (let* ((completion-ignore-case t)
16477 (cat (org-entry-get (point) "CATEGORY"))
16478 (props0 (org-entry-properties nil 'standard))
16479 (props (if cat props0
16480 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16481 (prop (if (< 1 (length props))
16482 (completing-read "Property: " props nil t)
16483 (caar props))))
16484 (list prop)))
16485 (if (not property)
16486 (message "No property to delete in this entry")
16487 (org-entry-delete nil property)
16488 (message "Property \"%s\" deleted" property)))
16490 (defun org-delete-property-globally (property)
16491 "Remove PROPERTY globally, from all entries.
16492 This function ignores narrowing, if any."
16493 (interactive
16494 (let* ((completion-ignore-case t)
16495 (prop (completing-read
16496 "Globally remove property: "
16497 (mapcar #'list (org-buffer-property-keys)))))
16498 (list prop)))
16499 (org-with-wide-buffer
16500 (goto-char (point-min))
16501 (let ((count 0)
16502 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16503 (while (re-search-forward re nil t)
16504 (when (org-entry-delete (point) property) (cl-incf count)))
16505 (message "Property \"%s\" removed from %d entries" property count))))
16507 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16509 (defun org-compute-property-at-point ()
16510 "Compute the property at point.
16511 This looks for an enclosing column format, extracts the operator and
16512 then applies it to the property in the column format's scope."
16513 (interactive)
16514 (unless (org-at-property-p)
16515 (user-error "Not at a property"))
16516 (let ((prop (match-string-no-properties 2)))
16517 (org-columns-get-format-and-top-level)
16518 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16519 (user-error "No operator defined for property %s" prop))
16520 (org-columns-compute prop)))
16522 (defvar org-property-allowed-value-functions nil
16523 "Hook for functions supplying allowed values for a specific property.
16524 The functions must take a single argument, the name of the property, and
16525 return a flat list of allowed values. If \":ETC\" is one of
16526 the values, this means that these values are intended as defaults for
16527 completion, but that other values should be allowed too.
16528 The functions must return nil if they are not responsible for this
16529 property.")
16531 (defun org-property-get-allowed-values (pom property &optional table)
16532 "Get allowed values for the property PROPERTY.
16533 When TABLE is non-nil, return an alist that can directly be used for
16534 completion."
16535 (let (vals)
16536 (cond
16537 ((equal property "TODO")
16538 (setq vals (org-with-point-at pom
16539 (append org-todo-keywords-1 '("")))))
16540 ((equal property "PRIORITY")
16541 (let ((n org-lowest-priority))
16542 (while (>= n org-highest-priority)
16543 (push (char-to-string n) vals)
16544 (setq n (1- n)))))
16545 ((equal property "CATEGORY"))
16546 ((member property org-special-properties))
16547 ((setq vals (run-hook-with-args-until-success
16548 'org-property-allowed-value-functions property)))
16550 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16551 (when (and vals (string-match "\\S-" vals))
16552 (setq vals (car (read-from-string (concat "(" vals ")"))))
16553 (setq vals (mapcar (lambda (x)
16554 (cond ((stringp x) x)
16555 ((numberp x) (number-to-string x))
16556 ((symbolp x) (symbol-name x))
16557 (t "???")))
16558 vals)))))
16559 (when (member ":ETC" vals)
16560 (setq vals (remove ":ETC" vals))
16561 (org-add-props (car vals) '(org-unrestricted t)))
16562 (if table (mapcar 'list vals) vals)))
16564 (defun org-property-previous-allowed-value (&optional _previous)
16565 "Switch to the next allowed value for this property."
16566 (interactive)
16567 (org-property-next-allowed-value t))
16569 (defun org-property-next-allowed-value (&optional previous)
16570 "Switch to the next allowed value for this property."
16571 (interactive)
16572 (unless (org-at-property-p)
16573 (user-error "Not at a property"))
16574 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16575 (key (match-string 2))
16576 (value (match-string 3))
16577 (allowed (or (org-property-get-allowed-values (point) key)
16578 (and (member value '("[ ]" "[-]" "[X]"))
16579 '("[ ]" "[X]"))))
16580 (heading (save-match-data (nth 4 (org-heading-components))))
16581 nval)
16582 (unless allowed
16583 (user-error "Allowed values for this property have not been defined"))
16584 (when previous (setq allowed (reverse allowed)))
16585 (when (member value allowed)
16586 (setq nval (car (cdr (member value allowed)))))
16587 (setq nval (or nval (car allowed)))
16588 (when (equal nval value)
16589 (user-error "Only one allowed value for this property"))
16590 (org-at-property-p)
16591 (replace-match (concat " :" key ": " nval) t t)
16592 (org-indent-line)
16593 (beginning-of-line 1)
16594 (skip-chars-forward " \t")
16595 (when (equal prop org-effort-property)
16596 (org-refresh-property
16597 '((effort . identity)
16598 (effort-minutes . org-duration-string-to-minutes))
16599 nval)
16600 (when (string= org-clock-current-task heading)
16601 (setq org-clock-effort nval)
16602 (org-clock-update-mode-line)))
16603 (run-hook-with-args 'org-property-changed-functions key nval)))
16605 (defun org-find-olp (path &optional this-buffer)
16606 "Return a marker pointing to the entry at outline path OLP.
16607 If anything goes wrong, throw an error.
16608 You can wrap this call to catch the error like this:
16610 (condition-case msg
16611 (org-mobile-locate-entry (match-string 4))
16612 (error (nth 1 msg)))
16614 The return value will then be either a string with the error message,
16615 or a marker if everything is OK.
16617 If THIS-BUFFER is set, the outline path does not contain a file,
16618 only headings."
16619 (let* ((file (if this-buffer buffer-file-name (pop path)))
16620 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16621 (level 1)
16622 (lmin 1)
16623 (lmax 1)
16624 end found flevel)
16625 (unless buffer (error "File not found :%s" file))
16626 (with-current-buffer buffer
16627 (org-with-wide-buffer
16628 (goto-char (point-min))
16629 (dolist (heading path)
16630 (let ((re (format org-complex-heading-regexp-format
16631 (regexp-quote heading)))
16632 (cnt 0))
16633 (while (re-search-forward re end t)
16634 (setq level (- (match-end 1) (match-beginning 1)))
16635 (when (and (>= level lmin) (<= level lmax))
16636 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16637 (when (= cnt 0)
16638 (error "Heading not found on level %d: %s" lmax heading))
16639 (when (> cnt 1)
16640 (error "Heading not unique on level %d: %s" lmax heading))
16641 (goto-char found)
16642 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16643 (setq end (save-excursion (org-end-of-subtree t t)))))
16644 (when (org-at-heading-p)
16645 (point-marker))))))
16647 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16648 "Find node HEADING in BUFFER.
16649 Return a marker to the heading if it was found, or nil if not.
16650 If POS-ONLY is set, return just the position instead of a marker.
16652 The heading text must match exact, but it may have a TODO keyword,
16653 a priority cookie and tags in the standard locations."
16654 (with-current-buffer (or buffer (current-buffer))
16655 (org-with-wide-buffer
16656 (goto-char (point-min))
16657 (let (case-fold-search)
16658 (when (re-search-forward
16659 (format org-complex-heading-regexp-format
16660 (regexp-quote heading)) nil t)
16661 (if pos-only
16662 (match-beginning 0)
16663 (move-marker (make-marker) (match-beginning 0))))))))
16665 (defun org-find-exact-heading-in-directory (heading &optional dir)
16666 "Find Org node headline HEADING in all .org files in directory DIR.
16667 When the target headline is found, return a marker to this location."
16668 (let ((files (directory-files (or dir default-directory)
16669 t "\\`[^.#].*\\.org\\'"))
16670 visiting m buffer)
16671 (catch 'found
16672 (dolist (file files)
16673 (message "trying %s" file)
16674 (setq visiting (org-find-base-buffer-visiting file))
16675 (setq buffer (or visiting (find-file-noselect file)))
16676 (setq m (org-find-exact-headline-in-buffer
16677 heading buffer))
16678 (when (and (not m) (not visiting)) (kill-buffer buffer))
16679 (and m (throw 'found m))))))
16681 (defun org-find-entry-with-id (ident)
16682 "Locate the entry that contains the ID property with exact value IDENT.
16683 IDENT can be a string, a symbol or a number, this function will search for
16684 the string representation of it.
16685 Return the position where this entry starts, or nil if there is no such entry."
16686 (interactive "sID: ")
16687 (let ((id (cond
16688 ((stringp ident) ident)
16689 ((symbolp ident) (symbol-name ident))
16690 ((numberp ident) (number-to-string ident))
16691 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16692 (org-with-wide-buffer (org-find-property "ID" id))))
16694 ;;;; Timestamps
16696 (defvar org-last-changed-timestamp nil)
16697 (defvar org-last-inserted-timestamp nil
16698 "The last time stamp inserted with `org-insert-time-stamp'.")
16700 (defun org-time-stamp (arg &optional inactive)
16701 "Prompt for a date/time and insert a time stamp.
16703 If the user specifies a time like HH:MM or if this command is
16704 called with at least one prefix argument, the time stamp contains
16705 the date and the time. Otherwise, only the date is included.
16707 All parts of a date not specified by the user are filled in from
16708 the timestamp at point, if any, or the current date/time
16709 otherwise.
16711 If there is already a timestamp at the cursor, it is replaced.
16713 With two universal prefix arguments, insert an active timestamp
16714 with the current time without prompting the user.
16716 When called from lisp, the timestamp is inactive if INACTIVE is
16717 non-nil."
16718 (interactive "P")
16719 (let* ((ts (cond
16720 ((org-at-date-range-p t)
16721 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16722 ((org-at-timestamp-p t) (match-string 0))))
16723 ;; Default time is either the timestamp at point or today.
16724 ;; When entering a range, only the range start is considered.
16725 (default-time (if (not ts) (current-time)
16726 (apply #'encode-time (org-parse-time-string ts))))
16727 (default-input (and ts (org-get-compact-tod ts)))
16728 (repeater (and ts
16729 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16730 (match-string 0 ts)))
16731 org-time-was-given
16732 org-end-time-was-given
16733 (time
16734 (and (if (equal arg '(16)) (current-time)
16735 ;; Preserve `this-command' and `last-command'.
16736 (let ((this-command this-command)
16737 (last-command last-command))
16738 (org-read-date
16739 arg 'totime nil nil default-time default-input
16740 inactive))))))
16741 (cond
16742 ((and ts
16743 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16744 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16745 (insert "--")
16746 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16748 ;; Make sure we're on a timestamp. When in the middle of a date
16749 ;; range, move arbitrarily to range end.
16750 (unless (org-at-timestamp-p t)
16751 (skip-chars-forward "-")
16752 (org-at-timestamp-p t))
16753 (replace-match "")
16754 (setq org-last-changed-timestamp
16755 (org-insert-time-stamp
16756 time (or org-time-was-given arg)
16757 inactive nil nil (list org-end-time-was-given)))
16758 (when repeater
16759 (backward-char)
16760 (insert " " repeater)
16761 (setq org-last-changed-timestamp
16762 (concat (substring org-last-inserted-timestamp 0 -1)
16763 " " repeater ">")))
16764 (message "Timestamp updated"))
16765 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16766 (t (org-insert-time-stamp
16767 time (or org-time-was-given arg) inactive nil nil
16768 (list org-end-time-was-given))))))
16770 ;; FIXME: can we use this for something else, like computing time differences?
16771 (defun org-get-compact-tod (s)
16772 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16773 (let* ((t1 (match-string 1 s))
16774 (h1 (string-to-number (match-string 2 s)))
16775 (m1 (string-to-number (match-string 3 s)))
16776 (t2 (and (match-end 4) (match-string 5 s)))
16777 (h2 (and t2 (string-to-number (match-string 6 s))))
16778 (m2 (and t2 (string-to-number (match-string 7 s))))
16779 dh dm)
16780 (if (not t2)
16782 (setq dh (- h2 h1) dm (- m2 m1))
16783 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16784 (concat t1 "+" (number-to-string dh)
16785 (and (/= 0 dm) (format ":%02d" dm)))))))
16787 (defun org-time-stamp-inactive (&optional arg)
16788 "Insert an inactive time stamp.
16789 An inactive time stamp is enclosed in square brackets instead of angle
16790 brackets. It is inactive in the sense that it does not trigger agenda entries,
16791 does not link to the calendar and cannot be changed with the S-cursor keys.
16792 So these are more for recording a certain time/date."
16793 (interactive "P")
16794 (org-time-stamp arg 'inactive))
16796 (defvar org-date-ovl (make-overlay 1 1))
16797 (overlay-put org-date-ovl 'face 'org-date-selected)
16798 (delete-overlay org-date-ovl)
16800 (defvar org-ans1) ; dynamically scoped parameter
16801 (defvar org-ans2) ; dynamically scoped parameter
16803 (defvar org-plain-time-of-day-regexp) ; defined below
16805 (defvar org-overriding-default-time nil) ; dynamically scoped
16806 (defvar org-read-date-overlay nil)
16807 (defvar org-dcst nil) ; dynamically scoped
16808 (defvar org-read-date-history nil)
16809 (defvar org-read-date-final-answer nil)
16810 (defvar org-read-date-analyze-futurep nil)
16811 (defvar org-read-date-analyze-forced-year nil)
16812 (defvar org-read-date-inactive)
16814 (defvar org-read-date-minibuffer-local-map
16815 (let* ((map (make-sparse-keymap)))
16816 (set-keymap-parent map minibuffer-local-map)
16817 (org-defkey map (kbd ".")
16818 (lambda () (interactive)
16819 ;; Are we at the beginning of the prompt?
16820 (if (looking-back "^[^:]+: "
16821 (let ((inhibit-field-text-motion t))
16822 (line-beginning-position)))
16823 (org-eval-in-calendar '(calendar-goto-today))
16824 (insert "."))))
16825 (org-defkey map (kbd "C-.")
16826 (lambda () (interactive)
16827 (org-eval-in-calendar '(calendar-goto-today))))
16828 (org-defkey map [(meta shift left)]
16829 (lambda () (interactive)
16830 (org-eval-in-calendar '(calendar-backward-month 1))))
16831 (org-defkey map [(meta shift right)]
16832 (lambda () (interactive)
16833 (org-eval-in-calendar '(calendar-forward-month 1))))
16834 (org-defkey map [(meta shift up)]
16835 (lambda () (interactive)
16836 (org-eval-in-calendar '(calendar-backward-year 1))))
16837 (org-defkey map [(meta shift down)]
16838 (lambda () (interactive)
16839 (org-eval-in-calendar '(calendar-forward-year 1))))
16840 (org-defkey map [?\e (shift left)]
16841 (lambda () (interactive)
16842 (org-eval-in-calendar '(calendar-backward-month 1))))
16843 (org-defkey map [?\e (shift right)]
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-forward-month 1))))
16846 (org-defkey map [?\e (shift up)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-backward-year 1))))
16849 (org-defkey map [?\e (shift down)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-forward-year 1))))
16852 (org-defkey map [(shift up)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-backward-week 1))))
16855 (org-defkey map [(shift down)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-forward-week 1))))
16858 (org-defkey map [(shift left)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-backward-day 1))))
16861 (org-defkey map [(shift right)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-forward-day 1))))
16864 (org-defkey map "!"
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(diary-view-entries))
16867 (message "")))
16868 (org-defkey map ">"
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-scroll-left 1))))
16871 (org-defkey map "<"
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-scroll-right 1))))
16874 (org-defkey map "\C-v"
16875 (lambda () (interactive)
16876 (org-eval-in-calendar
16877 '(calendar-scroll-left-three-months 1))))
16878 (org-defkey map "\M-v"
16879 (lambda () (interactive)
16880 (org-eval-in-calendar
16881 '(calendar-scroll-right-three-months 1))))
16882 map)
16883 "Keymap for minibuffer commands when using `org-read-date'.")
16885 (defvar org-def)
16886 (defvar org-defdecode)
16887 (defvar org-with-time)
16889 (defvar calendar-setup) ; Dynamically scoped.
16890 (defun org-read-date (&optional with-time to-time from-string prompt
16891 default-time default-input inactive)
16892 "Read a date, possibly a time, and make things smooth for the user.
16893 The prompt will suggest to enter an ISO date, but you can also enter anything
16894 which will at least partially be understood by `parse-time-string'.
16895 Unrecognized parts of the date will default to the current day, month, year,
16896 hour and minute. If this command is called to replace a timestamp at point,
16897 or to enter the second timestamp of a range, the default time is taken
16898 from the existing stamp. Furthermore, the command prefers the future,
16899 so if you are giving a date where the year is not given, and the day-month
16900 combination is already past in the current year, it will assume you
16901 mean next year. For details, see the manual. A few examples:
16903 3-2-5 --> 2003-02-05
16904 feb 15 --> currentyear-02-15
16905 2/15 --> currentyear-02-15
16906 sep 12 9 --> 2009-09-12
16907 12:45 --> today 12:45
16908 22 sept 0:34 --> currentyear-09-22 0:34
16909 12 --> currentyear-currentmonth-12
16910 Fri --> nearest Friday after today
16911 -Tue --> last Tuesday
16912 etc.
16914 Furthermore you can specify a relative date by giving, as the *first* thing
16915 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16916 change in days weeks, months, years.
16917 With a single plus or minus, the date is relative to today. With a double
16918 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16919 +4d --> four days from today
16920 +4 --> same as above
16921 +2w --> two weeks from today
16922 ++5 --> five days from default date
16924 The function understands only English month and weekday abbreviations.
16926 While prompting, a calendar is popped up - you can also select the
16927 date with the mouse (button 1). The calendar shows a period of three
16928 months. To scroll it to other months, use the keys `>' and `<'.
16929 If you don't like the calendar, turn it off with
16930 (setq org-read-date-popup-calendar nil)
16932 With optional argument TO-TIME, the date will immediately be converted
16933 to an internal time.
16934 With an optional argument WITH-TIME, the prompt will suggest to
16935 also insert a time. Note that when WITH-TIME is not set, you can
16936 still enter a time, and this function will inform the calling routine
16937 about this change. The calling routine may then choose to change the
16938 format used to insert the time stamp into the buffer to include the time.
16939 With optional argument FROM-STRING, read from this string instead from
16940 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16941 the time/date that is used for everything that is not specified by the
16942 user."
16943 (require 'parse-time)
16944 (let* ((org-with-time with-time)
16945 (org-time-stamp-rounding-minutes
16946 (if (equal org-with-time '(16))
16947 '(0 0)
16948 org-time-stamp-rounding-minutes))
16949 (org-dcst org-display-custom-times)
16950 (ct (org-current-time))
16951 (org-def (or org-overriding-default-time default-time ct))
16952 (org-defdecode (decode-time org-def))
16953 (cur-frame (selected-frame))
16954 (mouse-autoselect-window nil) ; Don't let the mouse jump
16955 (calendar-setup
16956 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16957 (calendar-move-hook nil)
16958 (calendar-view-diary-initially-flag nil)
16959 (calendar-view-holidays-initially-flag nil)
16960 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16961 ;; Rationalize `org-def' and `org-defdecode', if required.
16962 (when (< (nth 2 org-defdecode) org-extend-today-until)
16963 (setf (nth 2 org-defdecode) -1)
16964 (setf (nth 1 org-defdecode) 59)
16965 (setq org-def (apply #'encode-time org-defdecode))
16966 (setq org-defdecode (decode-time org-def)))
16967 (let* ((timestr (format-time-string
16968 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16969 org-def))
16970 (prompt (concat (if prompt (concat prompt " ") "")
16971 (format "Date+time [%s]: " timestr))))
16972 (cond
16973 (from-string (setq ans from-string))
16974 (org-read-date-popup-calendar
16975 (save-excursion
16976 (save-window-excursion
16977 (calendar)
16978 (when (eq calendar-setup 'calendar-only)
16979 (setq cal-frame
16980 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16981 (select-frame cal-frame))
16982 (org-eval-in-calendar '(setq cursor-type nil) t)
16983 (unwind-protect
16984 (progn
16985 (calendar-forward-day (- (time-to-days org-def)
16986 (calendar-absolute-from-gregorian
16987 (calendar-current-date))))
16988 (org-eval-in-calendar nil t)
16989 (let* ((old-map (current-local-map))
16990 (map (copy-keymap calendar-mode-map))
16991 (minibuffer-local-map
16992 (copy-keymap org-read-date-minibuffer-local-map)))
16993 (org-defkey map (kbd "RET") 'org-calendar-select)
16994 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16995 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16996 (unwind-protect
16997 (progn
16998 (use-local-map map)
16999 (setq org-read-date-inactive inactive)
17000 (add-hook 'post-command-hook 'org-read-date-display)
17001 (setq org-ans0
17002 (read-string prompt
17003 default-input
17004 'org-read-date-history
17005 nil))
17006 ;; org-ans0: from prompt
17007 ;; org-ans1: from mouse click
17008 ;; org-ans2: from calendar motion
17009 (setq ans
17010 (concat org-ans0 " " (or org-ans1 org-ans2))))
17011 (remove-hook 'post-command-hook 'org-read-date-display)
17012 (use-local-map old-map)
17013 (when org-read-date-overlay
17014 (delete-overlay org-read-date-overlay)
17015 (setq org-read-date-overlay nil)))))
17016 (bury-buffer "*Calendar*")
17017 (when cal-frame
17018 (delete-frame cal-frame)
17019 (select-frame-set-input-focus cur-frame))))))
17021 (t ; Naked prompt only
17022 (unwind-protect
17023 (setq ans (read-string prompt default-input
17024 'org-read-date-history timestr))
17025 (when org-read-date-overlay
17026 (delete-overlay org-read-date-overlay)
17027 (setq org-read-date-overlay nil))))))
17029 (setq final (org-read-date-analyze ans org-def org-defdecode))
17031 (when org-read-date-analyze-forced-year
17032 (message "Year was forced into %s"
17033 (if org-read-date-force-compatible-dates
17034 "compatible range (1970-2037)"
17035 "range representable on this machine"))
17036 (ding))
17038 ;; One round trip to get rid of 34th of August and stuff like that....
17039 (setq final (decode-time (apply 'encode-time final)))
17041 (setq org-read-date-final-answer ans)
17043 (if to-time
17044 (apply 'encode-time final)
17045 (if (and (boundp 'org-time-was-given) org-time-was-given)
17046 (format "%04d-%02d-%02d %02d:%02d"
17047 (nth 5 final) (nth 4 final) (nth 3 final)
17048 (nth 2 final) (nth 1 final))
17049 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17051 (defun org-read-date-display ()
17052 "Display the current date prompt interpretation in the minibuffer."
17053 (when org-read-date-display-live
17054 (when org-read-date-overlay
17055 (delete-overlay org-read-date-overlay))
17056 (when (minibufferp (current-buffer))
17057 (save-excursion
17058 (end-of-line 1)
17059 (while (not (equal (buffer-substring
17060 (max (point-min) (- (point) 4)) (point))
17061 " "))
17062 (insert " ")))
17063 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17064 " " (or org-ans1 org-ans2)))
17065 (org-end-time-was-given nil)
17066 (f (org-read-date-analyze ans org-def org-defdecode))
17067 (fmts (if org-dcst
17068 org-time-stamp-custom-formats
17069 org-time-stamp-formats))
17070 (fmt (if (or org-with-time
17071 (and (boundp 'org-time-was-given) org-time-was-given))
17072 (cdr fmts)
17073 (car fmts)))
17074 (txt (format-time-string fmt (apply 'encode-time f)))
17075 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17076 (txt (concat "=> " txt)))
17077 (when (and org-end-time-was-given
17078 (string-match org-plain-time-of-day-regexp txt))
17079 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17080 org-end-time-was-given
17081 (substring txt (match-end 0)))))
17082 (when org-read-date-analyze-futurep
17083 (setq txt (concat txt " (=>F)")))
17084 (setq org-read-date-overlay
17085 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17086 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17088 (defun org-read-date-analyze (ans def defdecode)
17089 "Analyze the combined answer of the date prompt."
17090 ;; FIXME: cleanup and comment
17091 ;; Pass `current-time' result to `decode-time' (instead of calling
17092 ;; without arguments) so that only `current-time' has to be
17093 ;; overriden in tests.
17094 (let ((org-def def)
17095 (org-defdecode defdecode)
17096 (nowdecode (decode-time (current-time)))
17097 delta deltan deltaw deltadef year month day
17098 hour minute second wday pm h2 m2 tl wday1
17099 iso-year iso-weekday iso-week iso-date futurep kill-year)
17100 (setq org-read-date-analyze-futurep nil
17101 org-read-date-analyze-forced-year nil)
17102 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17103 (setq ans "+0"))
17105 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17106 (setq ans (replace-match "" t t ans)
17107 deltan (car delta)
17108 deltaw (nth 1 delta)
17109 deltadef (nth 2 delta)))
17111 ;; Check if there is an iso week date in there. If yes, store the
17112 ;; info and postpone interpreting it until the rest of the parsing
17113 ;; is done.
17114 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17115 (setq iso-year (when (match-end 1)
17116 (org-small-year-to-year
17117 (string-to-number (match-string 1 ans))))
17118 iso-weekday (when (match-end 3)
17119 (string-to-number (match-string 3 ans)))
17120 iso-week (string-to-number (match-string 2 ans)))
17121 (setq ans (replace-match "" t t ans)))
17123 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17124 (when (string-match
17125 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17126 (setq year (if (match-end 2)
17127 (string-to-number (match-string 2 ans))
17128 (progn (setq kill-year t)
17129 (string-to-number (format-time-string "%Y"))))
17130 month (string-to-number (match-string 3 ans))
17131 day (string-to-number (match-string 4 ans)))
17132 (setq year (org-small-year-to-year year))
17133 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17134 t nil ans)))
17136 ;; Help matching dotted european dates
17137 (when (string-match
17138 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17139 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17140 (setq kill-year t)
17141 (string-to-number (format-time-string "%Y")))
17142 day (string-to-number (match-string 1 ans))
17143 month (string-to-number (match-string 2 ans))
17144 ans (replace-match (format "%04d-%02d-%02d" year month day)
17145 t nil ans)))
17147 ;; Help matching american dates, like 5/30 or 5/30/7
17148 (when (string-match
17149 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17150 (setq year (if (match-end 4)
17151 (string-to-number (match-string 4 ans))
17152 (progn (setq kill-year t)
17153 (string-to-number (format-time-string "%Y"))))
17154 month (string-to-number (match-string 1 ans))
17155 day (string-to-number (match-string 2 ans)))
17156 (setq year (org-small-year-to-year year))
17157 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17158 t nil ans)))
17159 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17160 ;; If there is a time with am/pm, and *no* time without it, we convert
17161 ;; so that matching will be successful.
17162 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17163 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17164 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17165 (setq hour (string-to-number (match-string 1 ans))
17166 minute (if (match-end 3)
17167 (string-to-number (match-string 3 ans))
17169 pm (equal ?p
17170 (string-to-char (downcase (match-string 4 ans)))))
17171 (if (and (= hour 12) (not pm))
17172 (setq hour 0)
17173 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17174 (setq ans (replace-match (format "%02d:%02d" hour minute)
17175 t t ans))))
17177 ;; Check if a time range is given as a duration
17178 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17179 (setq hour (string-to-number (match-string 1 ans))
17180 h2 (+ hour (string-to-number (match-string 3 ans)))
17181 minute (string-to-number (match-string 2 ans))
17182 m2 (+ minute (if (match-end 5) (string-to-number
17183 (match-string 5 ans))0)))
17184 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17185 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17186 t t ans)))
17188 ;; Check if there is a time range
17189 (when (boundp 'org-end-time-was-given)
17190 (setq org-time-was-given nil)
17191 (when (and (string-match org-plain-time-of-day-regexp ans)
17192 (match-end 8))
17193 (setq org-end-time-was-given (match-string 8 ans))
17194 (setq ans (concat (substring ans 0 (match-beginning 7))
17195 (substring ans (match-end 7))))))
17197 (setq tl (parse-time-string ans)
17198 day (or (nth 3 tl) (nth 3 org-defdecode))
17199 month
17200 (cond ((nth 4 tl))
17201 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17202 ;; Day was specified. Make sure DAY+MONTH
17203 ;; combination happens in the future.
17204 ((nth 3 tl)
17205 (setq futurep t)
17206 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17207 (nth 4 nowdecode)))
17208 (t (nth 4 org-defdecode)))
17209 year
17210 (cond ((and (not kill-year) (nth 5 tl)))
17211 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17212 ;; Month was guessed in the future and is at least
17213 ;; equal to NOWDECODE's. Fix year accordingly.
17214 (futurep
17215 (if (or (> month (nth 4 nowdecode))
17216 (>= day (nth 3 nowdecode)))
17217 (nth 5 nowdecode)
17218 (1+ (nth 5 nowdecode))))
17219 ;; Month was specified. Make sure MONTH+YEAR
17220 ;; combination happens in the future.
17221 ((nth 4 tl)
17222 (setq futurep t)
17223 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17224 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17225 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17226 (t (nth 5 nowdecode))))
17227 (t (nth 5 org-defdecode)))
17228 hour (or (nth 2 tl) (nth 2 org-defdecode))
17229 minute (or (nth 1 tl) (nth 1 org-defdecode))
17230 second (or (nth 0 tl) 0)
17231 wday (nth 6 tl))
17233 (when (and (eq org-read-date-prefer-future 'time)
17234 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17235 (equal day (nth 3 nowdecode))
17236 (equal month (nth 4 nowdecode))
17237 (equal year (nth 5 nowdecode))
17238 (nth 2 tl)
17239 (or (< (nth 2 tl) (nth 2 nowdecode))
17240 (and (= (nth 2 tl) (nth 2 nowdecode))
17241 (nth 1 tl)
17242 (< (nth 1 tl) (nth 1 nowdecode)))))
17243 (setq day (1+ day)
17244 futurep t))
17246 ;; Special date definitions below
17247 (cond
17248 (iso-week
17249 ;; There was an iso week
17250 (require 'cal-iso)
17251 (setq futurep nil)
17252 (setq year (or iso-year year)
17253 day (or iso-weekday wday 1)
17254 wday nil ; to make sure that the trigger below does not match
17255 iso-date (calendar-gregorian-from-absolute
17256 (calendar-iso-to-absolute
17257 (list iso-week day year))))
17258 ; FIXME: Should we also push ISO weeks into the future?
17259 ; (when (and org-read-date-prefer-future
17260 ; (not iso-year)
17261 ; (< (calendar-absolute-from-gregorian iso-date)
17262 ; (time-to-days (current-time))))
17263 ; (setq year (1+ year)
17264 ; iso-date (calendar-gregorian-from-absolute
17265 ; (calendar-iso-to-absolute
17266 ; (list iso-week day year)))))
17267 (setq month (car iso-date)
17268 year (nth 2 iso-date)
17269 day (nth 1 iso-date)))
17270 (deltan
17271 (setq futurep nil)
17272 (unless deltadef
17273 ;; Pass `current-time' result to `decode-time' (instead of
17274 ;; calling without arguments) so that only `current-time' has
17275 ;; to be overriden in tests.
17276 (let ((now (decode-time (current-time))))
17277 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17278 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17279 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17280 ((equal deltaw "m") (setq month (+ month deltan)))
17281 ((equal deltaw "y") (setq year (+ year deltan)))))
17282 ((and wday (not (nth 3 tl)))
17283 ;; Weekday was given, but no day, so pick that day in the week
17284 ;; on or after the derived date.
17285 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17286 (unless (equal wday wday1)
17287 (setq day (+ day (% (- wday wday1 -7) 7))))))
17288 (when (and (boundp 'org-time-was-given)
17289 (nth 2 tl))
17290 (setq org-time-was-given t))
17291 (when (< year 100) (setq year (+ 2000 year)))
17292 ;; Check of the date is representable
17293 (if org-read-date-force-compatible-dates
17294 (progn
17295 (when (< year 1970)
17296 (setq year 1970 org-read-date-analyze-forced-year t))
17297 (when (> year 2037)
17298 (setq year 2037 org-read-date-analyze-forced-year t)))
17299 (condition-case nil
17300 (ignore (encode-time second minute hour day month year))
17301 (error
17302 (setq year (nth 5 org-defdecode))
17303 (setq org-read-date-analyze-forced-year t))))
17304 (setq org-read-date-analyze-futurep futurep)
17305 (list second minute hour day month year)))
17307 (defvar parse-time-weekdays)
17308 (defun org-read-date-get-relative (s today default)
17309 "Check string S for special relative date string.
17310 TODAY and DEFAULT are internal times, for today and for a default.
17311 Return shift list (N what def-flag)
17312 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17313 N is the number of WHATs to shift.
17314 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17315 the DEFAULT date rather than TODAY."
17316 (require 'parse-time)
17317 (when (and
17318 (string-match
17319 (concat
17320 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17321 "\\([0-9]+\\)?"
17322 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17323 "\\([ \t]\\|$\\)") s)
17324 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17325 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17326 (string-to-char (substring (match-string 1 s) -1))
17327 ?+))
17328 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17329 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17330 (what (if (match-end 3) (match-string 3 s) "d"))
17331 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17332 (date (if rel default today))
17333 (wday (nth 6 (decode-time date)))
17334 delta)
17335 (if wday1
17336 (progn
17337 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17338 (when (= delta 0) (setq delta 7))
17339 (when (= dir ?-)
17340 (setq delta (- delta 7))
17341 (when (= delta 0) (setq delta -7)))
17342 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17343 (list delta "d" rel))
17344 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17346 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17347 "Turn a user-specified date into the internal representation.
17348 The internal representation needed by the calendar is (month day year).
17349 This is a wrapper to handle the brain-dead convention in calendar that
17350 user function argument order change dependent on argument order."
17351 (pcase calendar-date-style
17352 (`american (list arg1 arg2 arg3))
17353 (`european (list arg2 arg1 arg3))
17354 (`iso (list arg2 arg3 arg1))))
17356 (defun org-eval-in-calendar (form &optional keepdate)
17357 "Eval FORM in the calendar window and return to current window.
17358 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17359 (let ((sf (selected-frame))
17360 (sw (selected-window)))
17361 (select-window (get-buffer-window "*Calendar*" t))
17362 (eval form)
17363 (when (and (not keepdate) (calendar-cursor-to-date))
17364 (let* ((date (calendar-cursor-to-date))
17365 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17366 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17367 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17368 (select-window sw)
17369 (select-frame-set-input-focus sf)))
17371 (defun org-calendar-select ()
17372 "Return to `org-read-date' with the date currently selected.
17373 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17374 (interactive)
17375 (when (calendar-cursor-to-date)
17376 (let* ((date (calendar-cursor-to-date))
17377 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17378 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17379 (when (active-minibuffer-window) (exit-minibuffer))))
17381 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17382 "Insert a date stamp for the date given by the internal TIME.
17383 See `format-time-string' for the format of TIME.
17384 WITH-HM means use the stamp format that includes the time of the day.
17385 INACTIVE means use square brackets instead of angular ones, so that the
17386 stamp will not contribute to the agenda.
17387 PRE and POST are optional strings to be inserted before and after the
17388 stamp.
17389 The command returns the inserted time stamp."
17390 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17391 stamp)
17392 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17393 (insert-before-markers (or pre ""))
17394 (when (listp extra)
17395 (setq extra (car extra))
17396 (if (and (stringp extra)
17397 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17398 (setq extra (format "-%02d:%02d"
17399 (string-to-number (match-string 1 extra))
17400 (string-to-number (match-string 2 extra))))
17401 (setq extra nil)))
17402 (when extra
17403 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17404 (insert-before-markers (setq stamp (format-time-string fmt time)))
17405 (insert-before-markers (or post ""))
17406 (setq org-last-inserted-timestamp stamp)))
17408 (defun org-toggle-time-stamp-overlays ()
17409 "Toggle the use of custom time stamp formats."
17410 (interactive)
17411 (setq org-display-custom-times (not org-display-custom-times))
17412 (unless org-display-custom-times
17413 (let ((p (point-min)) (bmp (buffer-modified-p)))
17414 (while (setq p (next-single-property-change p 'display))
17415 (when (and (get-text-property p 'display)
17416 (eq (get-text-property p 'face) 'org-date))
17417 (remove-text-properties
17418 p (setq p (next-single-property-change p 'display))
17419 '(display t))))
17420 (set-buffer-modified-p bmp)))
17421 (org-restart-font-lock)
17422 (setq org-table-may-need-update t)
17423 (if org-display-custom-times
17424 (message "Time stamps are overlaid with custom format")
17425 (message "Time stamp overlays removed")))
17427 (defun org-display-custom-time (beg end)
17428 "Overlay modified time stamp format over timestamp between BEG and END."
17429 (let* ((ts (buffer-substring beg end))
17430 t1 w1 with-hm tf time str w2 (off 0))
17431 (save-match-data
17432 (setq t1 (org-parse-time-string ts t))
17433 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17434 (setq off (- (match-end 0) (match-beginning 0)))))
17435 (setq end (- end off))
17436 (setq w1 (- end beg)
17437 with-hm (and (nth 1 t1) (nth 2 t1))
17438 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17439 time (org-fix-decoded-time t1)
17440 str (org-add-props
17441 (format-time-string
17442 (substring tf 1 -1) (apply 'encode-time time))
17443 nil 'mouse-face 'highlight)
17444 w2 (length str))
17445 (unless (= w2 w1)
17446 (add-text-properties (1+ beg) (+ 2 beg)
17447 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17448 (put-text-property beg end 'display str)))
17450 (defun org-fix-decoded-time (time)
17451 "Set 0 instead of nil for the first 6 elements of time.
17452 Don't touch the rest."
17453 (let ((n 0))
17454 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17456 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17457 "Difference between TIMESTAMP-STRING and now in days.
17458 If SECONDS is non-nil, return the difference in seconds."
17459 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17460 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17461 (funcall fdiff (current-time)))))
17463 (defun org-deadline-close-p (timestamp-string &optional ndays)
17464 "Is the time in TIMESTAMP-STRING close to the current date?"
17465 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17466 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17467 (not (org-entry-is-done-p))))
17469 (defun org-get-wdays (ts &optional delay zero-delay)
17470 "Get the deadline lead time appropriate for timestring TS.
17471 When DELAY is non-nil, get the delay time for scheduled items
17472 instead of the deadline lead time. When ZERO-DELAY is non-nil
17473 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17474 don't try to find the delay cookie in the scheduled timestamp."
17475 (let ((tv (if delay org-scheduled-delay-days
17476 org-deadline-warning-days)))
17477 (cond
17478 ((or (and delay (< tv 0))
17479 (and delay zero-delay (<= tv 0))
17480 (and (not delay) (<= tv 0)))
17481 ;; Enforce this value no matter what
17482 (- tv))
17483 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17484 ;; lead time is specified.
17485 (floor (* (string-to-number (match-string 1 ts))
17486 (cdr (assoc (match-string 2 ts)
17487 '(("d" . 1) ("w" . 7)
17488 ("m" . 30.4) ("y" . 365.25)
17489 ("h" . 0.041667)))))))
17490 ;; go for the default.
17491 (t tv))))
17493 (defun org-calendar-select-mouse (ev)
17494 "Return to `org-read-date' with the date currently selected.
17495 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17496 (interactive "e")
17497 (mouse-set-point ev)
17498 (when (calendar-cursor-to-date)
17499 (let* ((date (calendar-cursor-to-date))
17500 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17501 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17502 (when (active-minibuffer-window) (exit-minibuffer))))
17504 (defun org-check-deadlines (ndays)
17505 "Check if there are any deadlines due or past due.
17506 A deadline is considered due if it happens within `org-deadline-warning-days'
17507 days from today's date. If the deadline appears in an entry marked DONE,
17508 it is not shown. A numeric prefix argument NDAYS can be used to test that
17509 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17510 are shown."
17511 (interactive "P")
17512 (let* ((org-warn-days
17513 (cond
17514 ((equal ndays '(4)) 100000)
17515 (ndays (prefix-numeric-value ndays))
17516 (t (abs org-deadline-warning-days))))
17517 (case-fold-search nil)
17518 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17519 (callback
17520 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17521 (message "%d deadlines past-due or due within %d days"
17522 (org-occur regexp nil callback)
17523 org-warn-days)))
17525 (defsubst org-re-timestamp (type)
17526 "Return a regexp for timestamp TYPE.
17527 Allowed values for TYPE are:
17529 all: all timestamps
17530 active: only active timestamps (<...>)
17531 inactive: only inactive timestamps ([...])
17532 scheduled: only scheduled timestamps
17533 deadline: only deadline timestamps
17534 closed: only closed time-stamps
17536 When TYPE is nil, fall back on returning a regexp that matches
17537 both scheduled and deadline timestamps."
17538 (cl-case type
17539 (all org-ts-regexp-both)
17540 (active org-ts-regexp)
17541 (inactive org-ts-regexp-inactive)
17542 (scheduled org-scheduled-time-regexp)
17543 (deadline org-deadline-time-regexp)
17544 (closed org-closed-time-regexp)
17545 (otherwise
17546 (concat "\\<"
17547 (regexp-opt (list org-deadline-string org-scheduled-string))
17548 " *<\\([^>]+\\)>"))))
17550 (defun org-check-before-date (d)
17551 "Check if there are deadlines or scheduled entries before date D."
17552 (interactive (list (org-read-date)))
17553 (let* ((case-fold-search nil)
17554 (regexp (org-re-timestamp org-ts-type))
17555 (ts-type org-ts-type)
17556 (callback
17557 (lambda ()
17558 (let ((match (match-string 1)))
17559 (and (if (memq ts-type '(active inactive all))
17560 (eq (org-element-type (save-excursion
17561 (backward-char)
17562 (org-element-context)))
17563 'timestamp)
17564 (org-at-planning-p))
17565 (time-less-p
17566 (org-time-string-to-time match)
17567 (org-time-string-to-time d)))))))
17568 (message "%d entries before %s"
17569 (org-occur regexp nil callback)
17570 d)))
17572 (defun org-check-after-date (d)
17573 "Check if there are deadlines or scheduled entries after date D."
17574 (interactive (list (org-read-date)))
17575 (let* ((case-fold-search nil)
17576 (regexp (org-re-timestamp org-ts-type))
17577 (ts-type org-ts-type)
17578 (callback
17579 (lambda ()
17580 (let ((match (match-string 1)))
17581 (and (if (memq ts-type '(active inactive all))
17582 (eq (org-element-type (save-excursion
17583 (backward-char)
17584 (org-element-context)))
17585 'timestamp)
17586 (org-at-planning-p))
17587 (not (time-less-p
17588 (org-time-string-to-time match)
17589 (org-time-string-to-time d))))))))
17590 (message "%d entries after %s"
17591 (org-occur regexp nil callback)
17592 d)))
17594 (defun org-check-dates-range (start-date end-date)
17595 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17596 (interactive (list (org-read-date nil nil nil "Range starts")
17597 (org-read-date nil nil nil "Range end")))
17598 (let ((case-fold-search nil)
17599 (regexp (org-re-timestamp org-ts-type))
17600 (callback
17601 (let ((type org-ts-type))
17602 (lambda ()
17603 (let ((match (match-string 1)))
17604 (and
17605 (if (memq type '(active inactive all))
17606 (eq (org-element-type (save-excursion
17607 (backward-char)
17608 (org-element-context)))
17609 'timestamp)
17610 (org-at-planning-p))
17611 (not (time-less-p
17612 (org-time-string-to-time match)
17613 (org-time-string-to-time start-date)))
17614 (time-less-p
17615 (org-time-string-to-time match)
17616 (org-time-string-to-time end-date))))))))
17617 (message "%d entries between %s and %s"
17618 (org-occur regexp nil callback) start-date end-date)))
17620 (defun org-evaluate-time-range (&optional to-buffer)
17621 "Evaluate a time range by computing the difference between start and end.
17622 Normally the result is just printed in the echo area, but with prefix arg
17623 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17624 If the time range is actually in a table, the result is inserted into the
17625 next column.
17626 For time difference computation, a year is assumed to be exactly 365
17627 days in order to avoid rounding problems."
17628 (interactive "P")
17630 (org-clock-update-time-maybe)
17631 (save-excursion
17632 (unless (org-at-date-range-p t)
17633 (goto-char (point-at-bol))
17634 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17635 (unless (org-at-date-range-p t)
17636 (user-error "Not at a time-stamp range, and none found in current line")))
17637 (let* ((ts1 (match-string 1))
17638 (ts2 (match-string 2))
17639 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17640 (match-end (match-end 0))
17641 (time1 (org-time-string-to-time ts1))
17642 (time2 (org-time-string-to-time ts2))
17643 (t1 (float-time time1))
17644 (t2 (float-time time2))
17645 (diff (abs (- t2 t1)))
17646 (negative (< (- t2 t1) 0))
17647 ;; (ys (floor (* 365 24 60 60)))
17648 (ds (* 24 60 60))
17649 (hs (* 60 60))
17650 (fy "%dy %dd %02d:%02d")
17651 (fy1 "%dy %dd")
17652 (fd "%dd %02d:%02d")
17653 (fd1 "%dd")
17654 (fh "%02d:%02d")
17655 y d h m align)
17656 (if havetime
17657 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17659 d (floor (/ diff ds)) diff (mod diff ds)
17660 h (floor (/ diff hs)) diff (mod diff hs)
17661 m (floor (/ diff 60)))
17662 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17664 d (floor (+ (/ diff ds) 0.5))
17665 h 0 m 0))
17666 (if (not to-buffer)
17667 (message "%s" (org-make-tdiff-string y d h m))
17668 (if (org-at-table-p)
17669 (progn
17670 (goto-char match-end)
17671 (setq align t)
17672 (and (looking-at " *|") (goto-char (match-end 0))))
17673 (goto-char match-end))
17674 (when (looking-at
17675 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17676 (replace-match ""))
17677 (when negative (insert " -"))
17678 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17679 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17680 (insert " " (format fh h m))))
17681 (when align (org-table-align))
17682 (message "Time difference inserted")))))
17684 (defun org-make-tdiff-string (y d h m)
17685 (let ((fmt "")
17686 (l nil))
17687 (when (> y 0)
17688 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17689 (push y l))
17690 (when (> d 0)
17691 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17692 (push d l))
17693 (when (> h 0)
17694 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17695 (push h l))
17696 (when (> m 0)
17697 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17698 (push m l))
17699 (apply 'format fmt (nreverse l))))
17701 (defun org-time-string-to-time (s &optional buffer pos)
17702 "Convert a timestamp string into internal time."
17703 (condition-case errdata
17704 (apply 'encode-time (org-parse-time-string s))
17705 (error (error "Bad timestamp `%s'%s\nError was: %s"
17706 s (if (not (and buffer pos))
17708 (format-message " at %d in buffer `%s'" pos buffer))
17709 (cdr errdata)))))
17711 (defun org-time-string-to-seconds (s)
17712 "Convert a timestamp string to a number of seconds."
17713 (float-time (org-time-string-to-time s)))
17715 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17717 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17718 "Convert time stamp S to an absolute day number.
17720 If DAYNR in non-nil, and there is a specifier for a cyclic time
17721 stamp, get the closest date to DAYNR. If PREFER is
17722 `past' (respectively `future') return a date past (respectively
17723 after) or equal to DAYNR.
17725 POS is the location of time stamp S, as a buffer position in
17726 BUFFER.
17728 Diary sexp timestamps are matched against DAYNR, when non-nil.
17729 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17730 signalled."
17731 (cond
17732 ((string-match "\\`%%\\((.*)\\)" s)
17733 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17734 ;; only able to match individual dates. If it fails, raise an
17735 ;; error.
17736 (if (and daynr
17737 (org-diary-sexp-entry
17738 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17739 daynr
17740 (signal 'org-diary-sexp-no-match (list s))))
17741 (daynr (org-closest-date s daynr prefer))
17742 (t (time-to-days
17743 (condition-case errdata
17744 (apply #'encode-time (org-parse-time-string s))
17745 (error (error "Bad timestamp `%s'%s\nError was: %s"
17747 (if (not (and buffer pos)) ""
17748 (format-message " at %d in buffer `%s'" pos buffer))
17749 (cdr errdata))))))))
17751 (defun org-days-to-iso-week (days)
17752 "Return the iso week number."
17753 (require 'cal-iso)
17754 (car (calendar-iso-from-absolute days)))
17756 (defun org-small-year-to-year (year)
17757 "Convert 2-digit years into 4-digit years.
17758 YEAR is expanded into one of the 30 next years, if possible, or
17759 into a past one. Any year larger than 99 is returned unchanged."
17760 (if (>= year 100) year
17761 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17762 (century (/ current 100))
17763 (offset (- year (% current 100))))
17764 (cond ((> offset 30) (+ (* (1- century) 100) year))
17765 ((> offset -70) (+ (* century 100) year))
17766 (t (+ (* (1+ century) 100) year))))))
17768 (defun org-time-from-absolute (d)
17769 "Return the time corresponding to date D.
17770 D may be an absolute day number, or a calendar-type list (month day year)."
17771 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17772 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17774 (defvar org-agenda-current-date)
17775 (defun org-calendar-holiday ()
17776 "List of holidays, for Diary display in Org mode."
17777 (require 'holidays)
17778 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17779 (and hl (mapconcat #'identity hl "; "))))
17781 (defun org-diary-sexp-entry (sexp entry d)
17782 "Process a SEXP diary ENTRY for date D."
17783 (require 'diary-lib)
17784 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17785 ;; dynamically.
17786 (let* ((sexp `(let ((entry ,entry)
17787 (date ',d))
17788 ,(car (read-from-string sexp))))
17789 (result (if calendar-debug-sexp (eval sexp)
17790 (condition-case nil
17791 (eval sexp)
17792 (error
17793 (beep)
17794 (message "Bad sexp at line %d in %s: %s"
17795 (org-current-line)
17796 (buffer-file-name) sexp)
17797 (sleep-for 2))))))
17798 (cond ((stringp result) (split-string result "; "))
17799 ((and (consp result)
17800 (not (consp (cdr result)))
17801 (stringp (cdr result))) (cdr result))
17802 ((and (consp result)
17803 (stringp (car result))) result)
17804 (result entry))))
17806 (defun org-diary-to-ical-string (frombuf)
17807 "Get iCalendar entries from diary entries in buffer FROMBUF.
17808 This uses the icalendar.el library."
17809 (let* ((tmpdir temporary-file-directory)
17810 (tmpfile (make-temp-name
17811 (expand-file-name "orgics" tmpdir)))
17812 buf rtn b e)
17813 (with-current-buffer frombuf
17814 (icalendar-export-region (point-min) (point-max) tmpfile)
17815 (setq buf (find-buffer-visiting tmpfile))
17816 (set-buffer buf)
17817 (goto-char (point-min))
17818 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17819 (setq b (match-beginning 0)))
17820 (goto-char (point-max))
17821 (when (re-search-backward "^END:VEVENT" nil t)
17822 (setq e (match-end 0)))
17823 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17824 (kill-buffer buf)
17825 (delete-file tmpfile)
17826 rtn))
17828 (defun org-closest-date (start current prefer)
17829 "Return closest date to CURRENT starting from START.
17831 CURRENT and START are both time stamps.
17833 When PREFER is `past', return a date that is either CURRENT or
17834 past. When PREFER is `future', return a date that is either
17835 CURRENT or future.
17837 Only time stamps with a repeater are modified. Any other time
17838 stamp stay unchanged. In any case, return value is an absolute
17839 day number."
17840 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17841 ;; No repeater. Do not shift time stamp.
17842 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17843 (let ((value (string-to-number (match-string 1 start)))
17844 (type (match-string 2 start)))
17845 (if (= 0 value)
17846 ;; Repeater with a 0-value is considered as void.
17847 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17848 (let* ((base (org-date-to-gregorian start))
17849 (target (org-date-to-gregorian current))
17850 (sday (calendar-absolute-from-gregorian base))
17851 (cday (calendar-absolute-from-gregorian target))
17852 n1 n2)
17853 ;; If START is already past CURRENT, just return START.
17854 (if (<= cday sday) sday
17855 ;; Compute closest date before (N1) and closest date past
17856 ;; (N2) CURRENT.
17857 (pcase type
17858 ("h"
17859 (let ((missing-hours
17860 (mod (+ (- (* 24 (- cday sday))
17861 (nth 2 (org-parse-time-string start)))
17862 org-extend-today-until)
17863 value)))
17864 (setf n1 (if (= missing-hours 0) cday
17865 (- cday (1+ (/ missing-hours 24)))))
17866 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17867 ((or "d" "w")
17868 (let ((value (if (equal type "w") (* 7 value) value)))
17869 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17870 (setf n2 (+ n1 value))))
17871 ("m"
17872 (let* ((add-months
17873 (lambda (d n)
17874 ;; Add N months to gregorian date D, i.e.,
17875 ;; a list (MONTH DAY YEAR). Return a valid
17876 ;; gregorian date.
17877 (let ((m (+ (nth 0 d) n)))
17878 (list (mod m 12)
17879 (nth 1 d)
17880 (+ (/ m 12) (nth 2 d))))))
17881 (months ; Complete months to TARGET.
17882 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17883 (- (nth 0 target) (nth 0 base))
17884 ;; If START's day is greater than
17885 ;; TARGET's, remove incomplete month.
17886 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17887 value)
17888 value))
17889 (before (funcall add-months base months)))
17890 (setf n1 (calendar-absolute-from-gregorian before))
17891 (setf n2
17892 (calendar-absolute-from-gregorian
17893 (funcall add-months before value)))))
17895 (let* ((d (nth 1 base))
17896 (m (nth 0 base))
17897 (y (nth 2 base))
17898 (years ; Complete years to TARGET.
17899 (* (/ (- (nth 2 target)
17901 ;; If START's month and day are
17902 ;; greater than TARGET's, remove
17903 ;; incomplete year.
17904 (if (or (> (nth 0 target) m)
17905 (and (= (nth 0 target) m)
17906 (> (nth 1 target) d)))
17909 value)
17910 value))
17911 (before (list m d (+ y years))))
17912 (setf n1 (calendar-absolute-from-gregorian before))
17913 (setf n2 (calendar-absolute-from-gregorian
17914 (list m d (+ (nth 2 before) value)))))))
17915 ;; Handle PREFER parameter, if any.
17916 (cond
17917 ((eq prefer 'past) (if (= cday n2) n2 n1))
17918 ((eq prefer 'future) (if (= cday n1) n1 n2))
17919 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17921 (defun org-date-to-gregorian (d)
17922 "Turn any specification of date D into a Gregorian date for the calendar."
17923 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17924 ((and (listp d) (= (length d) 3)) d)
17925 ((stringp d)
17926 (let ((d (org-parse-time-string d)))
17927 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17928 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17930 (defun org-parse-time-string (s &optional nodefault)
17931 "Parse the standard Org time string.
17932 This should be a lot faster than the normal `parse-time-string'.
17933 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17934 hour and minute fields will be nil if not given."
17935 (cond ((string-match org-ts-regexp0 s)
17936 (list 0
17937 (when (or (match-beginning 8) (not nodefault))
17938 (string-to-number (or (match-string 8 s) "0")))
17939 (when (or (match-beginning 7) (not nodefault))
17940 (string-to-number (or (match-string 7 s) "0")))
17941 (string-to-number (match-string 4 s))
17942 (string-to-number (match-string 3 s))
17943 (string-to-number (match-string 2 s))
17944 nil nil nil))
17945 ((string-match "^<[^>]+>$" s)
17946 (decode-time (seconds-to-time (org-matcher-time s))))
17947 (t (error "Not a standard Org time string: %s" s))))
17949 (defun org-timestamp-up (&optional arg)
17950 "Increase the date item at the cursor by one.
17951 If the cursor is on the year, change the year. If it is on the month,
17952 the day or the time, change that.
17953 With prefix ARG, change by that many units."
17954 (interactive "p")
17955 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17957 (defun org-timestamp-down (&optional arg)
17958 "Decrease the date item at the cursor by one.
17959 If the cursor is on the year, change the year. If it is on the month,
17960 the day or the time, change that.
17961 With prefix ARG, change by that many units."
17962 (interactive "p")
17963 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17965 (defun org-timestamp-up-day (&optional arg)
17966 "Increase the date in the time stamp by one day.
17967 With prefix ARG, change that many days."
17968 (interactive "p")
17969 (if (and (not (org-at-timestamp-p t))
17970 (org-at-heading-p))
17971 (org-todo 'up)
17972 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17974 (defun org-timestamp-down-day (&optional arg)
17975 "Decrease the date in the time stamp by one day.
17976 With prefix ARG, change that many days."
17977 (interactive "p")
17978 (if (and (not (org-at-timestamp-p t))
17979 (org-at-heading-p))
17980 (org-todo 'down)
17981 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17983 (defun org-at-timestamp-p (&optional inactive-ok)
17984 "Non-nil if point is inside a timestamp.
17986 When optional argument INACTIVE-OK is non-nil, also consider
17987 inactive timestamps.
17989 When this function returns a non-nil value, match data is set
17990 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17991 INACTIVE-OK.
17993 Return the position of the point as a symbol among `bracket',
17994 `after', `year', `month', `hour', `minute', `day' or a number of
17995 character from the last know part of the time stamp.
17997 This function checks context and only return non-nil for valid
17998 time stamps. If you need to match anything looking like a time
17999 stamp, or if you are sure about the context, consider using
18000 `org-in-regexp', e.g.,
18002 (org-in-regexp org-ts-regexp)
18004 Unlike to `org-element-context', the function recognizes time
18005 stamps in properties drawers, planning lines and clocks."
18006 (interactive)
18007 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18008 (pos (point))
18009 (match
18010 (let ((boundaries (org-in-regexp tsr)))
18011 (save-match-data
18012 (cond ((null boundaries) nil)
18013 ((org-at-planning-p))
18014 ((org-at-property-p))
18015 ;; CLOCK lines only contain inactive time-stamps.
18016 ((and inactive-ok (org-at-clock-log-p)))
18018 (eq 'timestamp
18019 (save-excursion
18020 (when (= pos (cdr boundaries)) (forward-char -1))
18021 (org-element-type (org-element-context))))))))))
18022 (cond
18023 ((not match) nil)
18024 ((= pos (match-beginning 0)) 'bracket)
18025 ;; Distinguish location right before the closing bracket from
18026 ;; right after it.
18027 ((= pos (1- (match-end 0))) 'bracket)
18028 ((= pos (match-end 0)) 'after)
18029 ((org-pos-in-match-range pos 2) 'year)
18030 ((org-pos-in-match-range pos 3) 'month)
18031 ((org-pos-in-match-range pos 7) 'hour)
18032 ((org-pos-in-match-range pos 8) 'minute)
18033 ((or (org-pos-in-match-range pos 4)
18034 (org-pos-in-match-range pos 5)) 'day)
18035 ((and (> pos (or (match-end 8) (match-end 5)))
18036 (< pos (match-end 0)))
18037 (- pos (or (match-end 8) (match-end 5))))
18038 (t 'day))))
18040 (defun org-toggle-timestamp-type ()
18041 "Toggle the type (<active> or [inactive]) of a time stamp."
18042 (interactive)
18043 (when (org-at-timestamp-p t)
18044 (let ((beg (match-beginning 0)) (end (match-end 0))
18045 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18046 (save-excursion
18047 (goto-char beg)
18048 (while (re-search-forward "[][<>]" end t)
18049 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18050 t t)))
18051 (message "Timestamp is now %sactive"
18052 (if (equal (char-after beg) ?<) "" "in")))))
18054 (defun org-at-clock-log-p ()
18055 "Non-nil if point is on a clock log line."
18056 (and (org-match-line org-clock-line-re)
18057 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
18059 (defvar org-clock-history) ; defined in org-clock.el
18060 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18061 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18062 "Change the date in the time stamp at point.
18063 The date will be changed by N times WHAT. WHAT can be `day', `month',
18064 `year', `minute', `second'. If WHAT is not given, the cursor position
18065 in the timestamp determines what will be changed.
18066 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18067 (let ((origin (point))
18068 (timestamp? (org-at-timestamp-p t))
18069 origin-cat
18070 with-hm inactive
18071 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18072 extra rem
18073 ts time time0 fixnext clrgx)
18074 (unless timestamp? (user-error "Not at a timestamp"))
18075 (if (and (not what) (eq timestamp? 'bracket))
18076 (org-toggle-timestamp-type)
18077 ;; Point isn't on brackets. Remember the part of the time-stamp
18078 ;; the point was in. Indeed, size of time-stamps may change,
18079 ;; but point must be kept in the same category nonetheless.
18080 (setq origin-cat timestamp?)
18081 (when (and (not what) (not (eq timestamp? 'day))
18082 org-display-custom-times
18083 (get-text-property (point) 'display)
18084 (not (get-text-property (1- (point)) 'display)))
18085 (setq timestamp? 'day))
18086 (setq timestamp? (or what timestamp?)
18087 inactive (= (char-after (match-beginning 0)) ?\[)
18088 ts (match-string 0))
18089 (replace-match "")
18090 (when (string-match
18091 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18093 (setq extra (match-string 1 ts))
18094 (when suppress-tmp-delay
18095 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18096 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18097 (setq with-hm t))
18098 (setq time0 (org-parse-time-string ts))
18099 (when (and updown
18100 (eq timestamp? 'minute)
18101 (not current-prefix-arg))
18102 ;; This looks like s-up and s-down. Change by one rounding step.
18103 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18104 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18105 (setcar (cdr time0) (+ (nth 1 time0)
18106 (if (> n 0) (- rem) (- dm rem))))))
18107 (setq time
18108 (apply #'encode-time
18109 (or (car time0) 0)
18110 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18111 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18112 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18113 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18114 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18115 (nthcdr 6 time0)))
18116 (when (and (memq timestamp? '(hour minute))
18117 extra
18118 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18119 (setq extra (org-modify-ts-extra
18120 extra
18121 (if (eq timestamp? 'hour) 2 5)
18122 n dm)))
18123 (when (integerp timestamp?)
18124 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18125 (when (eq what 'calendar)
18126 (let ((cal-date (org-get-date-from-calendar)))
18127 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18128 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18129 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18130 (setcar time0 (or (car time0) 0))
18131 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18132 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18133 (setq time (apply 'encode-time time0))))
18134 ;; Insert the new time-stamp, and ensure point stays in the same
18135 ;; category as before (i.e. not after the last position in that
18136 ;; category).
18137 (let ((pos (point)))
18138 ;; Stay before inserted string. `save-excursion' is of no use.
18139 (setq org-last-changed-timestamp
18140 (org-insert-time-stamp time with-hm inactive nil nil extra))
18141 (goto-char pos))
18142 (save-match-data
18143 (looking-at org-ts-regexp3)
18144 (goto-char
18145 (pcase origin-cat
18146 ;; `day' category ends before `hour' if any, or at the end
18147 ;; of the day name.
18148 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18149 (`hour (min (match-end 7) origin))
18150 (`minute (min (1- (match-end 8)) origin))
18151 ((pred integerp) (min (1- (match-end 0)) origin))
18152 ;; Point was right after the time-stamp. However, the
18153 ;; time-stamp length might have changed, so refer to
18154 ;; (match-end 0) instead.
18155 (`after (match-end 0))
18156 ;; `year' and `month' have both fixed size: point couldn't
18157 ;; have moved into another part.
18158 (_ origin))))
18159 ;; Update clock if on a CLOCK line.
18160 (org-clock-update-time-maybe)
18161 ;; Maybe adjust the closest clock in `org-clock-history'
18162 (when org-clock-adjust-closest
18163 (if (not (and (org-at-clock-log-p)
18164 (< 1 (length (delq nil (mapcar 'marker-position
18165 org-clock-history))))))
18166 (message "No clock to adjust")
18167 (cond ((save-excursion ; fix previous clock?
18168 (re-search-backward org-ts-regexp0 nil t)
18169 (looking-back (concat org-clock-string " \\[")
18170 (line-beginning-position)))
18171 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18172 ((save-excursion ; fix next clock?
18173 (re-search-backward org-ts-regexp0 nil t)
18174 (looking-at (concat org-ts-regexp0 "\\] =>")))
18175 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18176 (save-window-excursion
18177 ;; Find closest clock to point, adjust the previous/next one in history
18178 (let* ((p (save-excursion (org-back-to-heading t)))
18179 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18180 (clfixnth
18181 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18182 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18183 (if (not clfixpos)
18184 (message "No clock to adjust")
18185 (save-excursion
18186 (org-goto-marker-or-bmk clfixpos)
18187 (org-show-subtree)
18188 (when (re-search-forward clrgx nil t)
18189 (goto-char (match-beginning 1))
18190 (let (org-clock-adjust-closest)
18191 (org-timestamp-change n timestamp? updown))
18192 (message "Clock adjusted in %s for heading: %s"
18193 (file-name-nondirectory (buffer-file-name))
18194 (org-get-heading t t)))))))))
18195 ;; Try to recenter the calendar window, if any.
18196 (when (and org-calendar-follow-timestamp-change
18197 (get-buffer-window "*Calendar*" t)
18198 (memq timestamp? '(day month year)))
18199 (org-recenter-calendar (time-to-days time))))))
18201 (defun org-modify-ts-extra (s pos n dm)
18202 "Change the different parts of the lead-time and repeat fields in timestamp."
18203 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18204 ng h m new rem)
18205 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18206 (cond
18207 ((or (org-pos-in-match-range pos 2)
18208 (org-pos-in-match-range pos 3))
18209 (setq m (string-to-number (match-string 3 s))
18210 h (string-to-number (match-string 2 s)))
18211 (if (org-pos-in-match-range pos 2)
18212 (setq h (+ h n))
18213 (setq n (* dm (with-no-warnings (signum n))))
18214 (unless (= 0 (setq rem (% m dm)))
18215 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18216 (setq m (+ m n)))
18217 (when (< m 0) (setq m (+ m 60) h (1- h)))
18218 (when (> m 59) (setq m (- m 60) h (1+ h)))
18219 (setq h (mod h 24))
18220 (setq ng 1 new (format "-%02d:%02d" h m)))
18221 ((org-pos-in-match-range pos 6)
18222 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18223 ((org-pos-in-match-range pos 5)
18224 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18226 ((org-pos-in-match-range pos 9)
18227 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18228 ((org-pos-in-match-range pos 8)
18229 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18231 (when ng
18232 (setq s (concat
18233 (substring s 0 (match-beginning ng))
18235 (substring s (match-end ng))))))
18238 (defun org-recenter-calendar (d)
18239 "If the calendar is visible, recenter it to date D."
18240 (let ((cwin (get-buffer-window "*Calendar*" t)))
18241 (when cwin
18242 (let ((calendar-move-hook nil))
18243 (with-selected-window cwin
18244 (calendar-goto-date
18245 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18247 (defun org-goto-calendar (&optional arg)
18248 "Go to the Emacs calendar at the current date.
18249 If there is a time stamp in the current line, go to that date.
18250 A prefix ARG can be used to force the current date."
18251 (interactive "P")
18252 (let ((tsr org-ts-regexp) diff
18253 (calendar-move-hook nil)
18254 (calendar-view-holidays-initially-flag nil)
18255 (calendar-view-diary-initially-flag nil))
18256 (when (or (org-at-timestamp-p)
18257 (save-excursion
18258 (beginning-of-line 1)
18259 (looking-at (concat ".*" tsr))))
18260 (let ((d1 (time-to-days (current-time)))
18261 (d2 (time-to-days
18262 (org-time-string-to-time (match-string 1)))))
18263 (setq diff (- d2 d1))))
18264 (calendar)
18265 (calendar-goto-today)
18266 (when (and diff (not arg)) (calendar-forward-day diff))))
18268 (defun org-get-date-from-calendar ()
18269 "Return a list (month day year) of date at point in calendar."
18270 (with-current-buffer "*Calendar*"
18271 (save-match-data
18272 (calendar-cursor-to-date))))
18274 (defun org-date-from-calendar ()
18275 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18276 If there is already a time stamp at the cursor position, update it."
18277 (interactive)
18278 (if (org-at-timestamp-p t)
18279 (org-timestamp-change 0 'calendar)
18280 (let ((cal-date (org-get-date-from-calendar)))
18281 (org-insert-time-stamp
18282 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18284 (defcustom org-effort-durations
18285 `(("min" . 1)
18286 ("h" . 60)
18287 ("d" . ,(* 60 8))
18288 ("w" . ,(* 60 8 5))
18289 ("m" . ,(* 60 8 5 4))
18290 ("y" . ,(* 60 8 5 40)))
18291 "Conversion factor to minutes for an effort modifier.
18293 Each entry has the form (MODIFIER . MINUTES).
18295 In an effort string, a number followed by MODIFIER is multiplied
18296 by the specified number of MINUTES to obtain an effort in
18297 minutes.
18299 For example, if the value of this variable is ((\"hours\" . 60)), then an
18300 effort string \"2hours\" is equivalent to 120 minutes."
18301 :group 'org-agenda
18302 :version "26.1"
18303 :package-version '(Org . "8.3")
18304 :type '(alist :key-type (string :tag "Modifier")
18305 :value-type (number :tag "Minutes")))
18307 (defun org-minutes-to-clocksum-string (m)
18308 "Format number of minutes as a clocksum string.
18309 The format is determined by `org-time-clocksum-format',
18310 `org-time-clocksum-use-fractional' and
18311 `org-time-clocksum-fractional-format' and
18312 `org-time-clocksum-use-effort-durations'."
18313 (let ((clocksum "")
18314 (m (round m)) ; Don't allow fractions of minutes
18315 h d w mo y fmt n)
18316 (setq h (if org-time-clocksum-use-effort-durations
18317 (cdr (assoc "h" org-effort-durations)) 60)
18318 d (if org-time-clocksum-use-effort-durations
18319 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18320 w (if org-time-clocksum-use-effort-durations
18321 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18322 mo (if org-time-clocksum-use-effort-durations
18323 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18324 y (if org-time-clocksum-use-effort-durations
18325 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18326 ;; fractional format
18327 (if org-time-clocksum-use-fractional
18328 (cond
18329 ;; single format string
18330 ((stringp org-time-clocksum-fractional-format)
18331 (format org-time-clocksum-fractional-format (/ m (float h))))
18332 ;; choice of fractional formats for different time units
18333 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18334 (> (/ (truncate m) (* y d h)) 0))
18335 (format fmt (/ m (* y d (float h)))))
18336 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18337 (> (/ (truncate m) (* mo d h)) 0))
18338 (format fmt (/ m (* mo d (float h)))))
18339 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18340 (> (/ (truncate m) (* w d h)) 0))
18341 (format fmt (/ m (* w d (float h)))))
18342 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18343 (> (/ (truncate m) (* d h)) 0))
18344 (format fmt (/ m (* d (float h)))))
18345 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18346 (> (/ (truncate m) h) 0))
18347 (format fmt (/ m (float h))))
18348 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18349 (format fmt m))
18350 ;; fall back to smallest time unit with a format
18351 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18352 (format fmt (/ m (float h))))
18353 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18354 (format fmt (/ m (* d (float h)))))
18355 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18356 (format fmt (/ m (* w d (float h)))))
18357 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18358 (format fmt (/ m (* mo d (float h)))))
18359 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18360 (format fmt (/ m (* y d (float h))))))
18361 ;; standard (non-fractional) format, with single format string
18362 (if (stringp org-time-clocksum-format)
18363 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18364 ;; separate formats components
18365 (and (setq fmt (plist-get org-time-clocksum-format :years))
18366 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18367 (plist-get org-time-clocksum-format :require-years))
18368 (setq clocksum (concat clocksum (format fmt n))
18369 m (- m (* n y d h))))
18370 (and (setq fmt (plist-get org-time-clocksum-format :months))
18371 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18372 (plist-get org-time-clocksum-format :require-months))
18373 (setq clocksum (concat clocksum (format fmt n))
18374 m (- m (* n mo d h))))
18375 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18376 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18377 (plist-get org-time-clocksum-format :require-weeks))
18378 (setq clocksum (concat clocksum (format fmt n))
18379 m (- m (* n w d h))))
18380 (and (setq fmt (plist-get org-time-clocksum-format :days))
18381 (or (> (setq n (/ (truncate m) (* d h))) 0)
18382 (plist-get org-time-clocksum-format :require-days))
18383 (setq clocksum (concat clocksum (format fmt n))
18384 m (- m (* n d h))))
18385 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18386 (or (> (setq n (/ (truncate m) h)) 0)
18387 (plist-get org-time-clocksum-format :require-hours))
18388 (setq clocksum (concat clocksum (format fmt n))
18389 m (- m (* n h))))
18390 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18391 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18392 (setq clocksum (concat clocksum (format fmt m))))
18393 ;; return formatted time duration
18394 clocksum))))
18396 (defun org-hours-to-clocksum-string (n)
18397 (org-minutes-to-clocksum-string (* n 60)))
18399 (defun org-hh:mm-string-to-minutes (s)
18400 "Convert a string H:MM to a number of minutes.
18401 If the string is just a number, interpret it as minutes.
18402 In fact, the first hh:mm or number in the string will be taken,
18403 there can be extra stuff in the string.
18404 If no number is found, the return value is 0."
18405 (cond
18406 ((integerp s) s)
18407 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18408 (+ (* (string-to-number (match-string 1 s)) 60)
18409 (string-to-number (match-string 2 s))))
18410 ((string-match "\\([0-9]+\\)" s)
18411 (string-to-number (match-string 1 s)))
18412 (t 0)))
18414 (defcustom org-image-actual-width t
18415 "Should we use the actual width of images when inlining them?
18417 When set to t, always use the image width.
18419 When set to a number, use imagemagick (when available) to set
18420 the image's width to this value.
18422 When set to a number in a list, try to get the width from any
18423 #+ATTR.* keyword if it matches a width specification like
18425 #+ATTR_HTML: :width 300px
18427 and fall back on that number if none is found.
18429 When set to nil, try to get the width from an #+ATTR.* keyword
18430 and fall back on the original width if none is found.
18432 This requires Emacs >= 24.1, build with imagemagick support."
18433 :group 'org-appearance
18434 :version "24.4"
18435 :package-version '(Org . "8.0")
18436 :type '(choice
18437 (const :tag "Use the image width" t)
18438 (integer :tag "Use a number of pixels")
18439 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18440 (const :tag "Use #+ATTR* or don't resize" nil)))
18442 (defcustom org-agenda-inhibit-startup nil
18443 "Inhibit startup when preparing agenda buffers.
18444 When this variable is t, the initialization of the Org agenda
18445 buffers is inhibited: e.g. the visibility state is not set, the
18446 tables are not re-aligned, etc."
18447 :type 'boolean
18448 :version "24.3"
18449 :group 'org-agenda)
18451 (defcustom org-agenda-ignore-properties nil
18452 "Avoid updating text properties when building the agenda.
18453 Properties are used to prepare buffers for effort estimates,
18454 appointments, statistics and subtree-local categories.
18455 If you don't use these in the agenda, you can add them to this
18456 list and agenda building will be a bit faster.
18457 The value is a list, with zero or more of the symbols `effort', `appt',
18458 `stats' or `category'."
18459 :type '(set :greedy t
18460 (const effort)
18461 (const appt)
18462 (const stats)
18463 (const category))
18464 :version "26.1"
18465 :package-version '(Org . "8.3")
18466 :group 'org-agenda)
18468 (defun org-duration-string-to-minutes (s &optional output-to-string)
18469 "Convert a duration string S to minutes.
18471 A bare number is interpreted as minutes, modifiers can be set by
18472 customizing `org-effort-durations' (which see).
18474 Entries containing a colon are interpreted as H:MM by
18475 `org-hh:mm-string-to-minutes'."
18476 (let ((result 0)
18477 (re (concat "\\([0-9.]+\\) *\\("
18478 (regexp-opt (mapcar 'car org-effort-durations))
18479 "\\)")))
18480 (while (string-match re s)
18481 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18482 (string-to-number (match-string 1 s))))
18483 (setq s (replace-match "" nil t s)))
18484 (setq result (floor result))
18485 (cl-incf result (org-hh:mm-string-to-minutes s))
18486 (if output-to-string (number-to-string result) result)))
18488 ;;;; Files
18490 (defun org-save-all-org-buffers ()
18491 "Save all Org buffers without user confirmation."
18492 (interactive)
18493 (message "Saving all Org buffers...")
18494 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18495 (when (featurep 'org-id) (org-id-locations-save))
18496 (message "Saving all Org buffers... done"))
18498 (defun org-revert-all-org-buffers ()
18499 "Revert all Org buffers.
18500 Prompt for confirmation when there are unsaved changes.
18501 Be sure you know what you are doing before letting this function
18502 overwrite your changes.
18504 This function is useful in a setup where one tracks org files
18505 with a version control system, to revert on one machine after pulling
18506 changes from another. I believe the procedure must be like this:
18508 1. M-x org-save-all-org-buffers
18509 2. Pull changes from the other machine, resolve conflicts
18510 3. M-x org-revert-all-org-buffers"
18511 (interactive)
18512 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18513 (user-error "Abort"))
18514 (save-excursion
18515 (save-window-excursion
18516 (dolist (b (buffer-list))
18517 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18518 (with-current-buffer b buffer-file-name))
18519 (pop-to-buffer-same-window b)
18520 (revert-buffer t 'no-confirm)))
18521 (when (and (featurep 'org-id) org-id-track-globally)
18522 (org-id-locations-load)))))
18524 ;;;; Agenda files
18526 ;;;###autoload
18527 (defun org-switchb (&optional arg)
18528 "Switch between Org buffers.
18530 With `\\[universal-argument]' prefix, restrict available buffers to files.
18532 With `\\[universal-argument] \\[universal-argument]' \
18533 prefix, restrict available buffers to agenda files."
18534 (interactive "P")
18535 (let ((blist (org-buffer-list
18536 (cond ((equal arg '(4)) 'files)
18537 ((equal arg '(16)) 'agenda)))))
18538 (pop-to-buffer-same-window
18539 (completing-read "Org buffer: "
18540 (mapcar #'list (mapcar #'buffer-name blist))
18541 nil t))))
18543 (defun org-buffer-list (&optional predicate exclude-tmp)
18544 "Return a list of Org buffers.
18545 PREDICATE can be `export', `files' or `agenda'.
18547 export restrict the list to Export buffers.
18548 files restrict the list to buffers visiting Org files.
18549 agenda restrict the list to buffers visiting agenda files.
18551 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18552 (let* ((bfn nil)
18553 (agenda-files (and (eq predicate 'agenda)
18554 (mapcar 'file-truename (org-agenda-files t))))
18555 (filter
18556 (cond
18557 ((eq predicate 'files)
18558 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18559 ((eq predicate 'export)
18560 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18561 ((eq predicate 'agenda)
18562 (lambda (b)
18563 (with-current-buffer b
18564 (and (derived-mode-p 'org-mode)
18565 (setq bfn (buffer-file-name b))
18566 (member (file-truename bfn) agenda-files)))))
18567 (t (lambda (b) (with-current-buffer b
18568 (or (derived-mode-p 'org-mode)
18569 (string-match "\\*Org .*Export"
18570 (buffer-name b)))))))))
18571 (delq nil
18572 (mapcar
18573 (lambda(b)
18574 (if (and (funcall filter b)
18575 (or (not exclude-tmp)
18576 (not (string-match "tmp" (buffer-name b)))))
18578 nil))
18579 (buffer-list)))))
18581 (defun org-agenda-files (&optional unrestricted archives)
18582 "Get the list of agenda files.
18583 Optional UNRESTRICTED means return the full list even if a restriction
18584 is currently in place.
18585 When ARCHIVES is t, include all archive files that are really being
18586 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18587 `org-agenda-archives-mode' is t."
18588 (let ((files
18589 (cond
18590 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18591 ((stringp org-agenda-files) (org-read-agenda-file-list))
18592 ((listp org-agenda-files) org-agenda-files)
18593 (t (error "Invalid value of `org-agenda-files'")))))
18594 (setq files (apply 'append
18595 (mapcar (lambda (f)
18596 (if (file-directory-p f)
18597 (directory-files
18598 f t org-agenda-file-regexp)
18599 (list f)))
18600 files)))
18601 (when org-agenda-skip-unavailable-files
18602 (setq files (delq nil
18603 (mapcar (function
18604 (lambda (file)
18605 (and (file-readable-p file) file)))
18606 files))))
18607 (when (or (eq archives t)
18608 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18609 (setq files (org-add-archive-files files)))
18610 files))
18612 (defun org-agenda-file-p (&optional file)
18613 "Return non-nil, if FILE is an agenda file.
18614 If FILE is omitted, use the file associated with the current
18615 buffer."
18616 (let ((fname (or file (buffer-file-name))))
18617 (and fname
18618 (member (file-truename fname)
18619 (mapcar #'file-truename (org-agenda-files t))))))
18621 (defun org-edit-agenda-file-list ()
18622 "Edit the list of agenda files.
18623 Depending on setup, this either uses customize to edit the variable
18624 `org-agenda-files', or it visits the file that is holding the list. In the
18625 latter case, the buffer is set up in a way that saving it automatically kills
18626 the buffer and restores the previous window configuration."
18627 (interactive)
18628 (if (stringp org-agenda-files)
18629 (let ((cw (current-window-configuration)))
18630 (find-file org-agenda-files)
18631 (setq-local org-window-configuration cw)
18632 (add-hook 'after-save-hook
18633 (lambda ()
18634 (set-window-configuration
18635 (prog1 org-window-configuration
18636 (kill-buffer (current-buffer))))
18637 (org-install-agenda-files-menu)
18638 (message "New agenda file list installed"))
18639 nil 'local)
18640 (message "%s" (substitute-command-keys
18641 "Edit list and finish with \\[save-buffer]")))
18642 (customize-variable 'org-agenda-files)))
18644 (defun org-store-new-agenda-file-list (list)
18645 "Set new value for the agenda file list and save it correctly."
18646 (if (stringp org-agenda-files)
18647 (let ((fe (org-read-agenda-file-list t)) b u)
18648 (while (setq b (find-buffer-visiting org-agenda-files))
18649 (kill-buffer b))
18650 (with-temp-file org-agenda-files
18651 (insert
18652 (mapconcat
18653 (lambda (f) ;; Keep un-expanded entries.
18654 (if (setq u (assoc f fe))
18655 (cdr u)
18657 list "\n")
18658 "\n")))
18659 (let ((org-mode-hook nil) (org-inhibit-startup t)
18660 (org-insert-mode-line-in-empty-file nil))
18661 (setq org-agenda-files list)
18662 (customize-save-variable 'org-agenda-files org-agenda-files))))
18664 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18665 "Read the list of agenda files from a file.
18666 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18667 filenames, used by `org-store-new-agenda-file-list' to write back
18668 un-expanded file names."
18669 (when (file-directory-p org-agenda-files)
18670 (error "`org-agenda-files' cannot be a single directory"))
18671 (when (stringp org-agenda-files)
18672 (with-temp-buffer
18673 (insert-file-contents org-agenda-files)
18674 (mapcar
18675 (lambda (f)
18676 (let ((e (expand-file-name (substitute-in-file-name f)
18677 org-directory)))
18678 (if pair-with-expansion
18679 (cons e f)
18680 e)))
18681 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18683 ;;;###autoload
18684 (defun org-cycle-agenda-files ()
18685 "Cycle through the files in `org-agenda-files'.
18686 If the current buffer visits an agenda file, find the next one in the list.
18687 If the current buffer does not, find the first agenda file."
18688 (interactive)
18689 (let* ((fs (or (org-agenda-files t)
18690 (user-error "No agenda files")))
18691 (files (copy-sequence fs))
18692 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18693 file)
18694 (when tcf
18695 (while (and (setq file (pop files))
18696 (not (equal (file-truename file) tcf)))))
18697 (find-file (car (or files fs)))
18698 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18700 (defun org-agenda-file-to-front (&optional to-end)
18701 "Move/add the current file to the top of the agenda file list.
18702 If the file is not present in the list, it is added to the front. If it is
18703 present, it is moved there. With optional argument TO-END, add/move to the
18704 end of the list."
18705 (interactive "P")
18706 (let ((org-agenda-skip-unavailable-files nil)
18707 (file-alist (mapcar (lambda (x)
18708 (cons (file-truename x) x))
18709 (org-agenda-files t)))
18710 (ctf (file-truename
18711 (or buffer-file-name
18712 (user-error "Please save the current buffer to a file"))))
18713 x had)
18714 (setq x (assoc ctf file-alist) had x)
18716 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18717 (if to-end
18718 (setq file-alist (append (delq x file-alist) (list x)))
18719 (setq file-alist (cons x (delq x file-alist))))
18720 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18721 (org-install-agenda-files-menu)
18722 (message "File %s to %s of agenda file list"
18723 (if had "moved" "added") (if to-end "end" "front"))))
18725 (defun org-remove-file (&optional file)
18726 "Remove current file from the list of files in variable `org-agenda-files'.
18727 These are the files which are being checked for agenda entries.
18728 Optional argument FILE means use this file instead of the current."
18729 (interactive)
18730 (let* ((org-agenda-skip-unavailable-files nil)
18731 (file (or file buffer-file-name
18732 (user-error "Current buffer does not visit a file")))
18733 (true-file (file-truename file))
18734 (afile (abbreviate-file-name file))
18735 (files (delq nil (mapcar
18736 (lambda (x)
18737 (unless (equal true-file
18738 (file-truename x))
18740 (org-agenda-files t)))))
18741 (if (not (= (length files) (length (org-agenda-files t))))
18742 (progn
18743 (org-store-new-agenda-file-list files)
18744 (org-install-agenda-files-menu)
18745 (message "Removed from Org Agenda list: %s" afile))
18746 (message "File was not in list: %s (not removed)" afile))))
18748 (defun org-file-menu-entry (file)
18749 (vector file (list 'find-file file) t))
18751 (defun org-check-agenda-file (file)
18752 "Make sure FILE exists. If not, ask user what to do."
18753 (unless (file-exists-p file)
18754 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18755 (abbreviate-file-name file))
18756 (let ((r (downcase (read-char-exclusive))))
18757 (cond
18758 ((equal r ?r)
18759 (org-remove-file file)
18760 (throw 'nextfile t))
18761 (t (user-error "Abort"))))))
18763 (defun org-get-agenda-file-buffer (file)
18764 "Get an agenda buffer visiting FILE.
18765 If the buffer needs to be created, add it to the list of buffers
18766 which might be released later."
18767 (let ((buf (org-find-base-buffer-visiting file)))
18768 (if buf
18769 buf ; just return it
18770 ;; Make a new buffer and remember it
18771 (setq buf (find-file-noselect file))
18772 (when buf (push buf org-agenda-new-buffers))
18773 buf)))
18775 (defun org-release-buffers (blist)
18776 "Release all buffers in list, asking the user for confirmation when needed.
18777 When a buffer is unmodified, it is just killed. When modified, it is saved
18778 \(if the user agrees) and then killed."
18779 (let (file)
18780 (dolist (buf blist)
18781 (setq file (buffer-file-name buf))
18782 (when (and (buffer-modified-p buf)
18783 file
18784 (y-or-n-p (format "Save file %s? " file)))
18785 (with-current-buffer buf (save-buffer)))
18786 (kill-buffer buf))))
18788 (defun org-agenda-prepare-buffers (files)
18789 "Create buffers for all agenda files, protect archived trees and comments."
18790 (interactive)
18791 (let ((pa '(:org-archived t))
18792 (pc '(:org-comment t))
18793 (pall '(:org-archived t :org-comment t))
18794 (inhibit-read-only t)
18795 (org-inhibit-startup org-agenda-inhibit-startup)
18796 (rea (concat ":" org-archive-tag ":"))
18797 re pos)
18798 (setq org-tag-alist-for-agenda nil
18799 org-tag-groups-alist-for-agenda nil)
18800 (save-excursion
18801 (save-restriction
18802 (dolist (file files)
18803 (catch 'nextfile
18804 (if (bufferp file)
18805 (set-buffer file)
18806 (org-check-agenda-file file)
18807 (set-buffer (org-get-agenda-file-buffer file)))
18808 (widen)
18809 (org-set-regexps-and-options 'tags-only)
18810 (setq pos (point))
18811 (or (memq 'category org-agenda-ignore-properties)
18812 (org-refresh-category-properties))
18813 (or (memq 'stats org-agenda-ignore-properties)
18814 (org-refresh-stats-properties))
18815 (or (memq 'effort org-agenda-ignore-properties)
18816 (org-refresh-effort-properties))
18817 (or (memq 'appt org-agenda-ignore-properties)
18818 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18819 (setq org-todo-keywords-for-agenda
18820 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18821 (setq org-done-keywords-for-agenda
18822 (append org-done-keywords-for-agenda org-done-keywords))
18823 (setq org-todo-keyword-alist-for-agenda
18824 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18825 (setq org-tag-alist-for-agenda
18826 (org-uniquify
18827 (append org-tag-alist-for-agenda
18828 org-current-tag-alist)))
18829 ;; Merge current file's tag groups into global
18830 ;; `org-tag-groups-alist-for-agenda'.
18831 (when org-group-tags
18832 (dolist (alist org-tag-groups-alist)
18833 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18834 (if old
18835 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18836 (push alist org-tag-groups-alist-for-agenda)))))
18837 (org-with-silent-modifications
18838 (save-excursion
18839 (remove-text-properties (point-min) (point-max) pall)
18840 (when org-agenda-skip-archived-trees
18841 (goto-char (point-min))
18842 (while (re-search-forward rea nil t)
18843 (when (org-at-heading-p t)
18844 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18845 (goto-char (point-min))
18846 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18847 (while (re-search-forward re nil t)
18848 (when (save-match-data (org-in-commented-heading-p t))
18849 (add-text-properties
18850 (match-beginning 0) (org-end-of-subtree t) pc)))))
18851 (goto-char pos)))))
18852 (setq org-todo-keywords-for-agenda
18853 (org-uniquify org-todo-keywords-for-agenda))
18854 (setq org-todo-keyword-alist-for-agenda
18855 (org-uniquify org-todo-keyword-alist-for-agenda))))
18858 ;;;; CDLaTeX minor mode
18860 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18861 "Keymap for the minor `org-cdlatex-mode'.")
18863 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18864 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18865 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18866 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18867 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18869 (defvar org-cdlatex-texmathp-advice-is-done nil
18870 "Flag remembering if we have applied the advice to texmathp already.")
18872 (define-minor-mode org-cdlatex-mode
18873 "Toggle the minor `org-cdlatex-mode'.
18874 This mode supports entering LaTeX environment and math in LaTeX fragments
18875 in Org mode.
18876 \\{org-cdlatex-mode-map}"
18877 nil " OCDL" nil
18878 (when org-cdlatex-mode
18879 (require 'cdlatex)
18880 (run-hooks 'cdlatex-mode-hook)
18881 (cdlatex-compute-tables))
18882 (unless org-cdlatex-texmathp-advice-is-done
18883 (setq org-cdlatex-texmathp-advice-is-done t)
18884 (defadvice texmathp (around org-math-always-on activate)
18885 "Always return t in Org buffers.
18886 This is because we want to insert math symbols without dollars even outside
18887 the LaTeX math segments. If Org mode thinks that point is actually inside
18888 an embedded LaTeX fragment, let `texmathp' do its job.
18889 `\\[org-cdlatex-mode-map]'"
18890 (interactive)
18891 (let (p)
18892 (cond
18893 ((not (derived-mode-p 'org-mode)) ad-do-it)
18894 ((eq this-command 'cdlatex-math-symbol)
18895 (setq ad-return-value t
18896 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18898 (let ((p (org-inside-LaTeX-fragment-p)))
18899 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18900 (setq ad-return-value t
18901 texmathp-why '("Org mode embedded math" . 0))
18902 (when p ad-do-it)))))))))
18904 (defun turn-on-org-cdlatex ()
18905 "Unconditionally turn on `org-cdlatex-mode'."
18906 (org-cdlatex-mode 1))
18908 (defun org-try-cdlatex-tab ()
18909 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18910 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18911 - inside a LaTeX fragment, or
18912 - after the first word in a line, where an abbreviation expansion could
18913 insert a LaTeX environment."
18914 (when org-cdlatex-mode
18915 (cond
18916 ;; Before any word on the line: No expansion possible.
18917 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18918 ;; Just after first word on the line: Expand it. Make sure it
18919 ;; cannot happen on headlines, though.
18920 ((save-excursion
18921 (skip-chars-backward "a-zA-Z0-9*")
18922 (skip-chars-backward " \t")
18923 (and (bolp) (not (org-at-heading-p))))
18924 (cdlatex-tab) t)
18925 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18927 (defun org-cdlatex-underscore-caret (&optional _arg)
18928 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18929 Revert to the normal definition outside of these fragments."
18930 (interactive "P")
18931 (if (org-inside-LaTeX-fragment-p)
18932 (call-interactively 'cdlatex-sub-superscript)
18933 (let (org-cdlatex-mode)
18934 (call-interactively (key-binding (vector last-input-event))))))
18936 (defun org-cdlatex-math-modify (&optional _arg)
18937 "Execute `cdlatex-math-modify' in LaTeX fragments.
18938 Revert to the normal definition outside of these fragments."
18939 (interactive "P")
18940 (if (org-inside-LaTeX-fragment-p)
18941 (call-interactively 'cdlatex-math-modify)
18942 (let (org-cdlatex-mode)
18943 (call-interactively (key-binding (vector last-input-event))))))
18945 (defun org-cdlatex-environment-indent (&optional environment item)
18946 "Execute `cdlatex-environment' and indent the inserted environment.
18948 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18950 The inserted environment is indented to current indentation
18951 unless point is at the beginning of the line, in which the
18952 environment remains unintended."
18953 (interactive)
18954 ;; cdlatex-environment always return nil. Therefore, capture output
18955 ;; first and determine if an environment was selected.
18956 (let* ((beg (point-marker))
18957 (end (copy-marker (point) t))
18958 (inserted (progn
18959 (ignore-errors (cdlatex-environment environment item))
18960 (< beg end)))
18961 ;; Figure out how many lines to move forward after the
18962 ;; environment has been inserted.
18963 (lines (when inserted
18964 (save-excursion
18965 (- (cl-loop while (< beg (point))
18966 with x = 0
18967 do (forward-line -1)
18968 (cl-incf x)
18969 finally return x)
18970 (if (progn (goto-char beg)
18971 (and (progn (skip-chars-forward " \t") (eolp))
18972 (progn (skip-chars-backward " \t") (bolp))))
18973 1 0)))))
18974 (env (org-trim (delete-and-extract-region beg end))))
18975 (when inserted
18976 ;; Get indentation of next line unless at column 0.
18977 (let ((ind (if (bolp) 0
18978 (save-excursion
18979 (org-return-indent)
18980 (prog1 (org-get-indentation)
18981 (when (progn (skip-chars-forward " \t") (eolp))
18982 (delete-region beg (point)))))))
18983 (bol (progn (skip-chars-backward " \t") (bolp))))
18984 ;; Insert a newline before environment unless at column zero
18985 ;; to "escape" the current line. Insert a newline if
18986 ;; something is one the same line as \end{ENVIRONMENT}.
18987 (insert
18988 (concat (unless bol "\n") env
18989 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18990 (unless (zerop ind)
18991 (save-excursion
18992 (goto-char beg)
18993 (while (< (point) end)
18994 (unless (eolp) (indent-line-to ind))
18995 (forward-line))))
18996 (goto-char beg)
18997 (forward-line lines)
18998 (indent-line-to ind)))
18999 (set-marker beg nil)
19000 (set-marker end nil)))
19003 ;;;; LaTeX fragments
19005 (defun org-inside-LaTeX-fragment-p ()
19006 "Test if point is inside a LaTeX fragment.
19007 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19008 sequence appearing also before point.
19009 Even though the matchers for math are configurable, this function assumes
19010 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19011 delimiters are skipped when they have been removed by customization.
19012 The return value is nil, or a cons cell with the delimiter and the
19013 position of this delimiter.
19015 This function does a reasonably good job, but can locally be fooled by
19016 for example currency specifications. For example it will assume being in
19017 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19018 fragments that are properly closed, but during editing, we have to live
19019 with the uncertainty caused by missing closing delimiters. This function
19020 looks only before point, not after."
19021 (catch 'exit
19022 (let ((pos (point))
19023 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19024 (lim (progn
19025 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19026 (point)))
19027 dd-on str (start 0) m re)
19028 (goto-char pos)
19029 (when dodollar
19030 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19031 re (nth 1 (assoc "$" org-latex-regexps)))
19032 (while (string-match re str start)
19033 (cond
19034 ((= (match-end 0) (length str))
19035 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19036 ((= (match-end 0) (- (length str) 5))
19037 (throw 'exit nil))
19038 (t (setq start (match-end 0))))))
19039 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19040 (goto-char pos)
19041 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19042 (and (match-beginning 2) (throw 'exit nil))
19043 ;; count $$
19044 (while (re-search-backward "\\$\\$" lim t)
19045 (setq dd-on (not dd-on)))
19046 (goto-char pos)
19047 (when dd-on (cons "$$" m))))))
19049 (defun org-inside-latex-macro-p ()
19050 "Is point inside a LaTeX macro or its arguments?"
19051 (save-match-data
19052 (org-in-regexp
19053 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19055 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19056 "Build an overlay between BEG and END using IMAGE file.
19057 Argument IMAGETYPE is the extension of the displayed image,
19058 as a string. It defaults to \"png\"."
19059 (let ((ov (make-overlay beg end))
19060 (imagetype (or (intern imagetype) 'png)))
19061 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19062 (overlay-put ov 'evaporate t)
19063 (overlay-put ov
19064 'modification-hooks
19065 (list (lambda (o _flag _beg _end &optional _l)
19066 (delete-overlay o))))
19067 (overlay-put ov
19068 'display
19069 (list 'image :type imagetype :file image :ascent 'center))))
19071 (defun org--list-latex-overlays (&optional beg end)
19072 "List all Org LaTeX overlays in current buffer.
19073 Limit to overlays between BEG and END when those are provided."
19074 (cl-remove-if-not
19075 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19076 (overlays-in (or beg (point-min)) (or end (point-max)))))
19078 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19079 "Remove all overlays with LaTeX fragment images in current buffer.
19080 When optional arguments BEG and END are non-nil, remove all
19081 overlays between them instead. Return a non-nil value when some
19082 overlays were removed, nil otherwise."
19083 (let ((overlays (org--list-latex-overlays beg end)))
19084 (mapc #'delete-overlay overlays)
19085 overlays))
19087 (defun org-toggle-latex-fragment (&optional arg)
19088 "Preview the LaTeX fragment at point, or all locally or globally.
19090 If the cursor is on a LaTeX fragment, create the image and overlay
19091 it over the source code, if there is none. Remove it otherwise.
19092 If there is no fragment at point, display all fragments in the
19093 current section.
19095 With prefix ARG, preview or clear image for all fragments in the
19096 current subtree or in the whole buffer when used before the first
19097 headline. With a prefix ARG `\\[universal-argument] \
19098 \\[universal-argument]' preview or clear images
19099 for all fragments in the buffer."
19100 (interactive "P")
19101 (when (display-graphic-p)
19102 (catch 'exit
19103 (save-excursion
19104 (let (beg end msg)
19105 (cond
19106 ((or (equal arg '(16))
19107 (and (equal arg '(4))
19108 (org-with-limited-levels (org-before-first-heading-p))))
19109 (if (org-remove-latex-fragment-image-overlays)
19110 (progn (message "LaTeX fragments images removed from buffer")
19111 (throw 'exit nil))
19112 (setq msg "Creating images for buffer...")))
19113 ((equal arg '(4))
19114 (org-with-limited-levels (org-back-to-heading t))
19115 (setq beg (point))
19116 (setq end (progn (org-end-of-subtree t) (point)))
19117 (if (org-remove-latex-fragment-image-overlays beg end)
19118 (progn
19119 (message "LaTeX fragment images removed from subtree")
19120 (throw 'exit nil))
19121 (setq msg "Creating images for subtree...")))
19122 ((let ((datum (org-element-context)))
19123 (when (memq (org-element-type datum)
19124 '(latex-environment latex-fragment))
19125 (setq beg (org-element-property :begin datum))
19126 (setq end (org-element-property :end datum))
19127 (if (org-remove-latex-fragment-image-overlays beg end)
19128 (progn (message "LaTeX fragment image removed")
19129 (throw 'exit nil))
19130 (setq msg "Creating image...")))))
19132 (org-with-limited-levels
19133 (setq beg (if (org-at-heading-p) (line-beginning-position)
19134 (outline-previous-heading)
19135 (point)))
19136 (setq end (progn (outline-next-heading) (point)))
19137 (if (org-remove-latex-fragment-image-overlays beg end)
19138 (progn
19139 (message "LaTeX fragment images removed from section")
19140 (throw 'exit nil))
19141 (setq msg "Creating images for section...")))))
19142 (let ((file (buffer-file-name (buffer-base-buffer))))
19143 (org-format-latex
19144 (concat org-preview-latex-image-directory "org-ltximg")
19145 beg end
19146 ;; Emacs cannot overlay images from remote hosts. Create
19147 ;; it in `temporary-file-directory' instead.
19148 (if (or (not file) (file-remote-p file))
19149 temporary-file-directory
19150 default-directory)
19151 'overlays msg 'forbuffer org-preview-latex-default-process))
19152 (message (concat msg "done")))))))
19154 (defun org-format-latex
19155 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19156 "Replace LaTeX fragments with links to an image.
19158 The function takes care of creating the replacement image.
19160 Only consider fragments between BEG and END when those are
19161 provided.
19163 When optional argument OVERLAYS is non-nil, display the image on
19164 top of the fragment instead of replacing it.
19166 PROCESSING-TYPE is the conversion method to use, as a symbol.
19168 Some of the options can be changed using the variable
19169 `org-format-latex-options', which see."
19170 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19171 (unless (eq processing-type 'verbatim)
19172 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19173 (cnt 0)
19174 checkdir-flag)
19175 (goto-char (or beg (point-min)))
19176 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19177 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19178 (overlay-recenter (or end (point-max))))
19179 (while (re-search-forward math-regexp end t)
19180 (unless (and overlays
19181 (eq (get-char-property (point) 'org-overlay-type)
19182 'org-latex-overlay))
19183 (let* ((context (org-element-context))
19184 (type (org-element-type context)))
19185 (when (memq type '(latex-environment latex-fragment))
19186 (let ((block-type (eq type 'latex-environment))
19187 (value (org-element-property :value context))
19188 (beg (org-element-property :begin context))
19189 (end (save-excursion
19190 (goto-char (org-element-property :end context))
19191 (skip-chars-backward " \r\t\n")
19192 (point))))
19193 (cond
19194 ((eq processing-type 'mathjax)
19195 ;; Prepare for MathJax processing.
19196 (if (not (string-match "\\`\\$\\$?" value))
19197 (goto-char end)
19198 (delete-region beg end)
19199 (if (string= (match-string 0 value) "$$")
19200 (insert "\\[" (substring value 2 -2) "\\]")
19201 (insert "\\(" (substring value 1 -1) "\\)"))))
19202 ((assq processing-type org-preview-latex-process-alist)
19203 ;; Process to an image.
19204 (cl-incf cnt)
19205 (goto-char beg)
19206 (let* ((processing-info
19207 (cdr (assq processing-type org-preview-latex-process-alist)))
19208 (face (face-at-point))
19209 ;; Get the colors from the face at point.
19211 (let ((color (plist-get org-format-latex-options
19212 :foreground)))
19213 (if (and forbuffer (eq color 'auto))
19214 (face-attribute face :foreground nil 'default)
19215 color)))
19217 (let ((color (plist-get org-format-latex-options
19218 :background)))
19219 (if (and forbuffer (eq color 'auto))
19220 (face-attribute face :background nil 'default)
19221 color)))
19222 (hash (sha1 (prin1-to-string
19223 (list org-format-latex-header
19224 org-latex-default-packages-alist
19225 org-latex-packages-alist
19226 org-format-latex-options
19227 forbuffer value fg bg))))
19228 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19229 (absprefix (expand-file-name prefix dir))
19230 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19231 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19232 (sep (and block-type "\n\n"))
19233 (link (concat sep "[[file:" linkfile "]]" sep))
19234 (options
19235 (org-combine-plists
19236 org-format-latex-options
19237 `(:foreground ,fg :background ,bg))))
19238 (when msg (message msg cnt))
19239 (unless checkdir-flag ; Ensure the directory exists.
19240 (setq checkdir-flag t)
19241 (let ((todir (file-name-directory absprefix)))
19242 (unless (file-directory-p todir)
19243 (make-directory todir t))))
19244 (unless (file-exists-p movefile)
19245 (org-create-formula-image
19246 value movefile options forbuffer processing-type))
19247 (if overlays
19248 (progn
19249 (dolist (o (overlays-in beg end))
19250 (when (eq (overlay-get o 'org-overlay-type)
19251 'org-latex-overlay)
19252 (delete-overlay o)))
19253 (org--format-latex-make-overlay beg end movefile imagetype)
19254 (goto-char end))
19255 (delete-region beg end)
19256 (insert
19257 (org-add-props link
19258 (list 'org-latex-src
19259 (replace-regexp-in-string "\"" "" value)
19260 'org-latex-src-embed-type
19261 (if block-type 'paragraph 'character)))))))
19262 ((eq processing-type 'mathml)
19263 ;; Process to MathML.
19264 (unless (org-format-latex-mathml-available-p)
19265 (user-error "LaTeX to MathML converter not configured"))
19266 (cl-incf cnt)
19267 (when msg (message msg cnt))
19268 (goto-char beg)
19269 (delete-region beg end)
19270 (insert (org-format-latex-as-mathml
19271 value block-type prefix dir)))
19273 (error "Unknown conversion process %s for LaTeX fragments"
19274 processing-type)))))))))))
19276 (defun org-create-math-formula (latex-frag &optional mathml-file)
19277 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19278 Use `org-latex-to-mathml-convert-command'. If the conversion is
19279 sucessful, return the portion between \"<math...> </math>\"
19280 elements otherwise return nil. When MATHML-FILE is specified,
19281 write the results in to that file. When invoked as an
19282 interactive command, prompt for LATEX-FRAG, with initial value
19283 set to the current active region and echo the results for user
19284 inspection."
19285 (interactive (list (let ((frag (when (org-region-active-p)
19286 (buffer-substring-no-properties
19287 (region-beginning) (region-end)))))
19288 (read-string "LaTeX Fragment: " frag nil frag))))
19289 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19290 (let* ((tmp-in-file
19291 (let ((file (file-relative-name
19292 (make-temp-name (expand-file-name "ltxmathml-in")))))
19293 (write-region latex-frag nil file)
19294 file))
19295 (tmp-out-file (file-relative-name
19296 (make-temp-name (expand-file-name "ltxmathml-out"))))
19297 (cmd (format-spec
19298 org-latex-to-mathml-convert-command
19299 `((?j . ,(and org-latex-to-mathml-jar-file
19300 (shell-quote-argument
19301 (expand-file-name
19302 org-latex-to-mathml-jar-file))))
19303 (?I . ,(shell-quote-argument tmp-in-file))
19304 (?i . ,latex-frag)
19305 (?o . ,(shell-quote-argument tmp-out-file)))))
19306 mathml shell-command-output)
19307 (when (called-interactively-p 'any)
19308 (unless (org-format-latex-mathml-available-p)
19309 (user-error "LaTeX to MathML converter not configured")))
19310 (message "Running %s" cmd)
19311 (setq shell-command-output (shell-command-to-string cmd))
19312 (setq mathml
19313 (when (file-readable-p tmp-out-file)
19314 (with-current-buffer (find-file-noselect tmp-out-file t)
19315 (goto-char (point-min))
19316 (when (re-search-forward
19317 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19318 (regexp-quote
19319 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19320 nil t)
19321 (prog1 (match-string 0) (kill-buffer))))))
19322 (cond
19323 (mathml
19324 (setq mathml
19325 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19326 (when mathml-file
19327 (write-region mathml nil mathml-file))
19328 (when (called-interactively-p 'any)
19329 (message mathml)))
19330 ((message "LaTeX to MathML conversion failed")
19331 (message shell-command-output)))
19332 (delete-file tmp-in-file)
19333 (when (file-exists-p tmp-out-file)
19334 (delete-file tmp-out-file))
19335 mathml))
19337 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19338 prefix &optional dir)
19339 "Use `org-create-math-formula' but check local cache first."
19340 (let* ((absprefix (expand-file-name prefix dir))
19341 (print-length nil) (print-level nil)
19342 (formula-id (concat
19343 "formula-"
19344 (sha1
19345 (prin1-to-string
19346 (list latex-frag
19347 org-latex-to-mathml-convert-command)))))
19348 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19349 (formula-cache-dir (file-name-directory formula-cache)))
19351 (unless (file-directory-p formula-cache-dir)
19352 (make-directory formula-cache-dir t))
19354 (unless (file-exists-p formula-cache)
19355 (org-create-math-formula latex-frag formula-cache))
19357 (if (file-exists-p formula-cache)
19358 ;; Successful conversion. Return the link to MathML file.
19359 (org-add-props
19360 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19361 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19362 'org-latex-src-embed-type (if latex-frag-type
19363 'paragraph 'character)))
19364 ;; Failed conversion. Return the LaTeX fragment verbatim
19365 latex-frag)))
19367 (defun org--get-display-dpi ()
19368 "Get the DPI of the display.
19369 The function assumes that the display has the same pixel width in
19370 the horizontal and vertical directions."
19371 (if (display-graphic-p)
19372 (round (/ (display-pixel-height)
19373 (/ (display-mm-height) 25.4)))
19374 (error "Attempt to calculate the dpi of a non-graphic display")))
19376 (defun org-create-formula-image
19377 (string tofile options buffer &optional processing-type)
19378 "Create an image from LaTeX source using external processes.
19380 The LaTeX STRING is saved to a temporary LaTeX file, then
19381 converted to an image file by process PROCESSING-TYPE defined in
19382 `org-preview-latex-process-alist'. A nil value defaults to
19383 `org-preview-latex-default-process'.
19385 The generated image file is eventually moved to TOFILE.
19387 The OPTIONS argument controls the size, foreground color and
19388 background color of the generated image.
19390 When BUFFER non-nil, this function is used for LaTeX previewing.
19391 Otherwise, it is used to deal with LaTeX snippets showed in
19392 a HTML file."
19393 (let* ((processing-type (or processing-type
19394 org-preview-latex-default-process))
19395 (processing-info
19396 (cdr (assq processing-type org-preview-latex-process-alist)))
19397 (programs (plist-get processing-info :programs))
19398 (error-message (or (plist-get processing-info :message) ""))
19399 (use-xcolor (plist-get processing-info :use-xcolor))
19400 (image-input-type (plist-get processing-info :image-input-type))
19401 (image-output-type (plist-get processing-info :image-output-type))
19402 (post-clean (or (plist-get processing-info :post-clean)
19403 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19404 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19405 (latex-header
19406 (or (plist-get processing-info :latex-header)
19407 (org-latex-make-preamble
19408 (org-export-get-environment (org-export-get-backend 'latex))
19409 org-format-latex-header)))
19410 (latex-compiler (plist-get processing-info :latex-compiler))
19411 (image-converter (plist-get processing-info :image-converter))
19412 (tmpdir temporary-file-directory)
19413 (texfilebase (make-temp-name
19414 (expand-file-name "orgtex" tmpdir)))
19415 (texfile (concat texfilebase ".tex"))
19416 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19417 '(1.0 . 1.0)))
19418 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19419 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19420 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19421 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19422 "Black"))
19423 (bg (or (plist-get options (if buffer :background :html-background))
19424 "Transparent"))
19425 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19426 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19427 (dolist (program programs)
19428 (org-check-external-command program error-message))
19429 (if use-xcolor
19430 (progn (if (eq fg 'default)
19431 (setq fg (org-latex-color :foreground))
19432 (setq fg (org-latex-color-format fg)))
19433 (if (eq bg 'default)
19434 (setq bg (org-latex-color :background))
19435 (setq bg (org-latex-color-format
19436 (if (string= bg "Transparent") "white" bg))))
19437 (with-temp-file texfile
19438 (insert latex-header)
19439 (insert "\n\\begin{document}\n"
19440 "\\definecolor{fg}{rgb}{" fg "}\n"
19441 "\\definecolor{bg}{rgb}{" bg "}\n"
19442 "\n\\pagecolor{bg}\n"
19443 "\n{\\color{fg}\n"
19444 string
19445 "\n}\n"
19446 "\n\\end{document}\n")))
19447 (if (eq fg 'default)
19448 (setq fg (org-dvipng-color :foreground))
19449 (unless (string= fg "Transparent")
19450 (setq fg (org-dvipng-color-format fg))))
19451 (if (eq bg 'default)
19452 (setq bg (org-dvipng-color :background))
19453 (unless (string= bg "Transparent")
19454 (setq bg (org-dvipng-color-format bg))))
19455 (with-temp-file texfile
19456 (insert latex-header)
19457 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19459 (let* ((err-msg (format "Please adjust '%s' part of \
19460 `org-preview-latex-process-alist'."
19461 processing-type))
19462 (image-input-file
19463 (org-compile-file
19464 texfile latex-compiler image-input-type err-msg log-buf))
19465 (image-output-file
19466 (org-compile-file
19467 image-input-file image-converter image-output-type err-msg log-buf
19468 `((?F . ,(shell-quote-argument fg))
19469 (?B . ,(shell-quote-argument bg))
19470 (?D . ,(shell-quote-argument (format "%s" dpi)))
19471 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19472 (copy-file image-output-file tofile 'replace)
19473 (dolist (e post-clean)
19474 (when (file-exists-p (concat texfilebase e))
19475 (delete-file (concat texfilebase e))))
19476 image-output-file)))
19478 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19479 "Fill a LaTeX header template TPL.
19480 In the template, the following place holders will be recognized:
19482 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19483 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19484 [PACKAGES] \\usepackage statements for PKG
19485 [NO-PACKAGES] do not include PKG
19486 [EXTRA] the string EXTRA
19487 [NO-EXTRA] do not include EXTRA
19489 For backward compatibility, if both the positive and the negative place
19490 holder is missing, the positive one (without the \"NO-\") will be
19491 assumed to be present at the end of the template.
19492 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19493 EXTRA is a string.
19494 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19495 (let (rpl (end ""))
19496 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19497 (setq rpl (if (or (match-end 1) (not def-pkg))
19498 "" (org-latex-packages-to-string def-pkg snippets-p t))
19499 tpl (replace-match rpl t t tpl))
19500 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19502 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19503 (setq rpl (if (or (match-end 1) (not pkg))
19504 "" (org-latex-packages-to-string pkg snippets-p t))
19505 tpl (replace-match rpl t t tpl))
19506 (when pkg (setq end
19507 (concat end "\n"
19508 (org-latex-packages-to-string pkg snippets-p)))))
19510 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19511 (setq rpl (if (or (match-end 1) (not extra))
19512 "" (concat extra "\n"))
19513 tpl (replace-match rpl t t tpl))
19514 (when (and extra (string-match "\\S-" extra))
19515 (setq end (concat end "\n" extra))))
19517 (if (string-match "\\S-" end)
19518 (concat tpl "\n" end)
19519 tpl)))
19521 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19522 "Turn an alist of packages into a string with the \\usepackage macros."
19523 (setq pkg (mapconcat (lambda(p)
19524 (cond
19525 ((stringp p) p)
19526 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19527 (format "%% Package %s omitted" (cadr p)))
19528 ((equal "" (car p))
19529 (format "\\usepackage{%s}" (cadr p)))
19531 (format "\\usepackage[%s]{%s}"
19532 (car p) (cadr p)))))
19534 "\n"))
19535 (if newline (concat pkg "\n") pkg))
19537 (defun org-dvipng-color (attr)
19538 "Return a RGB color specification for dvipng."
19539 (org-dvipng-color-format (face-attribute 'default attr nil)))
19541 (defun org-dvipng-color-format (color-name)
19542 "Convert COLOR-NAME to a RGB color value for dvipng."
19543 (apply #'format "rgb %s %s %s"
19544 (mapcar 'org-normalize-color
19545 (color-values color-name))))
19547 (defun org-latex-color (attr)
19548 "Return a RGB color for the LaTeX color package."
19549 (org-latex-color-format (face-attribute 'default attr nil)))
19551 (defun org-latex-color-format (color-name)
19552 "Convert COLOR-NAME to a RGB color value."
19553 (apply #'format "%s,%s,%s"
19554 (mapcar 'org-normalize-color
19555 (color-values color-name))))
19557 (defun org-normalize-color (value)
19558 "Return string to be used as color value for an RGB component."
19559 (format "%g" (/ value 65535.0)))
19563 ;; Image display
19565 (defvar-local org-inline-image-overlays nil)
19567 (defun org-toggle-inline-images (&optional include-linked)
19568 "Toggle the display of inline images.
19569 INCLUDE-LINKED is passed to `org-display-inline-images'."
19570 (interactive "P")
19571 (if org-inline-image-overlays
19572 (progn
19573 (org-remove-inline-images)
19574 (when (called-interactively-p 'interactive)
19575 (message "Inline image display turned off")))
19576 (org-display-inline-images include-linked)
19577 (when (called-interactively-p 'interactive)
19578 (message (if org-inline-image-overlays
19579 (format "%d images displayed inline"
19580 (length org-inline-image-overlays))
19581 "No images to display inline")))))
19583 (defun org-redisplay-inline-images ()
19584 "Refresh the display of inline images."
19585 (interactive)
19586 (if (not org-inline-image-overlays)
19587 (org-toggle-inline-images)
19588 (org-toggle-inline-images)
19589 (org-toggle-inline-images)))
19591 (defun org-display-inline-images (&optional include-linked refresh beg end)
19592 "Display inline images.
19594 An inline image is a link which follows either of these
19595 conventions:
19597 1. Its path is a file with an extension matching return value
19598 from `image-file-name-regexp' and it has no contents.
19600 2. Its description consists in a single link of the previous
19601 type.
19603 When optional argument INCLUDE-LINKED is non-nil, also links with
19604 a text description part will be inlined. This can be nice for
19605 a quick look at those images, but it does not reflect what
19606 exported files will look like.
19608 When optional argument REFRESH is non-nil, refresh existing
19609 images between BEG and END. This will create new image displays
19610 only if necessary. BEG and END default to the buffer
19611 boundaries."
19612 (interactive "P")
19613 (when (display-graphic-p)
19614 (unless refresh
19615 (org-remove-inline-images)
19616 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19617 (org-with-wide-buffer
19618 (goto-char (or beg (point-min)))
19619 (let ((case-fold-search t)
19620 (file-extension-re (image-file-name-regexp)))
19621 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19622 (let ((link (save-match-data (org-element-context))))
19623 ;; Check if we're at an inline image.
19624 (when (and (equal (org-element-property :type link) "file")
19625 (or include-linked
19626 (not (org-element-property :contents-begin link)))
19627 (let ((parent (org-element-property :parent link)))
19628 (or (not (eq (org-element-type parent) 'link))
19629 (not (cdr (org-element-contents parent)))))
19630 (string-match-p file-extension-re
19631 (org-element-property :path link)))
19632 (let ((file (expand-file-name
19633 (org-link-unescape
19634 (org-element-property :path link)))))
19635 (when (file-exists-p file)
19636 (let ((width
19637 ;; Apply `org-image-actual-width' specifications.
19638 (cond
19639 ((not (image-type-available-p 'imagemagick)) nil)
19640 ((eq org-image-actual-width t) nil)
19641 ((listp org-image-actual-width)
19643 ;; First try to find a width among
19644 ;; attributes associated to the paragraph
19645 ;; containing link.
19646 (let ((paragraph
19647 (let ((e link))
19648 (while (and (setq e (org-element-property
19649 :parent e))
19650 (not (eq (org-element-type e)
19651 'paragraph))))
19652 e)))
19653 (when paragraph
19654 (save-excursion
19655 (goto-char (org-element-property :begin paragraph))
19656 (when
19657 (re-search-forward
19658 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19659 (org-element-property
19660 :post-affiliated paragraph)
19662 (string-to-number (match-string 1))))))
19663 ;; Otherwise, fall-back to provided number.
19664 (car org-image-actual-width)))
19665 ((numberp org-image-actual-width)
19666 org-image-actual-width)))
19667 (old (get-char-property-and-overlay
19668 (org-element-property :begin link)
19669 'org-image-overlay)))
19670 (if (and (car-safe old) refresh)
19671 (image-refresh (overlay-get (cdr old) 'display))
19672 (let ((image (create-image file
19673 (and width 'imagemagick)
19675 :width width)))
19676 (when image
19677 (let* ((link
19678 ;; If inline image is the description
19679 ;; of another link, be sure to
19680 ;; consider the latter as the one to
19681 ;; apply the overlay on.
19682 (let ((parent
19683 (org-element-property :parent link)))
19684 (if (eq (org-element-type parent) 'link)
19685 parent
19686 link)))
19687 (ov (make-overlay
19688 (org-element-property :begin link)
19689 (progn
19690 (goto-char
19691 (org-element-property :end link))
19692 (skip-chars-backward " \t")
19693 (point)))))
19694 (overlay-put ov 'display image)
19695 (overlay-put ov 'face 'default)
19696 (overlay-put ov 'org-image-overlay t)
19697 (overlay-put
19698 ov 'modification-hooks
19699 (list 'org-display-inline-remove-overlay))
19700 (push ov org-inline-image-overlays)))))))))))))))
19702 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19703 "Remove inline-display overlay if a corresponding region is modified."
19704 (let ((inhibit-modification-hooks t))
19705 (when (and ov after)
19706 (delete ov org-inline-image-overlays)
19707 (delete-overlay ov))))
19709 (defun org-remove-inline-images ()
19710 "Remove inline display of images."
19711 (interactive)
19712 (mapc #'delete-overlay org-inline-image-overlays)
19713 (setq org-inline-image-overlays nil))
19715 ;;;; Key bindings
19717 ;; Outline functions from `outline-mode-prefix-map'
19718 ;; that can be remapped in Org:
19719 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19720 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19721 (define-key org-mode-map [remap outline-forward-same-level]
19722 'org-forward-heading-same-level)
19723 (define-key org-mode-map [remap outline-backward-same-level]
19724 'org-backward-heading-same-level)
19725 (define-key org-mode-map [remap outline-show-branches]
19726 'org-kill-note-or-show-branches)
19727 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19728 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19729 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19730 (define-key org-mode-map [remap outline-next-visible-heading]
19731 'org-next-visible-heading)
19732 (define-key org-mode-map [remap outline-previous-visible-heading]
19733 'org-previous-visible-heading)
19734 (define-key org-mode-map [remap show-children] 'org-show-children)
19736 ;; Outline functions from `outline-mode-prefix-map' that can not
19737 ;; be remapped in Org:
19739 ;; - the column "key binding" shows whether the Outline function is still
19740 ;; available in Org mode on the same key that it has been bound to in
19741 ;; Outline mode:
19742 ;; - "overridden": key used for a different functionality in Org mode
19743 ;; - else: key still bound to the same Outline function in Org mode
19745 ;; | Outline function | key binding | Org replacement |
19746 ;; |------------------------------------+-------------+--------------------------|
19747 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19748 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19749 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19750 ;; | `show-entry' | overridden | no replacement |
19751 ;; | `show-branches' | `C-c C-k' | still same function |
19752 ;; | `show-subtree' | overridden | visibility cycling |
19753 ;; | `show-all' | overridden | no replacement |
19754 ;; | `hide-subtree' | overridden | visibility cycling |
19755 ;; | `hide-body' | overridden | no replacement |
19756 ;; | `hide-entry' | overridden | visibility cycling |
19757 ;; | `hide-leaves' | overridden | no replacement |
19758 ;; | `hide-sublevels' | overridden | no replacement |
19759 ;; | `hide-other' | overridden | no replacement |
19761 ;; Make `C-c C-x' a prefix key
19762 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19764 ;; TAB key with modifiers
19765 (org-defkey org-mode-map "\C-i" 'org-cycle)
19766 (org-defkey org-mode-map [(tab)] 'org-cycle)
19767 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19768 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19769 ;; The following line is necessary under Suse GNU/Linux
19770 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19771 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19772 (define-key org-mode-map [backtab] 'org-shifttab)
19774 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19775 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19776 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19778 ;; Cursor keys with modifiers
19779 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19780 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19781 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19782 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19784 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19785 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19786 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19787 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19788 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19789 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19791 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19792 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19793 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19794 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19796 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19797 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19798 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19799 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19801 ;; Babel keys
19802 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19803 (dolist (pair org-babel-key-bindings)
19804 (define-key org-babel-map (car pair) (cdr pair)))
19806 ;;; Extra keys for tty access.
19807 ;; We only set them when really needed because otherwise the
19808 ;; menus don't show the simple keys
19810 (when (or org-use-extra-keys (not window-system))
19811 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19812 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19813 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19814 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19815 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19816 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19817 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19818 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19819 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19820 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19821 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19822 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19823 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19824 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19825 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19826 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19827 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19828 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19829 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19830 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19831 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19832 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19833 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19834 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19835 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19836 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19837 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19838 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19840 ;; All the other keys
19842 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19843 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19844 (if (boundp 'narrow-map)
19845 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19846 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19847 (if (boundp 'narrow-map)
19848 (org-defkey narrow-map "b" 'org-narrow-to-block)
19849 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19850 (if (boundp 'narrow-map)
19851 (org-defkey narrow-map "e" 'org-narrow-to-element)
19852 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19853 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19854 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19855 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19856 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19857 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19858 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19859 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19860 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19861 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19862 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19863 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19864 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19865 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19866 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19867 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19868 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19869 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19870 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19871 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19872 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19873 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19874 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19875 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19876 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19877 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19878 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19879 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19880 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19881 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19882 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19883 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19884 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19885 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19886 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19887 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19888 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19889 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19890 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19891 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19892 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19893 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19894 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19895 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19896 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19897 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19898 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19899 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19900 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19901 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19902 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19903 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19904 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19905 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19906 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19907 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19908 (org-defkey org-mode-map "\C-c^" 'org-sort)
19909 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19910 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19911 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19912 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19913 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19914 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19915 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19916 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19917 (org-defkey org-mode-map "\C-m" 'org-return)
19918 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19919 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19920 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19921 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19922 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19923 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19924 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19925 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19926 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19927 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19928 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19929 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19930 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19931 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19932 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19933 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19934 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19935 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19936 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19937 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19938 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19939 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19940 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19941 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19942 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19944 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19945 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19946 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19948 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19949 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19950 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19951 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19952 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19953 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19954 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19955 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19956 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19957 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19958 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19959 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19960 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19961 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19962 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19963 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19964 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19965 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19966 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19967 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19968 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19969 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19971 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19972 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19973 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19974 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19975 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19977 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19979 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19981 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19982 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19984 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19987 (defconst org-speed-commands-default
19989 ("Outline Navigation")
19990 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19991 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19992 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19993 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19994 ("F" . org-next-block)
19995 ("B" . org-previous-block)
19996 ("u" . (org-speed-move-safe 'outline-up-heading))
19997 ("j" . org-goto)
19998 ("g" . (org-refile t))
19999 ("Outline Visibility")
20000 ("c" . org-cycle)
20001 ("C" . org-shifttab)
20002 (" " . org-display-outline-path)
20003 ("s" . org-narrow-to-subtree)
20004 ("=" . org-columns)
20005 ("Outline Structure Editing")
20006 ("U" . org-metaup)
20007 ("D" . org-metadown)
20008 ("r" . org-metaright)
20009 ("l" . org-metaleft)
20010 ("R" . org-shiftmetaright)
20011 ("L" . org-shiftmetaleft)
20012 ("i" . (progn (forward-char 1) (call-interactively
20013 'org-insert-heading-respect-content)))
20014 ("^" . org-sort)
20015 ("w" . org-refile)
20016 ("a" . org-archive-subtree-default-with-confirmation)
20017 ("@" . org-mark-subtree)
20018 ("#" . org-toggle-comment)
20019 ("Clock Commands")
20020 ("I" . org-clock-in)
20021 ("O" . org-clock-out)
20022 ("Meta Data Editing")
20023 ("t" . org-todo)
20024 ("," . (org-priority))
20025 ("0" . (org-priority ?\ ))
20026 ("1" . (org-priority ?A))
20027 ("2" . (org-priority ?B))
20028 ("3" . (org-priority ?C))
20029 (":" . org-set-tags-command)
20030 ("e" . org-set-effort)
20031 ("E" . org-inc-effort)
20032 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20033 (org-entry-put (point) "APPT_WARNTIME" m)))
20034 ("Agenda Views etc")
20035 ("v" . org-agenda)
20036 ("/" . org-sparse-tree)
20037 ("Misc")
20038 ("o" . org-open-at-point)
20039 ("?" . org-speed-command-help)
20040 ("<" . (org-agenda-set-restriction-lock 'subtree))
20041 (">" . (org-agenda-remove-restriction-lock))
20043 "The default speed commands.")
20045 (defun org-print-speed-command (e)
20046 (if (> (length (car e)) 1)
20047 (progn
20048 (princ "\n")
20049 (princ (car e))
20050 (princ "\n")
20051 (princ (make-string (length (car e)) ?-))
20052 (princ "\n"))
20053 (princ (car e))
20054 (princ " ")
20055 (if (symbolp (cdr e))
20056 (princ (symbol-name (cdr e)))
20057 (prin1 (cdr e)))
20058 (princ "\n")))
20060 (defun org-speed-command-help ()
20061 "Show the available speed commands."
20062 (interactive)
20063 (if (not org-use-speed-commands)
20064 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20065 (with-output-to-temp-buffer "*Help*"
20066 (princ "User-defined Speed commands\n===========================\n")
20067 (mapc #'org-print-speed-command org-speed-commands-user)
20068 (princ "\n")
20069 (princ "Built-in Speed commands\n=======================\n")
20070 (mapc #'org-print-speed-command org-speed-commands-default))
20071 (with-current-buffer "*Help*"
20072 (setq truncate-lines t))))
20074 (defun org-speed-move-safe (cmd)
20075 "Execute CMD, but make sure that the cursor always ends up in a headline.
20076 If not, return to the original position and throw an error."
20077 (interactive)
20078 (let ((pos (point)))
20079 (call-interactively cmd)
20080 (unless (and (bolp) (org-at-heading-p))
20081 (goto-char pos)
20082 (error "Boundary reached while executing %s" cmd))))
20084 (defvar org-self-insert-command-undo-counter 0)
20086 (defvar org-table-auto-blank-field) ; defined in org-table.el
20087 (defvar org-speed-command nil)
20089 (defun org-speed-command-activate (keys)
20090 "Hook for activating single-letter speed commands.
20091 `org-speed-commands-default' specifies a minimal command set.
20092 Use `org-speed-commands-user' for further customization."
20093 (when (or (and (bolp) (looking-at org-outline-regexp))
20094 (and (functionp org-use-speed-commands)
20095 (funcall org-use-speed-commands)))
20096 (cdr (assoc keys (append org-speed-commands-user
20097 org-speed-commands-default)))))
20099 (defun org-babel-speed-command-activate (keys)
20100 "Hook for activating single-letter code block commands."
20101 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20102 (cdr (assoc keys org-babel-key-bindings))))
20104 (defcustom org-speed-command-hook
20105 '(org-speed-command-activate org-babel-speed-command-activate)
20106 "Hook for activating speed commands at strategic locations.
20107 Hook functions are called in sequence until a valid handler is
20108 found.
20110 Each hook takes a single argument, a user-pressed command key
20111 which is also a `self-insert-command' from the global map.
20113 Within the hook, examine the cursor position and the command key
20114 and return nil or a valid handler as appropriate. Handler could
20115 be one of an interactive command, a function, or a form.
20117 Set `org-use-speed-commands' to non-nil value to enable this
20118 hook. The default setting is `org-speed-command-activate'."
20119 :group 'org-structure
20120 :version "24.1"
20121 :type 'hook)
20123 (defun org-self-insert-command (N)
20124 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20125 If the cursor is in a table looking at whitespace, the whitespace is
20126 overwritten, and the table is not marked as requiring realignment."
20127 (interactive "p")
20128 (org-check-before-invisible-edit 'insert)
20129 (cond
20130 ((and org-use-speed-commands
20131 (let ((kv (this-command-keys-vector)))
20132 (setq org-speed-command
20133 (run-hook-with-args-until-success
20134 'org-speed-command-hook
20135 (make-string 1 (aref kv (1- (length kv))))))))
20136 (cond
20137 ((commandp org-speed-command)
20138 (setq this-command org-speed-command)
20139 (call-interactively org-speed-command))
20140 ((functionp org-speed-command)
20141 (funcall org-speed-command))
20142 ((and org-speed-command (listp org-speed-command))
20143 (eval org-speed-command))
20144 (t (let (org-use-speed-commands)
20145 (call-interactively 'org-self-insert-command)))))
20146 ((and
20147 (org-at-table-p)
20148 (progn
20149 ;; Check if we blank the field, and if that triggers align.
20150 (and (featurep 'org-table) org-table-auto-blank-field
20151 (memq last-command
20152 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20153 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20154 ;; Got extra space, this field does not determine
20155 ;; column width.
20156 (let (org-table-may-need-update) (org-table-blank-field))
20157 ;; No extra space, this field may determine column
20158 ;; width.
20159 (org-table-blank-field)))
20161 (eq N 1)
20162 (looking-at "[^|\n]* \\( \\)|"))
20163 ;; There is room for insertion without re-aligning the table.
20164 (delete-region (match-beginning 1) (match-end 1))
20165 (self-insert-command N))
20167 (setq org-table-may-need-update t)
20168 (self-insert-command N)
20169 (org-fix-tags-on-the-fly)
20170 (when org-self-insert-cluster-for-undo
20171 (if (not (eq last-command 'org-self-insert-command))
20172 (setq org-self-insert-command-undo-counter 1)
20173 (if (>= org-self-insert-command-undo-counter 20)
20174 (setq org-self-insert-command-undo-counter 1)
20175 (and (> org-self-insert-command-undo-counter 0)
20176 buffer-undo-list (listp buffer-undo-list)
20177 (not (cadr buffer-undo-list)) ; remove nil entry
20178 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20179 (setq org-self-insert-command-undo-counter
20180 (1+ org-self-insert-command-undo-counter))))))))
20182 (defun org-check-before-invisible-edit (kind)
20183 "Check is editing if kind KIND would be dangerous with invisible text around.
20184 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20185 ;; First, try to get out of here as quickly as possible, to reduce overhead
20186 (when (and org-catch-invisible-edits
20187 (or (not (boundp 'visible-mode)) (not visible-mode))
20188 (or (get-char-property (point) 'invisible)
20189 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20190 ;; OK, we need to take a closer look
20191 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20192 (invisible-before-point (unless (bobp) (get-char-property
20193 (1- (point)) 'invisible)))
20194 (border-and-ok-direction
20196 ;; Check if we are acting predictably before invisible text
20197 (and invisible-at-point (not invisible-before-point)
20198 (memq kind '(insert delete-backward)))
20199 ;; Check if we are acting predictably after invisible text
20200 ;; This works not well, and I have turned it off. It seems
20201 ;; better to always show and stop after invisible text.
20202 ;; (and (not invisible-at-point) invisible-before-point
20203 ;; (memq kind '(insert delete)))
20205 (when (or (memq invisible-at-point '(outline org-hide-block t))
20206 (memq invisible-before-point '(outline org-hide-block t)))
20207 (when (eq org-catch-invisible-edits 'error)
20208 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20209 (if (and org-custom-properties-overlays
20210 (y-or-n-p "Display invisible properties in this buffer? "))
20211 (org-toggle-custom-properties-visibility)
20212 ;; Make the area visible
20213 (save-excursion
20214 (when invisible-before-point
20215 (goto-char (previous-single-char-property-change
20216 (point) 'invisible)))
20217 (outline-show-subtree))
20218 (cond
20219 ((eq org-catch-invisible-edits 'show)
20220 ;; That's it, we do the edit after showing
20221 (message
20222 "Unfolding invisible region around point before editing")
20223 (sit-for 1))
20224 ((and (eq org-catch-invisible-edits 'smart)
20225 border-and-ok-direction)
20226 (message "Unfolding invisible region around point before editing"))
20228 ;; Don't do the edit, make the user repeat it in full visibility
20229 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20231 (defun org-fix-tags-on-the-fly ()
20232 "Align tags in headline at point.
20233 Unlike to `org-set-tags', it ignores region and sorting."
20234 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20235 (org-at-heading-p))
20236 (let ((org-ignore-region t)
20237 (org-tags-sort-function nil))
20238 (org-set-tags nil t))))
20240 (defun org-delete-backward-char (N)
20241 "Like `delete-backward-char', insert whitespace at field end in tables.
20242 When deleting backwards, in tables this function will insert whitespace in
20243 front of the next \"|\" separator, to keep the table aligned. The table will
20244 still be marked for re-alignment if the field did fill the entire column,
20245 because, in this case the deletion might narrow the column."
20246 (interactive "p")
20247 (save-match-data
20248 (org-check-before-invisible-edit 'delete-backward)
20249 (if (and (org-at-table-p)
20250 (eq N 1)
20251 (string-match "|" (buffer-substring (point-at-bol) (point)))
20252 (looking-at ".*?|"))
20253 (let ((pos (point))
20254 (noalign (looking-at "[^|\n\r]* |"))
20255 (c org-table-may-need-update))
20256 (backward-delete-char N)
20257 (unless overwrite-mode
20258 (skip-chars-forward "^|")
20259 (insert " ")
20260 (goto-char (1- pos)))
20261 ;; noalign: if there were two spaces at the end, this field
20262 ;; does not determine the width of the column.
20263 (when noalign (setq org-table-may-need-update c)))
20264 (backward-delete-char N)
20265 (org-fix-tags-on-the-fly))))
20267 (defun org-delete-char (N)
20268 "Like `delete-char', but insert whitespace at field end in tables.
20269 When deleting characters, in tables this function will insert whitespace in
20270 front of the next \"|\" separator, to keep the table aligned. The table will
20271 still be marked for re-alignment if the field did fill the entire column,
20272 because, in this case the deletion might narrow the column."
20273 (interactive "p")
20274 (save-match-data
20275 (org-check-before-invisible-edit 'delete)
20276 (if (and (org-at-table-p)
20277 (not (bolp))
20278 (not (= (char-after) ?|))
20279 (eq N 1))
20280 (if (looking-at ".*?|")
20281 (let ((pos (point))
20282 (noalign (looking-at "[^|\n\r]* |"))
20283 (c org-table-may-need-update))
20284 (replace-match
20285 (concat (substring (match-string 0) 1 -1) " |") nil t)
20286 (goto-char pos)
20287 ;; noalign: if there were two spaces at the end, this field
20288 ;; does not determine the width of the column.
20289 (when noalign (setq org-table-may-need-update c)))
20290 (delete-char N))
20291 (delete-char N)
20292 (org-fix-tags-on-the-fly))))
20294 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20295 (put 'org-self-insert-command 'delete-selection
20296 (lambda ()
20297 (not (run-hook-with-args-until-success
20298 'self-insert-uses-region-functions))))
20299 (put 'orgtbl-self-insert-command 'delete-selection
20300 (lambda ()
20301 (not (run-hook-with-args-until-success
20302 'self-insert-uses-region-functions))))
20303 (put 'org-delete-char 'delete-selection 'supersede)
20304 (put 'org-delete-backward-char 'delete-selection 'supersede)
20305 (put 'org-yank 'delete-selection 'yank)
20307 ;; Make `flyspell-mode' delay after some commands
20308 (put 'org-self-insert-command 'flyspell-delayed t)
20309 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20310 (put 'org-delete-char 'flyspell-delayed t)
20311 (put 'org-delete-backward-char 'flyspell-delayed t)
20313 ;; Make pabbrev-mode expand after Org mode commands
20314 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20315 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20317 (defun org-remap (map &rest commands)
20318 "In MAP, remap the functions given in COMMANDS.
20319 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20320 (let (new old)
20321 (while commands
20322 (setq old (pop commands) new (pop commands))
20323 (org-defkey map (vector 'remap old) new))))
20325 (defun org-transpose-words ()
20326 "Transpose words for Org.
20327 This uses the `org-mode-transpose-word-syntax-table' syntax
20328 table, which interprets characters in `org-emphasis-alist' as
20329 word constituents."
20330 (interactive)
20331 (with-syntax-table org-mode-transpose-word-syntax-table
20332 (call-interactively 'transpose-words)))
20333 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20335 (when (eq org-enable-table-editor 'optimized)
20336 ;; If the user wants maximum table support, we need to hijack
20337 ;; some standard editing functions
20338 (org-remap org-mode-map
20339 'self-insert-command 'org-self-insert-command
20340 'delete-char 'org-delete-char
20341 'delete-backward-char 'org-delete-backward-char)
20342 (org-defkey org-mode-map "|" 'org-force-self-insert))
20344 (defvar org-ctrl-c-ctrl-c-hook nil
20345 "Hook for functions attaching themselves to `C-c C-c'.
20347 This can be used to add additional functionality to the C-c C-c
20348 key which executes context-dependent commands. This hook is run
20349 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20350 run after the last test.
20352 Each function will be called with no arguments. The function
20353 must check if the context is appropriate for it to act. If yes,
20354 it should do its thing and then return a non-nil value. If the
20355 context is wrong, just do nothing and return nil.")
20357 (defvar org-ctrl-c-ctrl-c-final-hook nil
20358 "Hook for functions attaching themselves to `C-c C-c'.
20360 This can be used to add additional functionality to the C-c C-c
20361 key which executes context-dependent commands. This hook is run
20362 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20363 before the first test.
20365 Each function will be called with no arguments. The function
20366 must check if the context is appropriate for it to act. If yes,
20367 it should do its thing and then return a non-nil value. If the
20368 context is wrong, just do nothing and return nil.")
20370 (defvar org-tab-first-hook nil
20371 "Hook for functions to attach themselves to TAB.
20372 See `org-ctrl-c-ctrl-c-hook' for more information.
20373 This hook runs as the first action when TAB is pressed, even before
20374 `org-cycle' messes around with the `outline-regexp' to cater for
20375 inline tasks and plain list item folding.
20376 If any function in this hook returns t, any other actions that
20377 would have been caused by TAB (such as table field motion or visibility
20378 cycling) will not occur.")
20380 (defvar org-tab-after-check-for-table-hook nil
20381 "Hook for functions to attach themselves to TAB.
20382 See `org-ctrl-c-ctrl-c-hook' for more information.
20383 This hook runs after it has been established that the cursor is not in a
20384 table, but before checking if the cursor is in a headline or if global cycling
20385 should be done.
20386 If any function in this hook returns t, not other actions like visibility
20387 cycling will be done.")
20389 (defvar org-tab-after-check-for-cycling-hook nil
20390 "Hook for functions to attach themselves to TAB.
20391 See `org-ctrl-c-ctrl-c-hook' for more information.
20392 This hook runs after it has been established that not table field motion and
20393 not visibility should be done because of current context. This is probably
20394 the place where a package like yasnippets can hook in.")
20396 (defvar org-tab-before-tab-emulation-hook nil
20397 "Hook for functions to attach themselves to TAB.
20398 See `org-ctrl-c-ctrl-c-hook' for more information.
20399 This hook runs after every other options for TAB have been exhausted, but
20400 before indentation and \t insertion takes place.")
20402 (defvar org-metaleft-hook nil
20403 "Hook for functions attaching themselves to `M-left'.
20404 See `org-ctrl-c-ctrl-c-hook' for more information.")
20405 (defvar org-metaright-hook nil
20406 "Hook for functions attaching themselves to `M-right'.
20407 See `org-ctrl-c-ctrl-c-hook' for more information.")
20408 (defvar org-metaup-hook nil
20409 "Hook for functions attaching themselves to `M-up'.
20410 See `org-ctrl-c-ctrl-c-hook' for more information.")
20411 (defvar org-metadown-hook nil
20412 "Hook for functions attaching themselves to `M-down'.
20413 See `org-ctrl-c-ctrl-c-hook' for more information.")
20414 (defvar org-shiftmetaleft-hook nil
20415 "Hook for functions attaching themselves to `M-S-left'.
20416 See `org-ctrl-c-ctrl-c-hook' for more information.")
20417 (defvar org-shiftmetaright-hook nil
20418 "Hook for functions attaching themselves to `M-S-right'.
20419 See `org-ctrl-c-ctrl-c-hook' for more information.")
20420 (defvar org-shiftmetaup-hook nil
20421 "Hook for functions attaching themselves to `M-S-up'.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.")
20423 (defvar org-shiftmetadown-hook nil
20424 "Hook for functions attaching themselves to `M-S-down'.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20426 (defvar org-metareturn-hook nil
20427 "Hook for functions attaching themselves to `M-RET'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-shiftup-hook nil
20430 "Hook for functions attaching themselves to `S-up'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-shiftup-final-hook nil
20433 "Hook for functions attaching themselves to `S-up'.
20434 This one runs after all other options except shift-select have been excluded.
20435 See `org-ctrl-c-ctrl-c-hook' for more information.")
20436 (defvar org-shiftdown-hook nil
20437 "Hook for functions attaching themselves to `S-down'.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.")
20439 (defvar org-shiftdown-final-hook nil
20440 "Hook for functions attaching themselves to `S-down'.
20441 This one runs after all other options except shift-select have been excluded.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftleft-hook nil
20444 "Hook for functions attaching themselves to `S-left'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftleft-final-hook nil
20447 "Hook for functions attaching themselves to `S-left'.
20448 This one runs after all other options except shift-select have been excluded.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-shiftright-hook nil
20451 "Hook for functions attaching themselves to `S-right'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftright-final-hook nil
20454 "Hook for functions attaching themselves to `S-right'.
20455 This one runs after all other options except shift-select have been excluded.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defun org-modifier-cursor-error ()
20459 "Throw an error, a modified cursor command was applied in wrong context."
20460 (user-error "This command is active in special context like tables, headlines or items"))
20462 (defun org-shiftselect-error ()
20463 "Throw an error because Shift-Cursor command was applied in wrong context."
20464 (if (and (boundp 'shift-select-mode) shift-select-mode)
20465 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20466 (user-error "This command works only in special context like headlines or timestamps")))
20468 (defun org-call-for-shift-select (cmd)
20469 (let ((this-command-keys-shift-translated t))
20470 (call-interactively cmd)))
20472 (defun org-shifttab (&optional arg)
20473 "Global visibility cycling or move to previous table field.
20474 Call `org-table-previous-field' within a table.
20475 When ARG is nil, cycle globally through visibility states.
20476 When ARG is a numeric prefix, show contents of this level."
20477 (interactive "P")
20478 (cond
20479 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20480 ((integerp arg)
20481 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20482 (message "Content view to level: %d" arg)
20483 (org-content (prefix-numeric-value arg2))
20484 (org-cycle-show-empty-lines t)
20485 (setq org-cycle-global-status 'overview)))
20486 (t (call-interactively 'org-global-cycle))))
20488 (defun org-shiftmetaleft ()
20489 "Promote subtree or delete table column.
20490 Calls `org-promote-subtree', `org-outdent-item-tree', or
20491 `org-table-delete-column', depending on context. See the
20492 individual commands for more information."
20493 (interactive)
20494 (cond
20495 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20496 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20497 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20498 ((if (not (org-region-active-p)) (org-at-item-p)
20499 (save-excursion (goto-char (region-beginning))
20500 (org-at-item-p)))
20501 (call-interactively 'org-outdent-item-tree))
20502 (t (org-modifier-cursor-error))))
20504 (defun org-shiftmetaright ()
20505 "Demote subtree or insert table column.
20506 Calls `org-demote-subtree', `org-indent-item-tree', or
20507 `org-table-insert-column', depending on context. See the
20508 individual commands for more information."
20509 (interactive)
20510 (cond
20511 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20512 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20513 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20514 ((if (not (org-region-active-p)) (org-at-item-p)
20515 (save-excursion (goto-char (region-beginning))
20516 (org-at-item-p)))
20517 (call-interactively 'org-indent-item-tree))
20518 (t (org-modifier-cursor-error))))
20520 (defun org-shiftmetaup (&optional _arg)
20521 "Drag the line at point up.
20522 In a table, kill the current row.
20523 On a clock timestamp, update the value of the timestamp like `S-<up>'
20524 but also adjust the previous clocked item in the clock history.
20525 Everywhere else, drag the line at point up."
20526 (interactive "P")
20527 (cond
20528 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20529 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20530 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20531 (call-interactively 'org-timestamp-up)))
20532 (t (call-interactively 'org-drag-line-backward))))
20534 (defun org-shiftmetadown (&optional _arg)
20535 "Drag the line at point down.
20536 In a table, insert an empty row at the current line.
20537 On a clock timestamp, update the value of the timestamp like `S-<down>'
20538 but also adjust the previous clocked item in the clock history.
20539 Everywhere else, drag the line at point down."
20540 (interactive "P")
20541 (cond
20542 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20543 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20544 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20545 (call-interactively 'org-timestamp-down)))
20546 (t (call-interactively 'org-drag-line-forward))))
20548 (defsubst org-hidden-tree-error ()
20549 (user-error
20550 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20552 (defun org-metaleft (&optional _arg)
20553 "Promote heading, list item at point or move table column left.
20555 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20556 depending on context. With no specific context, calls the Emacs
20557 default `backward-word'. See the individual commands for more
20558 information.
20560 This function runs the hook `org-metaleft-hook' as a first step,
20561 and returns at first non-nil value."
20562 (interactive "P")
20563 (cond
20564 ((run-hook-with-args-until-success 'org-metaleft-hook))
20565 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20566 ((org-with-limited-levels
20567 (or (org-at-heading-p)
20568 (and (org-region-active-p)
20569 (save-excursion
20570 (goto-char (region-beginning))
20571 (org-at-heading-p)))))
20572 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20573 (call-interactively 'org-do-promote))
20574 ;; At an inline task.
20575 ((org-at-heading-p)
20576 (call-interactively 'org-inlinetask-promote))
20577 ((or (org-at-item-p)
20578 (and (org-region-active-p)
20579 (save-excursion
20580 (goto-char (region-beginning))
20581 (org-at-item-p))))
20582 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20583 (call-interactively 'org-outdent-item))
20584 (t (call-interactively 'backward-word))))
20586 (defun org-metaright (&optional _arg)
20587 "Demote heading, list item at point or move table column right.
20589 In front of a drawer or a block keyword, indent it correctly.
20591 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20592 `org-indent-drawer' or `org-indent-block' depending on context.
20593 With no specific context, calls the Emacs default `forward-word'.
20594 See the individual commands for more information.
20596 This function runs the hook `org-metaright-hook' as a first step,
20597 and returns at first non-nil value."
20598 (interactive "P")
20599 (cond
20600 ((run-hook-with-args-until-success 'org-metaright-hook))
20601 ((org-at-table-p) (call-interactively 'org-table-move-column))
20602 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20603 ((org-at-block-p) (call-interactively 'org-indent-block))
20604 ((org-with-limited-levels
20605 (or (org-at-heading-p)
20606 (and (org-region-active-p)
20607 (save-excursion
20608 (goto-char (region-beginning))
20609 (org-at-heading-p)))))
20610 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20611 (call-interactively 'org-do-demote))
20612 ;; At an inline task.
20613 ((org-at-heading-p)
20614 (call-interactively 'org-inlinetask-demote))
20615 ((or (org-at-item-p)
20616 (and (org-region-active-p)
20617 (save-excursion
20618 (goto-char (region-beginning))
20619 (org-at-item-p))))
20620 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20621 (call-interactively 'org-indent-item))
20622 (t (call-interactively 'forward-word))))
20624 (defun org-check-for-hidden (what)
20625 "Check if there are hidden headlines/items in the current visual line.
20626 WHAT can be either `headlines' or `items'. If the current line is
20627 an outline or item heading and it has a folded subtree below it,
20628 this function returns t, nil otherwise."
20629 (let ((re (cond
20630 ((eq what 'headlines) org-outline-regexp-bol)
20631 ((eq what 'items) (org-item-beginning-re))
20632 (t (error "This should not happen"))))
20633 beg end)
20634 (save-excursion
20635 (catch 'exit
20636 (unless (org-region-active-p)
20637 (setq beg (point-at-bol))
20638 (beginning-of-line 2)
20639 (while (and (not (eobp)) ;; this is like `next-line'
20640 (get-char-property (1- (point)) 'invisible))
20641 (beginning-of-line 2))
20642 (setq end (point))
20643 (goto-char beg)
20644 (goto-char (point-at-eol))
20645 (setq end (max end (point)))
20646 (while (re-search-forward re end t)
20647 (when (get-char-property (match-beginning 0) 'invisible)
20648 (throw 'exit t))))
20649 nil))))
20651 (defun org-metaup (&optional _arg)
20652 "Move subtree up or move table row up.
20653 Calls `org-move-subtree-up' or `org-table-move-row' or
20654 `org-move-item-up', depending on context. See the individual commands
20655 for more information."
20656 (interactive "P")
20657 (cond
20658 ((run-hook-with-args-until-success 'org-metaup-hook))
20659 ((org-region-active-p)
20660 (let* ((a (min (region-beginning) (region-end)))
20661 (b (1- (max (region-beginning) (region-end))))
20662 (c (save-excursion (goto-char a)
20663 (move-beginning-of-line 0)))
20664 (d (save-excursion (goto-char a)
20665 (move-end-of-line 0) (point))))
20666 (transpose-regions a b c d)
20667 (goto-char c)))
20668 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20669 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20670 ((org-at-item-p) (call-interactively 'org-move-item-up))
20671 (t (org-drag-element-backward))))
20673 (defun org-metadown (&optional _arg)
20674 "Move subtree down or move table row down.
20675 Calls `org-move-subtree-down' or `org-table-move-row' or
20676 `org-move-item-down', depending on context. See the individual
20677 commands for more information."
20678 (interactive "P")
20679 (cond
20680 ((run-hook-with-args-until-success 'org-metadown-hook))
20681 ((org-region-active-p)
20682 (let* ((a (min (region-beginning) (region-end)))
20683 (b (max (region-beginning) (region-end)))
20684 (c (save-excursion (goto-char b)
20685 (move-beginning-of-line 1)))
20686 (d (save-excursion (goto-char b)
20687 (move-end-of-line 1) (1+ (point)))))
20688 (transpose-regions a b c d)
20689 (goto-char d)))
20690 ((org-at-table-p) (call-interactively 'org-table-move-row))
20691 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20692 ((org-at-item-p) (call-interactively 'org-move-item-down))
20693 (t (org-drag-element-forward))))
20695 (defun org-shiftup (&optional arg)
20696 "Increase item in timestamp or increase priority of current headline.
20697 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20698 depending on context. See the individual commands for more information."
20699 (interactive "P")
20700 (cond
20701 ((run-hook-with-args-until-success 'org-shiftup-hook))
20702 ((and org-support-shift-select (org-region-active-p))
20703 (org-call-for-shift-select 'previous-line))
20704 ((org-at-timestamp-p t)
20705 (call-interactively (if org-edit-timestamp-down-means-later
20706 'org-timestamp-down 'org-timestamp-up)))
20707 ((and (not (eq org-support-shift-select 'always))
20708 org-enable-priority-commands
20709 (org-at-heading-p))
20710 (call-interactively 'org-priority-up))
20711 ((and (not org-support-shift-select) (org-at-item-p))
20712 (call-interactively 'org-previous-item))
20713 ((org-clocktable-try-shift 'up arg))
20714 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20715 (org-support-shift-select
20716 (org-call-for-shift-select 'previous-line))
20717 (t (org-shiftselect-error))))
20719 (defun org-shiftdown (&optional arg)
20720 "Decrease item in timestamp or decrease priority of current headline.
20721 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20722 depending on context. See the individual commands for more information."
20723 (interactive "P")
20724 (cond
20725 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20726 ((and org-support-shift-select (org-region-active-p))
20727 (org-call-for-shift-select 'next-line))
20728 ((org-at-timestamp-p t)
20729 (call-interactively (if org-edit-timestamp-down-means-later
20730 'org-timestamp-up 'org-timestamp-down)))
20731 ((and (not (eq org-support-shift-select 'always))
20732 org-enable-priority-commands
20733 (org-at-heading-p))
20734 (call-interactively 'org-priority-down))
20735 ((and (not org-support-shift-select) (org-at-item-p))
20736 (call-interactively 'org-next-item))
20737 ((org-clocktable-try-shift 'down arg))
20738 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20739 (org-support-shift-select
20740 (org-call-for-shift-select 'next-line))
20741 (t (org-shiftselect-error))))
20743 (defun org-shiftright (&optional arg)
20744 "Cycle the thing at point or in the current line, depending on context.
20745 Depending on context, this does one of the following:
20747 - switch a timestamp at point one day into the future
20748 - on a headline, switch to the next TODO keyword.
20749 - on an item, switch entire list to the next bullet type
20750 - on a property line, switch to the next allowed value
20751 - on a clocktable definition line, move time block into the future"
20752 (interactive "P")
20753 (cond
20754 ((run-hook-with-args-until-success 'org-shiftright-hook))
20755 ((and org-support-shift-select (org-region-active-p))
20756 (org-call-for-shift-select 'forward-char))
20757 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20758 ((and (not (eq org-support-shift-select 'always))
20759 (org-at-heading-p))
20760 (let ((org-inhibit-logging
20761 (not org-treat-S-cursor-todo-selection-as-state-change))
20762 (org-inhibit-blocking
20763 (not org-treat-S-cursor-todo-selection-as-state-change)))
20764 (org-call-with-arg 'org-todo 'right)))
20765 ((or (and org-support-shift-select
20766 (not (eq org-support-shift-select 'always))
20767 (org-at-item-bullet-p))
20768 (and (not org-support-shift-select) (org-at-item-p)))
20769 (org-call-with-arg 'org-cycle-list-bullet nil))
20770 ((and (not (eq org-support-shift-select 'always))
20771 (org-at-property-p))
20772 (call-interactively 'org-property-next-allowed-value))
20773 ((org-clocktable-try-shift 'right arg))
20774 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20775 (org-support-shift-select
20776 (org-call-for-shift-select 'forward-char))
20777 (t (org-shiftselect-error))))
20779 (defun org-shiftleft (&optional arg)
20780 "Cycle the thing at point or in the current line, depending on context.
20781 Depending on context, this does one of the following:
20783 - switch a timestamp at point one day into the past
20784 - on a headline, switch to the previous TODO keyword.
20785 - on an item, switch entire list to the previous bullet type
20786 - on a property line, switch to the previous allowed value
20787 - on a clocktable definition line, move time block into the past"
20788 (interactive "P")
20789 (cond
20790 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20791 ((and org-support-shift-select (org-region-active-p))
20792 (org-call-for-shift-select 'backward-char))
20793 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20794 ((and (not (eq org-support-shift-select 'always))
20795 (org-at-heading-p))
20796 (let ((org-inhibit-logging
20797 (not org-treat-S-cursor-todo-selection-as-state-change))
20798 (org-inhibit-blocking
20799 (not org-treat-S-cursor-todo-selection-as-state-change)))
20800 (org-call-with-arg 'org-todo 'left)))
20801 ((or (and org-support-shift-select
20802 (not (eq org-support-shift-select 'always))
20803 (org-at-item-bullet-p))
20804 (and (not org-support-shift-select) (org-at-item-p)))
20805 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20806 ((and (not (eq org-support-shift-select 'always))
20807 (org-at-property-p))
20808 (call-interactively 'org-property-previous-allowed-value))
20809 ((org-clocktable-try-shift 'left arg))
20810 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20811 (org-support-shift-select
20812 (org-call-for-shift-select 'backward-char))
20813 (t (org-shiftselect-error))))
20815 (defun org-shiftcontrolright ()
20816 "Switch to next TODO set."
20817 (interactive)
20818 (cond
20819 ((and org-support-shift-select (org-region-active-p))
20820 (org-call-for-shift-select 'forward-word))
20821 ((and (not (eq org-support-shift-select 'always))
20822 (org-at-heading-p))
20823 (org-call-with-arg 'org-todo 'nextset))
20824 (org-support-shift-select
20825 (org-call-for-shift-select 'forward-word))
20826 (t (org-shiftselect-error))))
20828 (defun org-shiftcontrolleft ()
20829 "Switch to previous TODO set."
20830 (interactive)
20831 (cond
20832 ((and org-support-shift-select (org-region-active-p))
20833 (org-call-for-shift-select 'backward-word))
20834 ((and (not (eq org-support-shift-select 'always))
20835 (org-at-heading-p))
20836 (org-call-with-arg 'org-todo 'previousset))
20837 (org-support-shift-select
20838 (org-call-for-shift-select 'backward-word))
20839 (t (org-shiftselect-error))))
20841 (defun org-shiftcontrolup (&optional n)
20842 "Change timestamps synchronously up in CLOCK log lines.
20843 Optional argument N tells to change by that many units."
20844 (interactive "P")
20845 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20846 (let (org-support-shift-select)
20847 (org-clock-timestamps-up n))
20848 (user-error "Not at a clock log")))
20850 (defun org-shiftcontroldown (&optional n)
20851 "Change timestamps synchronously down in CLOCK log lines.
20852 Optional argument N tells to change by that many units."
20853 (interactive "P")
20854 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20855 (let (org-support-shift-select)
20856 (org-clock-timestamps-down n))
20857 (user-error "Not at a clock log")))
20859 (defun org-increase-number-at-point (&optional inc)
20860 "Increment the number at point.
20861 With an optional prefix numeric argument INC, increment using
20862 this numeric value."
20863 (interactive "p")
20864 (if (not (number-at-point))
20865 (user-error "Not on a number")
20866 (unless inc (setq inc 1))
20867 (let ((pos (point))
20868 (beg (skip-chars-backward "-+^/*0-9eE."))
20869 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20870 (setq nap (buffer-substring-no-properties
20871 (+ pos beg) (+ pos beg end)))
20872 (delete-region (+ pos beg) (+ pos beg end))
20873 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20874 (when (org-at-table-p)
20875 (org-table-align)
20876 (org-table-end-of-field 1))))
20878 (defun org-decrease-number-at-point (&optional inc)
20879 "Decrement the number at point.
20880 With an optional prefix numeric argument INC, decrement using
20881 this numeric value."
20882 (interactive "p")
20883 (org-increase-number-at-point (- (or inc 1))))
20885 (defun org-ctrl-c-ret ()
20886 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20887 (interactive)
20888 (cond
20889 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20890 (t (call-interactively 'org-insert-heading))))
20892 (defun org-find-visible ()
20893 (let ((s (point)))
20894 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20895 (get-char-property s 'invisible)))
20897 (defun org-find-invisible ()
20898 (let ((s (point)))
20899 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20900 (not (get-char-property s 'invisible))))
20903 (defun org-copy-visible (beg end)
20904 "Copy the visible parts of the region."
20905 (interactive "r")
20906 (let (snippets s)
20907 (save-excursion
20908 (save-restriction
20909 (narrow-to-region beg end)
20910 (setq s (goto-char (point-min)))
20911 (while (not (= (point) (point-max)))
20912 (goto-char (org-find-invisible))
20913 (push (buffer-substring s (point)) snippets)
20914 (setq s (goto-char (org-find-visible))))))
20915 (kill-new (apply 'concat (nreverse snippets)))))
20917 (defun org-copy-special ()
20918 "Copy region in table or copy current subtree.
20919 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20920 context. See the individual commands for more information."
20921 (interactive)
20922 (call-interactively
20923 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20925 (defun org-cut-special ()
20926 "Cut region in table or cut current subtree.
20927 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20928 context. See the individual commands for more information."
20929 (interactive)
20930 (call-interactively
20931 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20933 (defun org-paste-special (arg)
20934 "Paste rectangular region into table, or past subtree relative to level.
20935 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20936 See the individual commands for more information."
20937 (interactive "P")
20938 (if (org-at-table-p)
20939 (org-table-paste-rectangle)
20940 (org-paste-subtree arg)))
20942 (defun org-edit-special (&optional arg)
20943 "Call a special editor for the element at point.
20944 When at a table, call the formula editor with `org-table-edit-formulas'.
20945 When in a source code block, call `org-edit-src-code'.
20946 When in a fixed-width region, call `org-edit-fixed-width-region'.
20947 When in an export block, call `org-edit-export-block'.
20948 When in a LaTeX environment, call `org-edit-latex-environment'.
20949 When at an #+INCLUDE keyword, visit the included file.
20950 When at a footnote reference, call `org-edit-footnote-reference'
20951 On a link, call `ffap' to visit the link at point.
20952 Otherwise, return a user error."
20953 (interactive "P")
20954 (let ((element (org-element-at-point)))
20955 (barf-if-buffer-read-only)
20956 (pcase (org-element-type element)
20957 (`src-block
20958 (if (not arg) (org-edit-src-code)
20959 (let* ((info (org-babel-get-src-block-info))
20960 (lang (nth 0 info))
20961 (params (nth 2 info))
20962 (session (cdr (assq :session params))))
20963 (if (not session) (org-edit-src-code)
20964 ;; At a src-block with a session and function called with
20965 ;; an ARG: switch to the buffer related to the inferior
20966 ;; process.
20967 (switch-to-buffer
20968 (funcall (intern (concat "org-babel-prep-session:" lang))
20969 session params))))))
20970 (`keyword
20971 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20972 (org-open-link-from-string
20973 (format "[[%s]]"
20974 (expand-file-name
20975 (let ((value (org-element-property :value element)))
20976 (cond ((not (org-string-nw-p value))
20977 (user-error "No file to edit"))
20978 ((string-match "\\`\"\\(.*?\\)\"" value)
20979 (match-string 1 value))
20980 ((string-match "\\`[^ \t\"]\\S-*" value)
20981 (match-string 0 value))
20982 (t (user-error "No valid file specified")))))))
20983 (user-error "No special environment to edit here")))
20984 (`table
20985 (if (eq (org-element-property :type element) 'table.el)
20986 (org-edit-table.el)
20987 (call-interactively 'org-table-edit-formulas)))
20988 ;; Only Org tables contain `table-row' type elements.
20989 (`table-row (call-interactively 'org-table-edit-formulas))
20990 (`example-block (org-edit-src-code))
20991 (`export-block (org-edit-export-block))
20992 (`fixed-width (org-edit-fixed-width-region))
20993 (`latex-environment (org-edit-latex-environment))
20995 ;; No notable element at point. Though, we may be at a link or
20996 ;; a footnote reference, which are objects. Thus, scan deeper.
20997 (let ((context (org-element-context element)))
20998 (pcase (org-element-type context)
20999 (`footnote-reference (org-edit-footnote-reference))
21000 (`inline-src-block (org-edit-inline-src-code))
21001 (`link (call-interactively #'ffap))
21002 (_ (user-error "No special environment to edit here"))))))))
21004 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21005 (defun org-ctrl-c-ctrl-c (&optional arg)
21006 "Set tags in headline, or update according to changed information at point.
21008 This command does many different things, depending on context:
21010 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21011 this is what we do.
21013 - If the cursor is on a statistics cookie, update it.
21015 - If the cursor is in a headline, prompt for tags and insert them
21016 into the current line, aligned to `org-tags-column'. When called
21017 with prefix arg, realign all tags in the current buffer.
21019 - If the cursor is in one of the special #+KEYWORD lines, this
21020 triggers scanning the buffer for these lines and updating the
21021 information.
21023 - If the cursor is inside a table, realign the table. This command
21024 works even if the automatic table editor has been turned off.
21026 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21027 the entire table.
21029 - If the cursor is at a footnote reference or definition, jump to
21030 the corresponding definition or references, respectively.
21032 - If the cursor is a the beginning of a dynamic block, update it.
21034 - If the current buffer is a capture buffer, close note and file it.
21036 - If the cursor is on a <<<target>>>, update radio targets and
21037 corresponding links in this buffer.
21039 - If the cursor is on a numbered item in a plain list, renumber the
21040 ordered list.
21042 - If the cursor is on a checkbox, toggle it.
21044 - If the cursor is on a code block, evaluate it. The variable
21045 `org-confirm-babel-evaluate' can be used to control prompting
21046 before code block evaluation, by default every code block
21047 evaluation requires confirmation. Code block evaluation can be
21048 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21049 (interactive "P")
21050 (cond
21051 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21052 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21053 (org-remove-occur-highlights)
21054 (message "Temporary highlights/overlays removed from current buffer"))
21055 ((and (local-variable-p 'org-finish-function)
21056 (fboundp org-finish-function))
21057 (funcall org-finish-function))
21058 ((org-babel-hash-at-point))
21059 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21061 (let* ((context
21062 (org-element-lineage
21063 (org-element-context)
21064 ;; Limit to supported contexts.
21065 '(babel-call clock dynamic-block footnote-definition
21066 footnote-reference inline-babel-call inline-src-block
21067 inlinetask item keyword node-property paragraph
21068 plain-list property-drawer radio-target src-block
21069 statistics-cookie table table-cell table-row
21070 timestamp)
21072 (type (org-element-type context)))
21073 ;; For convenience: at the first line of a paragraph on the same
21074 ;; line as an item, apply function on that item instead.
21075 (when (eq type 'paragraph)
21076 (let ((parent (org-element-property :parent context)))
21077 (when (and (eq (org-element-type parent) 'item)
21078 (= (line-beginning-position)
21079 (org-element-property :begin parent)))
21080 (setq context parent)
21081 (setq type 'item))))
21082 ;; Act according to type of element or object at point.
21084 ;; Do nothing on a blank line, except if it is contained in
21085 ;; a src block. Hence, we first check if point is in such
21086 ;; a block and then if it is at a blank line.
21087 (pcase type
21088 ((or `inline-src-block `src-block)
21089 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21090 (org-babel-eval-wipe-error-buffer)
21091 (org-babel-execute-src-block
21092 current-prefix-arg (org-babel-get-src-block-info nil context))))
21093 ((guard (org-match-line "[ \t]*$"))
21094 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21095 (user-error
21096 (substitute-command-keys
21097 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21098 ((or `babel-call `inline-babel-call)
21099 (let ((info (org-babel-lob-get-info context)))
21100 (when info (org-babel-execute-src-block nil info))))
21101 (`clock (org-clock-update-time-maybe))
21102 (`dynamic-block
21103 (save-excursion
21104 (goto-char (org-element-property :post-affiliated context))
21105 (org-update-dblock)))
21106 (`footnote-definition
21107 (goto-char (org-element-property :post-affiliated context))
21108 (call-interactively 'org-footnote-action))
21109 (`footnote-reference (call-interactively #'org-footnote-action))
21110 ((or `headline `inlinetask)
21111 (save-excursion (goto-char (org-element-property :begin context))
21112 (call-interactively #'org-set-tags)))
21113 (`item
21114 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21115 ;; unconditionally, whereas `C-u' will toggle its presence.
21116 ;; Without a universal argument, if the item has a checkbox,
21117 ;; toggle it. Otherwise repair the list.
21118 (let* ((box (org-element-property :checkbox context))
21119 (struct (org-element-property :structure context))
21120 (old-struct (copy-tree struct))
21121 (parents (org-list-parents-alist struct))
21122 (prevs (org-list-prevs-alist struct))
21123 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21124 (org-list-set-checkbox
21125 (org-element-property :begin context) struct
21126 (cond ((equal arg '(16)) "[-]")
21127 ((and (not box) (equal arg '(4))) "[ ]")
21128 ((or (not box) (equal arg '(4))) nil)
21129 ((eq box 'on) "[ ]")
21130 (t "[X]")))
21131 ;; Mimic `org-list-write-struct' but with grabbing a return
21132 ;; value from `org-list-struct-fix-box'.
21133 (org-list-struct-fix-ind struct parents 2)
21134 (org-list-struct-fix-item-end struct)
21135 (org-list-struct-fix-bul struct prevs)
21136 (org-list-struct-fix-ind struct parents)
21137 (let ((block-item
21138 (org-list-struct-fix-box struct parents prevs orderedp)))
21139 (if (and box (equal struct old-struct))
21140 (if (equal arg '(16))
21141 (message "Checkboxes already reset")
21142 (user-error "Cannot toggle this checkbox: %s"
21143 (if (eq box 'on)
21144 "all subitems checked"
21145 "unchecked subitems")))
21146 (org-list-struct-apply-struct struct old-struct)
21147 (org-update-checkbox-count-maybe))
21148 (when block-item
21149 (message "Checkboxes were removed due to empty box at line %d"
21150 (org-current-line block-item))))))
21151 (`keyword
21152 (let ((org-inhibit-startup-visibility-stuff t)
21153 (org-startup-align-all-tables nil))
21154 (when (boundp 'org-table-coordinate-overlays)
21155 (mapc #'delete-overlay org-table-coordinate-overlays)
21156 (setq org-table-coordinate-overlays nil))
21157 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21158 (message "Local setup has been refreshed"))
21159 (`plain-list
21160 ;; At a plain list, with a double C-u argument, set
21161 ;; checkboxes of each item to "[-]", whereas a single one
21162 ;; will toggle their presence according to the state of the
21163 ;; first item in the list. Without an argument, repair the
21164 ;; list.
21165 (let* ((begin (org-element-property :contents-begin context))
21166 (beginm (move-marker (make-marker) begin))
21167 (struct (org-element-property :structure context))
21168 (old-struct (copy-tree struct))
21169 (first-box (save-excursion
21170 (goto-char begin)
21171 (looking-at org-list-full-item-re)
21172 (match-string-no-properties 3)))
21173 (new-box (cond ((equal arg '(16)) "[-]")
21174 ((equal arg '(4)) (unless first-box "[ ]"))
21175 ((equal first-box "[X]") "[ ]")
21176 (t "[X]"))))
21177 (cond
21178 (arg
21179 (dolist (pos
21180 (org-list-get-all-items
21181 begin struct (org-list-prevs-alist struct)))
21182 (org-list-set-checkbox pos struct new-box)))
21183 ((and first-box (eq (point) begin))
21184 ;; For convenience, when point is at bol on the first
21185 ;; item of the list and no argument is provided, simply
21186 ;; toggle checkbox of that item, if any.
21187 (org-list-set-checkbox begin struct new-box)))
21188 (org-list-write-struct
21189 struct (org-list-parents-alist struct) old-struct)
21190 (org-update-checkbox-count-maybe)
21191 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21192 ((or `property-drawer `node-property)
21193 (call-interactively #'org-property-action))
21194 (`radio-target
21195 (call-interactively #'org-update-radio-target-regexp))
21196 (`statistics-cookie
21197 (call-interactively #'org-update-statistics-cookies))
21198 ((or `table `table-cell `table-row)
21199 ;; At a table, recalculate every field and align it. Also
21200 ;; send the table if necessary. If the table has
21201 ;; a `table.el' type, just give up. At a table row or cell,
21202 ;; maybe recalculate line but always align table.
21203 (if (eq (org-element-property :type context) 'table.el)
21204 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21205 Use `\\[org-edit-special]' to edit table.el tables"))
21206 (let ((org-enable-table-editor t))
21207 (if (or (eq type 'table)
21208 ;; Check if point is at a TBLFM line.
21209 (and (eq type 'table-row)
21210 (= (point) (org-element-property :end context))))
21211 (save-excursion
21212 (if (org-at-TBLFM-p)
21213 (progn (require 'org-table)
21214 (org-table-calc-current-TBLFM))
21215 (goto-char (org-element-property :contents-begin context))
21216 (org-call-with-arg 'org-table-recalculate (or arg t))
21217 (orgtbl-send-table 'maybe)))
21218 (org-table-maybe-eval-formula)
21219 (cond (arg (call-interactively #'org-table-recalculate))
21220 ((org-table-maybe-recalculate-line))
21221 (t (org-table-align)))))))
21222 (`timestamp (org-timestamp-change 0 'day))
21223 ((and `nil (guard (org-at-heading-p)))
21224 ;; When point is on an unsupported object type, we can miss
21225 ;; the fact that it also is at a heading. Handle it here.
21226 (call-interactively #'org-set-tags))
21227 ((guard
21228 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21230 (user-error
21231 (substitute-command-keys
21232 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21234 (defun org-mode-restart ()
21235 (interactive)
21236 (let ((indent-status (bound-and-true-p org-indent-mode)))
21237 (funcall major-mode)
21238 (hack-local-variables)
21239 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21240 (org-indent-mode -1)))
21241 (message "%s restarted" major-mode))
21243 (defun org-kill-note-or-show-branches ()
21244 "Abort storing current note, or call `outline-show-branches'."
21245 (interactive)
21246 (if (not org-finish-function)
21247 (progn
21248 (outline-hide-subtree)
21249 (call-interactively 'outline-show-branches))
21250 (let ((org-note-abort t))
21251 (funcall org-finish-function))))
21253 (defun org-delete-indentation (&optional arg)
21254 "Join current line to previous and fix whitespace at join.
21256 If previous line is a headline add to headline title. Otherwise
21257 the function calls `delete-indentation'.
21259 With a non-nil optional argument, join it to the following one."
21260 (interactive "*P")
21261 (if (save-excursion
21262 (beginning-of-line (if arg 1 0))
21263 (let ((case-fold-search nil))
21264 (looking-at org-complex-heading-regexp)))
21265 ;; At headline.
21266 (let ((tags-column (when (match-beginning 5)
21267 (save-excursion (goto-char (match-beginning 5))
21268 (current-column))))
21269 (string (concat " " (progn (when arg (forward-line 1))
21270 (org-trim (delete-and-extract-region
21271 (line-beginning-position)
21272 (line-end-position)))))))
21273 (unless (bobp) (delete-region (point) (1- (point))))
21274 (goto-char (or (match-end 4)
21275 (match-beginning 5)
21276 (match-end 0)))
21277 (skip-chars-backward " \t")
21278 (save-excursion (insert string))
21279 ;; Adjust alignment of tags.
21280 (cond
21281 ((not tags-column)) ;no tags
21282 (org-auto-align-tags (org-set-tags nil t))
21283 (t (org--align-tags-here tags-column)))) ;preserve tags column
21284 (delete-indentation arg)))
21286 (defun org-open-line (n)
21287 "Insert a new row in tables, call `open-line' elsewhere.
21288 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21289 As a special case, when a document starts with a table, allow to
21290 call `open-line' on the very first character."
21291 (interactive "*p")
21292 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21293 (org-table-insert-row)
21294 (open-line n)))
21296 (defun org-return (&optional indent)
21297 "Goto next table row or insert a newline.
21299 Calls `org-table-next-row' or `newline', depending on context.
21301 When optional INDENT argument is non-nil, call
21302 `newline-and-indent' instead of `newline'.
21304 When `org-return-follows-link' is non-nil and point is on
21305 a timestamp or a link, call `org-open-at-point'. However, it
21306 will not happen if point is in a table or on a \"dead\"
21307 object (e.g., within a comment). In these case, you need to use
21308 `org-open-at-point' directly."
21309 (interactive)
21310 (let ((context (if org-return-follows-link (org-element-context)
21311 (org-element-at-point))))
21312 (cond
21313 ;; In a table, call `org-table-next-row'.
21314 ((or (and (eq (org-element-type context) 'table)
21315 (>= (point) (org-element-property :contents-begin context))
21316 (< (point) (org-element-property :contents-end context)))
21317 (org-element-lineage context '(table-row table-cell) t))
21318 (org-table-justify-field-maybe)
21319 (call-interactively #'org-table-next-row))
21320 ;; On a link or a timestamp, call `org-open-at-point' if
21321 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21322 ;; locations, e.g., in a comment, as `org-open-at-point'.
21323 ((and org-return-follows-link
21324 (or (org-in-regexp org-ts-regexp-both nil t)
21325 (org-in-regexp org-tsr-regexp-both nil t)
21326 (org-in-regexp org-any-link-re nil t)))
21327 (call-interactively #'org-open-at-point))
21328 ;; Insert newline in heading, but preserve tags.
21329 ((and (not (bolp))
21330 (save-excursion (beginning-of-line)
21331 (let ((case-fold-search nil))
21332 (looking-at org-complex-heading-regexp))))
21333 ;; At headline. Split line. However, if point is on keyword,
21334 ;; priority cookie or tags, do not break any of them: add
21335 ;; a newline after the headline instead.
21336 (let ((tags-column (and (match-beginning 5)
21337 (save-excursion (goto-char (match-beginning 5))
21338 (current-column))))
21339 (string
21340 (when (and (match-end 4) (org-point-in-group (point) 4))
21341 (delete-and-extract-region (point) (match-end 4)))))
21342 ;; Adjust tag alignment.
21343 (cond
21344 ((not (and tags-column string)))
21345 (org-auto-align-tags (org-set-tags nil t))
21346 (t (org--align-tags-here tags-column))) ;preserve tags column
21347 (end-of-line)
21348 (org-show-entry)
21349 (if indent (newline-and-indent) (newline))
21350 (when string (save-excursion (insert (org-trim string))))))
21351 ;; In a list, make sure indenting keeps trailing text within.
21352 ((and indent
21353 (not (eolp))
21354 (org-element-lineage context '(item)))
21355 (let ((trailing-data
21356 (delete-and-extract-region (point) (line-end-position))))
21357 (newline-and-indent)
21358 (save-excursion (insert trailing-data))))
21359 (t (if indent (newline-and-indent) (newline))))))
21361 (defun org-return-indent ()
21362 "Goto next table row or insert a newline and indent.
21363 Calls `org-table-next-row' or `newline-and-indent', depending on
21364 context. See the individual commands for more information."
21365 (interactive)
21366 (org-return t))
21368 (defun org-ctrl-c-star ()
21369 "Compute table, or change heading status of lines.
21370 Calls `org-table-recalculate' or `org-toggle-heading',
21371 depending on context."
21372 (interactive)
21373 (cond
21374 ((org-at-table-p)
21375 (call-interactively 'org-table-recalculate))
21377 ;; Convert all lines in region to list items
21378 (call-interactively 'org-toggle-heading))))
21380 (defun org-ctrl-c-minus ()
21381 "Insert separator line in table or modify bullet status of line.
21382 Also turns a plain line or a region of lines into list items.
21383 Calls `org-table-insert-hline', `org-toggle-item', or
21384 `org-cycle-list-bullet', depending on context."
21385 (interactive)
21386 (cond
21387 ((org-at-table-p)
21388 (call-interactively 'org-table-insert-hline))
21389 ((org-region-active-p)
21390 (call-interactively 'org-toggle-item))
21391 ((org-in-item-p)
21392 (call-interactively 'org-cycle-list-bullet))
21394 (call-interactively 'org-toggle-item))))
21396 (defun org-toggle-heading (&optional nstars)
21397 "Convert headings to normal text, or items or text to headings.
21398 If there is no active region, only convert the current line.
21400 With a `\\[universal-argument]' prefix, convert the whole list at
21401 point into heading.
21403 In a region:
21405 - If the first non blank line is a headline, remove the stars
21406 from all headlines in the region.
21408 - If it is a normal line, turn each and every normal line (i.e.,
21409 not an heading or an item) in the region into headings. If you
21410 want to convert only the first line of this region, use one
21411 universal prefix argument.
21413 - If it is a plain list item, turn all plain list items into headings.
21415 When converting a line into a heading, the number of stars is chosen
21416 such that the lines become children of the current entry. However,
21417 when a numeric prefix argument is given, its value determines the
21418 number of stars to add."
21419 (interactive "P")
21420 (let ((skip-blanks
21421 (function
21422 ;; Return beginning of first non-blank line, starting from
21423 ;; line at POS.
21424 (lambda (pos)
21425 (save-excursion
21426 (goto-char pos)
21427 (while (org-at-comment-p) (forward-line))
21428 (skip-chars-forward " \r\t\n")
21429 (point-at-bol)))))
21430 beg end toggled)
21431 ;; Determine boundaries of changes. If a universal prefix has
21432 ;; been given, put the list in a region. If region ends at a bol,
21433 ;; do not consider the last line to be in the region.
21435 (when (and current-prefix-arg (org-at-item-p))
21436 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21437 (org-mark-element))
21439 (if (org-region-active-p)
21440 (setq beg (funcall skip-blanks (region-beginning))
21441 end (copy-marker (save-excursion
21442 (goto-char (region-end))
21443 (if (bolp) (point) (point-at-eol)))))
21444 (setq beg (funcall skip-blanks (point-at-bol))
21445 end (copy-marker (point-at-eol))))
21446 ;; Ensure inline tasks don't count as headings.
21447 (org-with-limited-levels
21448 (save-excursion
21449 (goto-char beg)
21450 (cond
21451 ;; Case 1. Started at an heading: de-star headings.
21452 ((org-at-heading-p)
21453 (while (< (point) end)
21454 (when (org-at-heading-p t)
21455 (looking-at org-outline-regexp) (replace-match "")
21456 (setq toggled t))
21457 (forward-line)))
21458 ;; Case 2. Started at an item: change items into headlines.
21459 ;; One star will be added by `org-list-to-subtree'.
21460 ((org-at-item-p)
21461 (while (< (point) end)
21462 (when (org-at-item-p)
21463 ;; Pay attention to cases when region ends before list.
21464 (let* ((struct (org-list-struct))
21465 (list-end
21466 (min (org-list-get-bottom-point struct) (1+ end))))
21467 (save-restriction
21468 (narrow-to-region (point) list-end)
21469 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21470 (setq toggled t))
21471 (forward-line)))
21472 ;; Case 3. Started at normal text: make every line an heading,
21473 ;; skipping headlines and items.
21474 (t (let* ((stars
21475 (make-string
21476 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21477 (add-stars
21478 (cond (nstars "") ; stars from prefix only
21479 ((equal stars "") "*") ; before first heading
21480 (org-odd-levels-only "**") ; inside heading, odd
21481 (t "*"))) ; inside heading, oddeven
21482 (rpl (concat stars add-stars " "))
21483 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21484 (while (< (point) (if (equal nstars '(4)) lend end))
21485 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21486 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21487 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21488 (forward-line)))))))
21489 (unless toggled (message "Cannot toggle heading from here"))))
21491 (defun org-meta-return (&optional arg)
21492 "Insert a new heading or wrap a region in a table.
21493 Calls `org-insert-heading', `org-insert-item' or
21494 `org-table-wrap-region', depending on context. When called with
21495 an argument, unconditionally call `org-insert-heading'."
21496 (interactive "P")
21497 (org-check-before-invisible-edit 'insert)
21498 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21499 (call-interactively (cond (arg #'org-insert-heading)
21500 ((org-at-table-p) #'org-table-wrap-region)
21501 ((org-in-item-p) #'org-insert-item)
21502 (t #'org-insert-heading)))))
21504 ;;; Menu entries
21506 (defsubst org-in-subtree-not-table-p ()
21507 "Are we in a subtree and not in a table?"
21508 (and (not (org-before-first-heading-p))
21509 (not (org-at-table-p))))
21511 ;; Define the Org mode menus
21512 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21513 '("Tbl"
21514 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21515 ["Next Field" org-cycle (org-at-table-p)]
21516 ["Previous Field" org-shifttab (org-at-table-p)]
21517 ["Next Row" org-return (org-at-table-p)]
21518 "--"
21519 ["Blank Field" org-table-blank-field (org-at-table-p)]
21520 ["Edit Field" org-table-edit-field (org-at-table-p)]
21521 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21522 "--"
21523 ("Column"
21524 ["Move Column Left" org-metaleft (org-at-table-p)]
21525 ["Move Column Right" org-metaright (org-at-table-p)]
21526 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21527 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21528 ("Row"
21529 ["Move Row Up" org-metaup (org-at-table-p)]
21530 ["Move Row Down" org-metadown (org-at-table-p)]
21531 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21532 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21533 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21534 "--"
21535 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21536 ("Rectangle"
21537 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21538 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21539 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21540 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21541 "--"
21542 ("Calculate"
21543 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21544 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21545 ["Edit Formulas" org-edit-special (org-at-table-p)]
21546 "--"
21547 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21548 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21549 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21550 "--"
21551 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21552 "--"
21553 ["Sum Column/Rectangle" org-table-sum
21554 (or (org-at-table-p) (org-region-active-p))]
21555 ["Which Column?" org-table-current-column (org-at-table-p)])
21556 ["Debug Formulas"
21557 org-table-toggle-formula-debugger
21558 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21559 ["Show Col/Row Numbers"
21560 org-table-toggle-coordinate-overlays
21561 :style toggle
21562 :selected (bound-and-true-p org-table-overlay-coordinates)]
21563 "--"
21564 ["Create" org-table-create (and (not (org-at-table-p))
21565 org-enable-table-editor)]
21566 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21567 ["Import from File" org-table-import (not (org-at-table-p))]
21568 ["Export to File" org-table-export (org-at-table-p)]
21569 "--"
21570 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21571 "--"
21572 ("Plot"
21573 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21574 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21576 (easy-menu-define org-org-menu org-mode-map "Org menu"
21577 '("Org"
21578 ("Show/Hide"
21579 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21580 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21581 ["Sparse Tree..." org-sparse-tree t]
21582 ["Reveal Context" org-reveal t]
21583 ["Show All" outline-show-all t]
21584 "--"
21585 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21586 "--"
21587 ["New Heading" org-insert-heading t]
21588 ("Navigate Headings"
21589 ["Up" outline-up-heading t]
21590 ["Next" outline-next-visible-heading t]
21591 ["Previous" outline-previous-visible-heading t]
21592 ["Next Same Level" outline-forward-same-level t]
21593 ["Previous Same Level" outline-backward-same-level t]
21594 "--"
21595 ["Jump" org-goto t])
21596 ("Edit Structure"
21597 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21598 "--"
21599 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21600 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21601 "--"
21602 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21603 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21604 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21605 "--"
21606 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21607 "--"
21608 ["Copy visible text" org-copy-visible t]
21609 "--"
21610 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21611 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21612 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21613 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21614 "--"
21615 ["Sort Region/Children" org-sort t]
21616 "--"
21617 ["Convert to odd levels" org-convert-to-odd-levels t]
21618 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21619 ("Editing"
21620 ["Emphasis..." org-emphasize t]
21621 ["Edit Source Example" org-edit-special t]
21622 "--"
21623 ["Footnote new/jump" org-footnote-action t]
21624 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21625 ("Archive"
21626 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21627 "--"
21628 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21629 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21630 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21632 "--"
21633 ("Hyperlinks"
21634 ["Store Link (Global)" org-store-link t]
21635 ["Find existing link to here" org-occur-link-in-agenda-files t]
21636 ["Insert Link" org-insert-link t]
21637 ["Follow Link" org-open-at-point t]
21638 "--"
21639 ["Next link" org-next-link t]
21640 ["Previous link" org-previous-link t]
21641 "--"
21642 ["Descriptive Links"
21643 org-toggle-link-display
21644 :style radio
21645 :selected org-descriptive-links
21647 ["Literal Links"
21648 org-toggle-link-display
21649 :style radio
21650 :selected (not org-descriptive-links)])
21651 "--"
21652 ("TODO Lists"
21653 ["TODO/DONE/-" org-todo t]
21654 ("Select keyword"
21655 ["Next keyword" org-shiftright (org-at-heading-p)]
21656 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21657 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21658 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21659 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21660 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21661 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21662 "--"
21663 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21664 :selected org-enforce-todo-dependencies :style toggle :active t]
21665 "Settings for tree at point"
21666 ["Do Children sequentially" org-toggle-ordered-property :style radio
21667 :selected (org-entry-get nil "ORDERED")
21668 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21669 ["Do Children parallel" org-toggle-ordered-property :style radio
21670 :selected (not (org-entry-get nil "ORDERED"))
21671 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21672 "--"
21673 ["Set Priority" org-priority t]
21674 ["Priority Up" org-shiftup t]
21675 ["Priority Down" org-shiftdown t]
21676 "--"
21677 ["Get news from all feeds" org-feed-update-all t]
21678 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21679 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21680 ("TAGS and Properties"
21681 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21682 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21683 "--"
21684 ["Set property" org-set-property (not (org-before-first-heading-p))]
21685 ["Column view of properties" org-columns t]
21686 ["Insert Column View DBlock" org-columns-insert-dblock t])
21687 ("Dates and Scheduling"
21688 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21689 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21690 ("Change Date"
21691 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21692 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21693 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21694 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21695 ["Compute Time Range" org-evaluate-time-range t]
21696 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21697 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21698 "--"
21699 ["Custom time format" org-toggle-time-stamp-overlays
21700 :style radio :selected org-display-custom-times]
21701 "--"
21702 ["Goto Calendar" org-goto-calendar t]
21703 ["Date from Calendar" org-date-from-calendar t]
21704 "--"
21705 ["Start/Restart Timer" org-timer-start t]
21706 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21707 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21708 ["Insert Timer String" org-timer t]
21709 ["Insert Timer Item" org-timer-item t])
21710 ("Logging work"
21711 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21712 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21713 ["Clock out" org-clock-out t]
21714 ["Clock cancel" org-clock-cancel t]
21715 "--"
21716 ["Mark as default task" org-clock-mark-default-task t]
21717 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21718 ["Goto running clock" org-clock-goto t]
21719 "--"
21720 ["Display times" org-clock-display t]
21721 ["Create clock table" org-clock-report t]
21722 "--"
21723 ["Record DONE time"
21724 (progn (setq org-log-done (not org-log-done))
21725 (message "Switching to %s will %s record a timestamp"
21726 (car org-done-keywords)
21727 (if org-log-done "automatically" "not")))
21728 :style toggle :selected org-log-done])
21729 "--"
21730 ["Agenda Command..." org-agenda t]
21731 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21732 ("File List for Agenda")
21733 ("Special views current file"
21734 ["TODO Tree" org-show-todo-tree t]
21735 ["Check Deadlines" org-check-deadlines t]
21736 ["Tags/Property tree" org-match-sparse-tree t])
21737 "--"
21738 ["Export/Publish..." org-export-dispatch t]
21739 ("LaTeX"
21740 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21741 :selected org-cdlatex-mode]
21742 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21743 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21744 ["Modify math symbol" org-cdlatex-math-modify
21745 (org-inside-LaTeX-fragment-p)]
21746 ["Insert citation" org-reftex-citation t])
21747 "--"
21748 ("MobileOrg"
21749 ["Push Files and Views" org-mobile-push t]
21750 ["Get Captured and Flagged" org-mobile-pull t]
21751 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21752 "--"
21753 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21754 "--"
21755 ("Documentation"
21756 ["Show Version" org-version t]
21757 ["Info Documentation" org-info t])
21758 ("Customize"
21759 ["Browse Org Group" org-customize t]
21760 "--"
21761 ["Expand This Menu" org-create-customize-menu
21762 (fboundp 'customize-menu-create)])
21763 ["Send bug report" org-submit-bug-report t]
21764 "--"
21765 ("Refresh/Reload"
21766 ["Refresh setup current buffer" org-mode-restart t]
21767 ["Reload Org (after update)" org-reload t]
21768 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21771 (defun org-info (&optional node)
21772 "Read documentation for Org in the info system.
21773 With optional NODE, go directly to that node."
21774 (interactive)
21775 (info (format "(org)%s" (or node ""))))
21777 ;;;###autoload
21778 (defun org-submit-bug-report ()
21779 "Submit a bug report on Org via mail.
21781 Don't hesitate to report any problems or inaccurate documentation.
21783 If you don't have setup sending mail from (X)Emacs, please copy the
21784 output buffer into your mail program, as it gives us important
21785 information about your Org version and configuration."
21786 (interactive)
21787 (require 'reporter)
21788 (defvar reporter-prompt-for-summary-p)
21789 (org-load-modules-maybe)
21790 (org-require-autoloaded-modules)
21791 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21792 (reporter-submit-bug-report
21793 "emacs-orgmode@gnu.org"
21794 (org-version nil 'full)
21795 (let (list)
21796 (save-window-excursion
21797 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21798 (delete-other-windows)
21799 (erase-buffer)
21800 (insert "You are about to submit a bug report to the Org mailing list.
21802 We would like to add your full Org and Outline configuration to the
21803 bug report. This greatly simplifies the work of the maintainer and
21804 other experts on the mailing list.
21806 HOWEVER, some variables you have customized may contain private
21807 information. The names of customers, colleagues, or friends, might
21808 appear in the form of file names, tags, todo states, or search strings.
21809 If you answer yes to the prompt, you might want to check and remove
21810 such private information before sending the email.")
21811 (add-text-properties (point-min) (point-max) '(face org-warning))
21812 (when (yes-or-no-p "Include your Org configuration ")
21813 (mapatoms
21814 (lambda (v)
21815 (and (boundp v)
21816 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21817 (or (and (symbol-value v)
21818 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21819 (and
21820 (get v 'custom-type) (get v 'standard-value)
21821 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21822 (push v list)))))
21823 (kill-buffer (get-buffer "*Warn about privacy*"))
21824 list))
21825 nil nil
21826 "Remember to cover the basics, that is, what you expected to happen and
21827 what in fact did happen. You don't know how to make a good report? See
21829 http://orgmode.org/manual/Feedback.html#Feedback
21831 Your bug report will be posted to the Org mailing list.
21832 ------------------------------------------------------------------------")
21833 (save-excursion
21834 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21835 (replace-match "\\1Bug: \\3 [\\2]")))))
21838 (defun org-install-agenda-files-menu ()
21839 (let ((bl (buffer-list)))
21840 (save-excursion
21841 (while bl
21842 (set-buffer (pop bl))
21843 (when (derived-mode-p 'org-mode) (setq bl nil)))
21844 (when (derived-mode-p 'org-mode)
21845 (easy-menu-change
21846 '("Org") "File List for Agenda"
21847 (append
21848 (list
21849 ["Edit File List" (org-edit-agenda-file-list) t]
21850 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21851 ["Remove Current File from List" org-remove-file t]
21852 ["Cycle through agenda files" org-cycle-agenda-files t]
21853 ["Occur in all agenda files" org-occur-in-agenda-files t]
21854 "--")
21855 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21857 ;;;; Documentation
21859 (defun org-require-autoloaded-modules ()
21860 (interactive)
21861 (mapc #'require
21862 '(org-agenda org-archive org-attach org-clock org-colview org-id
21863 org-table org-timer)))
21865 ;;;###autoload
21866 (defun org-reload (&optional uncompiled)
21867 "Reload all org lisp files.
21868 With prefix arg UNCOMPILED, load the uncompiled versions."
21869 (interactive "P")
21870 (require 'loadhist)
21871 (let* ((org-dir (org-find-library-dir "org"))
21872 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21873 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21874 (remove-re (format "\\`%s\\'"
21875 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21876 (feats (delete-dups
21877 (mapcar 'file-name-sans-extension
21878 (mapcar 'file-name-nondirectory
21879 (delq nil
21880 (mapcar 'feature-file
21881 features))))))
21882 (lfeat (append
21883 (sort
21884 (setq feats
21885 (delq nil (mapcar
21886 (lambda (f)
21887 (if (and (string-match feature-re f)
21888 (not (string-match remove-re f)))
21889 f nil))
21890 feats)))
21891 'string-lessp)
21892 (list "org-version" "org")))
21893 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21894 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21895 load-uncore load-misses)
21896 (setq load-misses
21897 (delq 't
21898 (mapcar (lambda (f)
21899 (or (org-load-noerror-mustsuffix (concat org-dir f))
21900 (and (string= org-dir contrib-dir)
21901 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21902 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21903 (add-to-list 'load-uncore f 'append)
21906 lfeat)))
21907 (when load-uncore
21908 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21909 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21910 (if load-misses
21911 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21912 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21913 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21915 ;;;###autoload
21916 (defun org-customize ()
21917 "Call the customize function with org as argument."
21918 (interactive)
21919 (org-load-modules-maybe)
21920 (org-require-autoloaded-modules)
21921 (customize-browse 'org))
21923 (defun org-create-customize-menu ()
21924 "Create a full customization menu for Org mode, insert it into the menu."
21925 (interactive)
21926 (org-load-modules-maybe)
21927 (org-require-autoloaded-modules)
21928 (if (fboundp 'customize-menu-create)
21929 (progn
21930 (easy-menu-change
21931 '("Org") "Customize"
21932 `(["Browse Org group" org-customize t]
21933 "--"
21934 ,(customize-menu-create 'org)
21935 ["Set" Custom-set t]
21936 ["Save" Custom-save t]
21937 ["Reset to Current" Custom-reset-current t]
21938 ["Reset to Saved" Custom-reset-saved t]
21939 ["Reset to Standard Settings" Custom-reset-standard t]))
21940 (message "\"Org\"-menu now contains full customization menu"))
21941 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21943 ;;;; Miscellaneous stuff
21945 ;;; Generally useful functions
21947 (defun org-get-at-eol (property n)
21948 "Get text property PROPERTY at the end of line less N characters."
21949 (get-text-property (- (point-at-eol) n) property))
21951 (defun org-find-text-property-in-string (prop s)
21952 "Return the first non-nil value of property PROP in string S."
21953 (or (get-text-property 0 prop s)
21954 (get-text-property (or (next-single-property-change 0 prop s) 0)
21955 prop s)))
21957 (defun org-display-warning (message)
21958 "Display the given MESSAGE as a warning."
21959 (display-warning 'org message :warning))
21961 (defun org-eval (form)
21962 "Eval FORM and return result."
21963 (condition-case error
21964 (eval form)
21965 (error (format "%%![Error: %s]" error))))
21967 (defun org-in-clocktable-p ()
21968 "Check if the cursor is in a clocktable."
21969 (let ((pos (point)) start)
21970 (save-excursion
21971 (end-of-line 1)
21972 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21973 (setq start (match-beginning 0))
21974 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21975 (>= (match-end 0) pos)
21976 start))))
21978 (defun org-in-verbatim-emphasis ()
21979 (save-match-data
21980 (and (org-in-regexp org-verbatim-re 2)
21981 (>= (point) (match-beginning 3))
21982 (<= (point) (match-end 4)))))
21984 (defun org-overlay-display (ovl text &optional face evap)
21985 "Make overlay OVL display TEXT with face FACE."
21986 (overlay-put ovl 'display text)
21987 (if face (overlay-put ovl 'face face))
21988 (if evap (overlay-put ovl 'evaporate t)))
21990 (defun org-overlay-before-string (ovl text &optional face evap)
21991 "Make overlay OVL display TEXT with face FACE."
21992 (if face (org-add-props text nil 'face face))
21993 (overlay-put ovl 'before-string text)
21994 (if evap (overlay-put ovl 'evaporate t)))
21996 (defun org-find-overlays (prop &optional pos delete)
21997 "Find all overlays specifying PROP at POS or point.
21998 If DELETE is non-nil, delete all those overlays."
21999 (let (found)
22000 (dolist (ov (overlays-at (or pos (point))) found)
22001 (cond ((not (overlay-get ov prop)))
22002 (delete (delete-overlay ov))
22003 (t (push ov found))))))
22005 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22006 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22007 (if (and marker (marker-buffer marker)
22008 (buffer-live-p (marker-buffer marker)))
22009 (progn
22010 (pop-to-buffer-same-window (marker-buffer marker))
22011 (when (or (> marker (point-max)) (< marker (point-min)))
22012 (widen))
22013 (goto-char marker)
22014 (org-show-context 'org-goto))
22015 (if bookmark
22016 (bookmark-jump bookmark)
22017 (error "Cannot find location"))))
22019 (defun org-quote-csv-field (s)
22020 "Quote field for inclusion in CSV material."
22021 (if (string-match "[\",]" s)
22022 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22025 (defun org-force-self-insert (N)
22026 "Needed to enforce self-insert under remapping."
22027 (interactive "p")
22028 (self-insert-command N))
22030 (defun org-string-width (s)
22031 "Compute width of string, ignoring invisible characters.
22032 This ignores character with invisibility property `org-link', and also
22033 characters with property `org-cwidth', because these will become invisible
22034 upon the next fontification round."
22035 (let (b l)
22036 (when (or (eq t buffer-invisibility-spec)
22037 (assq 'org-link buffer-invisibility-spec))
22038 (while (setq b (text-property-any 0 (length s)
22039 'invisible 'org-link s))
22040 (setq s (concat (substring s 0 b)
22041 (substring s (or (next-single-property-change
22042 b 'invisible s)
22043 (length s)))))))
22044 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22045 (setq s (concat (substring s 0 b)
22046 (substring s (or (next-single-property-change
22047 b 'org-cwidth s)
22048 (length s))))))
22049 (setq l (string-width s) b -1)
22050 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22051 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22054 (defun org-shorten-string (s maxlength)
22055 "Shorten string S so that it is no longer than MAXLENGTH characters.
22056 If the string is shorter or has length MAXLENGTH, just return the
22057 original string. If it is longer, the functions finds a space in the
22058 string, breaks this string off at that locations and adds three dots
22059 as ellipsis. Including the ellipsis, the string will not be longer
22060 than MAXLENGTH. If finding a good breaking point in the string does
22061 not work, the string is just chopped off in the middle of a word
22062 if necessary."
22063 (if (<= (length s) maxlength)
22065 (let* ((n (max (- maxlength 4) 1))
22066 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22067 (if (string-match re s)
22068 (concat (match-string 1 s) "...")
22069 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22071 (defun org-get-indentation (&optional line)
22072 "Get the indentation of the current line, interpreting tabs.
22073 When LINE is given, assume it represents a line and compute its indentation."
22074 (if line
22075 (when (string-match "^ *" (org-remove-tabs line))
22076 (match-end 0))
22077 (save-excursion
22078 (beginning-of-line 1)
22079 (skip-chars-forward " \t")
22080 (current-column))))
22082 (defun org-get-string-indentation (s)
22083 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22084 (let ((n -1) (i 0) (w tab-width) c)
22085 (catch 'exit
22086 (while (< (setq n (1+ n)) (length s))
22087 (setq c (aref s n))
22088 (cond ((= c ?\ ) (setq i (1+ i)))
22089 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22090 (t (throw 'exit t)))))
22093 (defun org-remove-tabs (s &optional width)
22094 "Replace tabulators in S with spaces.
22095 Assumes that s is a single line, starting in column 0."
22096 (setq width (or width tab-width))
22097 (while (string-match "\t" s)
22098 (setq s (replace-match
22099 (make-string
22100 (- (* width (/ (+ (match-beginning 0) width) width))
22101 (match-beginning 0)) ?\ )
22102 t t s)))
22105 (defun org-fix-indentation (line ind)
22106 "Fix indentation in LINE.
22107 IND is a cons cell with target and minimum indentation.
22108 If the current indentation in LINE is smaller than the minimum,
22109 leave it alone. If it is larger than ind, set it to the target."
22110 (let* ((l (org-remove-tabs line))
22111 (i (org-get-indentation l))
22112 (i1 (car ind)) (i2 (cdr ind)))
22113 (when (>= i i2) (setq l (substring line i2)))
22114 (if (> i1 0)
22115 (concat (make-string i1 ?\ ) l)
22116 l)))
22118 (defun org-remove-indentation (code &optional n)
22119 "Remove maximum common indentation in string CODE and return it.
22120 N may optionally be the number of columns to remove. Return CODE
22121 as-is if removal failed."
22122 (with-temp-buffer
22123 (insert code)
22124 (if (org-do-remove-indentation n) (buffer-string) code)))
22126 (defun org-do-remove-indentation (&optional n)
22127 "Remove the maximum common indentation from the buffer.
22128 When optional argument N is a positive integer, remove exactly
22129 that much characters from indentation, if possible. Return nil
22130 if it fails."
22131 (catch :exit
22132 (goto-char (point-min))
22133 ;; Find maximum common indentation, if not specified.
22134 (let ((n (or n
22135 (let ((min-ind (point-max)))
22136 (save-excursion
22137 (while (re-search-forward "^[ \t]*\\S-" nil t)
22138 (let ((ind (1- (current-column))))
22139 (if (zerop ind) (throw :exit nil)
22140 (setq min-ind (min min-ind ind))))))
22141 min-ind))))
22142 (if (zerop n) (throw :exit nil)
22143 ;; Remove exactly N indentation, but give up if not possible.
22144 (while (not (eobp))
22145 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22146 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22147 ((< ind n) (throw :exit nil))
22148 (t (indent-line-to (- ind n))))
22149 (forward-line)))
22150 ;; Signal success.
22151 t))))
22153 (defun org-fill-template (template alist)
22154 "Find each %key of ALIST in TEMPLATE and replace it."
22155 (let ((case-fold-search nil))
22156 (dolist (entry (sort (copy-sequence alist)
22157 (lambda (a b) (< (length (car a)) (length (car b))))))
22158 (setq template
22159 (replace-regexp-in-string
22160 (concat "%" (regexp-quote (car entry)))
22161 (or (cdr entry) "") template t t)))
22162 template))
22164 (defun org-base-buffer (buffer)
22165 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22166 (if (not buffer)
22167 buffer
22168 (or (buffer-base-buffer buffer)
22169 buffer)))
22171 (defun org-wrap (string &optional width lines)
22172 "Wrap string to either a number of lines, or a width in characters.
22173 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22174 that costs. If there is a word longer than WIDTH, the text is actually
22175 wrapped to the length of that word.
22176 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22177 many lines, whatever width that takes.
22178 The return value is a list of lines, without newlines at the end."
22179 (let* ((words (org-split-string string "[ \t\n]+"))
22180 (maxword (apply 'max (mapcar 'org-string-width words)))
22181 w ll)
22182 (cond (width
22183 (org-do-wrap words (max maxword width)))
22184 (lines
22185 (setq w maxword)
22186 (setq ll (org-do-wrap words maxword))
22187 (if (<= (length ll) lines)
22189 (setq ll words)
22190 (while (> (length ll) lines)
22191 (setq w (1+ w))
22192 (setq ll (org-do-wrap words w)))
22193 ll))
22194 (t (error "Cannot wrap this")))))
22196 (defun org-do-wrap (words width)
22197 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22198 (let (lines line)
22199 (while words
22200 (setq line (pop words))
22201 (while (and words (< (+ (length line) (length (car words))) width))
22202 (setq line (concat line " " (pop words))))
22203 (setq lines (push line lines)))
22204 (nreverse lines)))
22206 (defun org-split-string (string &optional separators)
22207 "Splits STRING into substrings at SEPARATORS.
22208 SEPARATORS is a regular expression.
22209 No empty strings are returned if there are matches at the beginning
22210 and end of string."
22211 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22212 (let ((start 0) notfirst list)
22213 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22214 (if (and notfirst
22215 (= start (match-beginning 0))
22216 (< start (length string)))
22217 (1+ start) start))
22218 (< (match-beginning 0) (length string)))
22219 (setq notfirst t)
22220 (or (eq (match-beginning 0) 0)
22221 (and (eq (match-beginning 0) (match-end 0))
22222 (eq (match-beginning 0) start))
22223 (push (substring string start (match-beginning 0)) list))
22224 (setq start (match-end 0)))
22225 (or (eq start (length string))
22226 (push (substring string start) list))
22227 (nreverse list)))
22229 (defun org-quote-vert (s)
22230 "Replace \"|\" with \"\\vert\"."
22231 (while (string-match "|" s)
22232 (setq s (replace-match "\\vert" t t s)))
22235 (defun org-uuidgen-p (s)
22236 "Is S an ID created by UUIDGEN?"
22237 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22239 (defun org-in-src-block-p (&optional inside)
22240 "Whether point is in a code source block.
22241 When INSIDE is non-nil, don't consider we are within a src block
22242 when point is at #+BEGIN_SRC or #+END_SRC."
22243 (let ((case-fold-search t))
22244 (or (and (eq (get-char-property (point) 'src-block) t))
22245 (and (not inside)
22246 (save-match-data
22247 (save-excursion
22248 (beginning-of-line)
22249 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22251 (defun org-context ()
22252 "Return a list of contexts of the current cursor position.
22253 If several contexts apply, all are returned.
22254 Each context entry is a list with a symbol naming the context, and
22255 two positions indicating start and end of the context. Possible
22256 contexts are:
22258 :headline anywhere in a headline
22259 :headline-stars on the leading stars in a headline
22260 :todo-keyword on a TODO keyword (including DONE) in a headline
22261 :tags on the TAGS in a headline
22262 :priority on the priority cookie in a headline
22263 :item on the first line of a plain list item
22264 :item-bullet on the bullet/number of a plain list item
22265 :checkbox on the checkbox in a plain list item
22266 :table in an Org table
22267 :table-special on a special filed in a table
22268 :table-table in a table.el table
22269 :clocktable in a clocktable
22270 :src-block in a source block
22271 :link on a hyperlink
22272 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22273 :target on a <<target>>
22274 :radio-target on a <<<radio-target>>>
22275 :latex-fragment on a LaTeX fragment
22276 :latex-preview on a LaTeX fragment with overlaid preview image
22278 This function expects the position to be visible because it uses font-lock
22279 faces as a help to recognize the following contexts: :table-special, :link,
22280 and :keyword."
22281 (let* ((f (get-text-property (point) 'face))
22282 (faces (if (listp f) f (list f)))
22283 (case-fold-search t)
22284 (p (point)) clist o)
22285 ;; First the large context
22286 (cond
22287 ((org-at-heading-p t)
22288 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22289 (when (progn
22290 (beginning-of-line 1)
22291 (looking-at org-todo-line-tags-regexp))
22292 (push (org-point-in-group p 1 :headline-stars) clist)
22293 (push (org-point-in-group p 2 :todo-keyword) clist)
22294 (push (org-point-in-group p 4 :tags) clist))
22295 (goto-char p)
22296 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22297 (when (looking-at "\\[#[A-Z0-9]\\]")
22298 (push (org-point-in-group p 0 :priority) clist)))
22300 ((org-at-item-p)
22301 (push (org-point-in-group p 2 :item-bullet) clist)
22302 (push (list :item (point-at-bol)
22303 (save-excursion (org-end-of-item) (point)))
22304 clist)
22305 (and (org-at-item-checkbox-p)
22306 (push (org-point-in-group p 0 :checkbox) clist)))
22308 ((org-at-table-p)
22309 (push (list :table (org-table-begin) (org-table-end)) clist)
22310 (when (memq 'org-formula faces)
22311 (push (list :table-special
22312 (previous-single-property-change p 'face)
22313 (next-single-property-change p 'face)) clist)))
22314 ((org-at-table-p 'any)
22315 (push (list :table-table) clist)))
22316 (goto-char p)
22318 (let ((case-fold-search t))
22319 ;; New the "medium" contexts: clocktables, source blocks
22320 (cond ((org-in-clocktable-p)
22321 (push (list :clocktable
22322 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22323 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22324 (match-beginning 1))
22325 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22326 (match-end 0))) clist))
22327 ((org-in-src-block-p)
22328 (push (list :src-block
22329 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22330 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22331 (match-beginning 1))
22332 (and (search-forward "#+END_SRC" nil t)
22333 (match-beginning 0))) clist))))
22334 (goto-char p)
22336 ;; Now the small context
22337 (cond
22338 ((org-at-timestamp-p)
22339 (push (org-point-in-group p 0 :timestamp) clist))
22340 ((memq 'org-link faces)
22341 (push (list :link
22342 (previous-single-property-change p 'face)
22343 (next-single-property-change p 'face)) clist))
22344 ((memq 'org-special-keyword faces)
22345 (push (list :keyword
22346 (previous-single-property-change p 'face)
22347 (next-single-property-change p 'face)) clist))
22348 ((org-at-target-p)
22349 (push (org-point-in-group p 0 :target) clist)
22350 (goto-char (1- (match-beginning 0)))
22351 (when (looking-at org-radio-target-regexp)
22352 (push (org-point-in-group p 0 :radio-target) clist))
22353 (goto-char p))
22354 ((setq o (cl-some
22355 (lambda (o)
22356 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22358 (overlays-at (point))))
22359 (push (list :latex-fragment
22360 (overlay-start o) (overlay-end o)) clist)
22361 (push (list :latex-preview
22362 (overlay-start o) (overlay-end o)) clist))
22363 ((org-inside-LaTeX-fragment-p)
22364 ;; FIXME: positions wrong.
22365 (push (list :latex-fragment (point) (point)) clist)))
22367 (setq clist (nreverse (delq nil clist)))
22368 clist))
22370 (defun org-in-regexp (regexp &optional nlines visually)
22371 "Check if point is inside a match of REGEXP.
22373 Normally only the current line is checked, but you can include
22374 NLINES extra lines around point into the search. If VISUALLY is
22375 set, require that the cursor is not after the match but really
22376 on, so that the block visually is on the match.
22378 Return nil or a cons cell (BEG . END) where BEG and END are,
22379 respectively, the positions at the beginning and the end of the
22380 match."
22381 (catch :exit
22382 (let ((pos (point))
22383 (eol (line-end-position (if nlines (1+ nlines) 1))))
22384 (save-excursion
22385 (beginning-of-line (- 1 (or nlines 0)))
22386 (while (and (re-search-forward regexp eol t)
22387 (<= (match-beginning 0) pos))
22388 (let ((end (match-end 0)))
22389 (when (or (> end pos) (and (= end pos) (not visually)))
22390 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22392 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22393 "Non-nil when point is between matches of START-RE and END-RE.
22395 Also return a non-nil value when point is on one of the matches.
22397 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22398 buffer positions. Default values are the positions of headlines
22399 surrounding the point.
22401 The functions returns a cons cell whose car (resp. cdr) is the
22402 position before START-RE (resp. after END-RE)."
22403 (save-match-data
22404 (let ((pos (point))
22405 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22406 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22407 beg end)
22408 (save-excursion
22409 ;; Point is on a block when on START-RE or if START-RE can be
22410 ;; found before it...
22411 (and (or (org-in-regexp start-re)
22412 (re-search-backward start-re limit-up t))
22413 (setq beg (match-beginning 0))
22414 ;; ... and END-RE after it...
22415 (goto-char (match-end 0))
22416 (re-search-forward end-re limit-down t)
22417 (> (setq end (match-end 0)) pos)
22418 ;; ... without another START-RE in-between.
22419 (goto-char (match-beginning 0))
22420 (not (re-search-backward start-re (1+ beg) t))
22421 ;; Return value.
22422 (cons beg end))))))
22424 (defun org-in-block-p (names)
22425 "Non-nil when point belongs to a block whose name belongs to NAMES.
22427 NAMES is a list of strings containing names of blocks.
22429 Return first block name matched, or nil. Beware that in case of
22430 nested blocks, the returned name may not belong to the closest
22431 block from point."
22432 (save-match-data
22433 (catch 'exit
22434 (let ((case-fold-search t)
22435 (lim-up (save-excursion (outline-previous-heading)))
22436 (lim-down (save-excursion (outline-next-heading))))
22437 (dolist (name names)
22438 (let ((n (regexp-quote name)))
22439 (when (org-between-regexps-p
22440 (concat "^[ \t]*#\\+begin_" n)
22441 (concat "^[ \t]*#\\+end_" n)
22442 lim-up lim-down)
22443 (throw 'exit n)))))
22444 nil)))
22446 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22447 "Call `multi-occur' with buffers for all agenda files."
22448 (interactive "sOrg-files matching: ")
22449 (let* ((files (org-agenda-files))
22450 (tnames (mapcar #'file-truename files))
22451 (extra org-agenda-text-search-extra-files))
22452 (when (eq (car extra) 'agenda-archives)
22453 (setq extra (cdr extra))
22454 (setq files (org-add-archive-files files)))
22455 (dolist (f extra)
22456 (unless (member (file-truename f) tnames)
22457 (unless (member f files) (setq files (append files (list f))))
22458 (setq tnames (append tnames (list (file-truename f))))))
22459 (multi-occur
22460 (mapcar (lambda (x)
22461 (with-current-buffer
22462 ;; FIXME: Why not just (find-file-noselect x)?
22463 ;; Is it to avoid the "revert buffer" prompt?
22464 (or (get-file-buffer x) (find-file-noselect x))
22465 (widen)
22466 (current-buffer)))
22467 files)
22468 regexp)))
22470 (add-hook 'occur-mode-find-occurrence-hook
22471 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22473 (defun org-occur-link-in-agenda-files ()
22474 "Create a link and search for it in the agendas.
22475 The link is not stored in `org-stored-links', it is just created
22476 for the search purpose."
22477 (interactive)
22478 (let ((link (condition-case nil
22479 (org-store-link nil)
22480 (error "Unable to create a link to here"))))
22481 (org-occur-in-agenda-files (regexp-quote link))))
22483 (defun org-reverse-string (string)
22484 "Return the reverse of STRING."
22485 (apply 'string (reverse (string-to-list string))))
22487 ;; defsubst org-uniquify must be defined before first use
22489 (defun org-uniquify-alist (alist)
22490 "Merge elements of ALIST with the same key.
22492 For example, in this alist:
22494 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22495 => \\='((a 1 3) (b 2))
22497 merge (a 1) and (a 3) into (a 1 3).
22499 The function returns the new ALIST."
22500 (let (rtn)
22501 (dolist (e alist rtn)
22502 (let (n)
22503 (if (not (assoc (car e) rtn))
22504 (push e rtn)
22505 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22506 (setq rtn (assq-delete-all (car e) rtn))
22507 (push n rtn))))))
22509 (defun org-delete-all (elts list)
22510 "Remove all elements in ELTS from LIST.
22511 Comparison is done with `equal'. It is a destructive operation
22512 that may remove elements by altering the list structure."
22513 (while elts
22514 (setq list (delete (pop elts) list)))
22515 list)
22517 (defun org-back-over-empty-lines ()
22518 "Move backwards over whitespace, to the beginning of the first empty line.
22519 Returns the number of empty lines passed."
22520 (let ((pos (point)))
22521 (if (cdr (assq 'heading org-blank-before-new-entry))
22522 (skip-chars-backward " \t\n\r")
22523 (unless (eobp)
22524 (forward-line -1)))
22525 (beginning-of-line 2)
22526 (goto-char (min (point) pos))
22527 (count-lines (point) pos)))
22529 (defun org-skip-whitespace ()
22530 (skip-chars-forward " \t\n\r"))
22532 (defun org-point-in-group (point group &optional context)
22533 "Check if POINT is in match-group GROUP.
22534 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22535 match. If the match group does not exist or point is not inside it,
22536 return nil."
22537 (and (match-beginning group)
22538 (>= point (match-beginning group))
22539 (<= point (match-end group))
22540 (if context
22541 (list context (match-beginning group) (match-end group))
22542 t)))
22544 (defun org-switch-to-buffer-other-window (&rest args)
22545 "Switch to buffer in a second window on the current frame.
22546 In particular, do not allow pop-up frames.
22547 Returns the newly created buffer."
22548 (org-no-popups
22549 (apply 'switch-to-buffer-other-window args)))
22551 (defun org-combine-plists (&rest plists)
22552 "Create a single property list from all plists in PLISTS.
22553 The process starts by copying the first list, and then setting properties
22554 from the other lists. Settings in the last list are the most significant
22555 ones and overrule settings in the other lists."
22556 (let ((rtn (copy-sequence (pop plists)))
22557 p v ls)
22558 (while plists
22559 (setq ls (pop plists))
22560 (while ls
22561 (setq p (pop ls) v (pop ls))
22562 (setq rtn (plist-put rtn p v))))
22563 rtn))
22565 (defun org-replace-escapes (string table)
22566 "Replace %-escapes in STRING with values in TABLE.
22567 TABLE is an association list with keys like \"%a\" and string values.
22568 The sequences in STRING may contain normal field width and padding information,
22569 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22570 so values can contain further %-escapes if they are define later in TABLE."
22571 (let ((tbl (copy-alist table))
22572 (case-fold-search nil)
22573 (pchg 0)
22574 re rpl)
22575 (dolist (e tbl)
22576 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22577 (when (and (cdr e) (string-match re (cdr e)))
22578 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22579 (safe "SREF"))
22580 (add-text-properties 0 3 (list 'sref sref) safe)
22581 (setcdr e (replace-match safe t t (cdr e)))))
22582 (while (string-match re string)
22583 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22584 (cdr e)))
22585 (setq string (replace-match rpl t t string))))
22586 (while (setq pchg (next-property-change pchg string))
22587 (let ((sref (get-text-property pchg 'sref string)))
22588 (when (and sref (string-match "SREF" string pchg))
22589 (setq string (replace-match sref t t string)))))
22590 string))
22592 (defun org-find-base-buffer-visiting (file)
22593 "Like `find-buffer-visiting' but always return the base buffer and
22594 not an indirect buffer."
22595 (let ((buf (or (get-file-buffer file)
22596 (find-buffer-visiting file))))
22597 (if buf
22598 (or (buffer-base-buffer buf) buf)
22599 nil)))
22601 ;;; TODO: Only called once, from ox-odt which should probably use
22602 ;;; org-export-inline-image-p or something.
22603 (defun org-file-image-p (file)
22604 "Return non-nil if FILE is an image."
22605 (save-match-data
22606 (string-match (image-file-name-regexp) file)))
22608 (defun org-get-cursor-date (&optional with-time)
22609 "Return the date at cursor in as a time.
22610 This works in the calendar and in the agenda, anywhere else it just
22611 returns the current time.
22612 If WITH-TIME is non-nil, returns the time of the event at point (in
22613 the agenda) or the current time of the day."
22614 (let (date day defd tp hod mod)
22615 (when with-time
22616 (setq tp (get-text-property (point) 'time))
22617 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22618 (setq hod (string-to-number (match-string 1 tp))
22619 mod (string-to-number (match-string 2 tp))))
22620 (or tp (let ((now (decode-time)))
22621 (setq hod (nth 2 now)
22622 mod (nth 1 now)))))
22623 (cond
22624 ((eq major-mode 'calendar-mode)
22625 (setq date (calendar-cursor-to-date)
22626 defd (encode-time 0 (or mod 0) (or hod 0)
22627 (nth 1 date) (nth 0 date) (nth 2 date))))
22628 ((eq major-mode 'org-agenda-mode)
22629 (setq day (get-text-property (point) 'day))
22630 (when day
22631 (setq date (calendar-gregorian-from-absolute day)
22632 defd (encode-time 0 (or mod 0) (or hod 0)
22633 (nth 1 date) (nth 0 date) (nth 2 date))))))
22634 (or defd (current-time))))
22636 (defun org-mark-subtree (&optional up)
22637 "Mark the current subtree.
22638 This puts point at the start of the current subtree, and mark at
22639 the end. If a numeric prefix UP is given, move up into the
22640 hierarchy of headlines by UP levels before marking the subtree."
22641 (interactive "P")
22642 (org-with-limited-levels
22643 (cond ((org-at-heading-p) (beginning-of-line))
22644 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22645 (t (outline-previous-visible-heading 1))))
22646 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22647 (if (called-interactively-p 'any)
22648 (call-interactively 'org-mark-element)
22649 (org-mark-element)))
22651 (defun org-file-newer-than-p (file time)
22652 "Non-nil if FILE is newer than TIME.
22653 FILE is a filename, as a string, TIME is a list of integers, as
22654 returned by, e.g., `current-time'."
22655 (and (file-exists-p file)
22656 ;; Only compare times up to whole seconds as some file-systems
22657 ;; (e.g. HFS+) do not retain any finer granularity. As
22658 ;; a consequence, make sure we return non-nil when the two
22659 ;; times are equal.
22660 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22661 (cl-subseq time 0 2)))))
22663 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22664 "Compile a SOURCE file using PROCESS.
22666 PROCESS is either a function or a list of shell commands, as
22667 strings. EXT is a file extension, without the leading dot, as
22668 a string. It is used to check if the process actually succeeded.
22670 PROCESS must create a file with the same base name and directory
22671 as SOURCE, but ending with EXT. The function then returns its
22672 filename. Otherwise, it raises an error. The error message can
22673 then be refined by providing string ERR-MSG, which is appended to
22674 the standard message.
22676 If PROCESS is a function, it is called with a single argument:
22677 the SOURCE file.
22679 If it is a list of commands, each of them is called using
22680 `shell-command'. By default, in each command, %b, %f, %F, %o and
22681 %O are replaced with, respectively, SOURCE base name, name, full
22682 name, directory and absolute output file name. It is possible,
22683 however, to use more place-holders by specifying them in optional
22684 argument SPEC, as an alist following the pattern
22686 (CHARACTER . REPLACEMENT-STRING).
22688 When PROCESS is a list of commands, optional argument LOG-BUF can
22689 be set to a buffer or a buffer name. `shell-command' then uses
22690 it for output."
22691 (let* ((base-name (file-name-base source))
22692 (full-name (file-truename source))
22693 (out-dir (or (file-name-directory source) "./"))
22694 (output (expand-file-name (concat base-name "." ext) out-dir))
22695 (time (current-time))
22696 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22697 (save-window-excursion
22698 (pcase process
22699 ((pred functionp) (funcall process (shell-quote-argument source)))
22700 ((pred consp)
22701 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22702 (spec (append spec
22703 `((?b . ,(shell-quote-argument base-name))
22704 (?f . ,(shell-quote-argument source))
22705 (?F . ,(shell-quote-argument full-name))
22706 (?o . ,(shell-quote-argument out-dir))
22707 (?O . ,(shell-quote-argument output))))))
22708 (dolist (command process)
22709 (shell-command (format-spec command spec) log-buf))))
22710 (_ (error "No valid command to process %S%s" source err-msg))))
22711 ;; Check for process failure. Output file is expected to be
22712 ;; located in the same directory as SOURCE.
22713 (unless (org-file-newer-than-p output time)
22714 (error (format "File %S wasn't produced%s" output err-msg)))
22715 output))
22717 ;;; Indentation
22719 (defun org--get-expected-indentation (element contentsp)
22720 "Expected indentation column for current line, according to ELEMENT.
22721 ELEMENT is an element containing point. CONTENTSP is non-nil
22722 when indentation is to be computed according to contents of
22723 ELEMENT."
22724 (let ((type (org-element-type element))
22725 (start (org-element-property :begin element))
22726 (post-affiliated (org-element-property :post-affiliated element)))
22727 (org-with-wide-buffer
22728 (cond
22729 (contentsp
22730 (cl-case type
22731 ((diary-sexp footnote-definition) 0)
22732 ((headline inlinetask nil)
22733 (if (not org-adapt-indentation) 0
22734 (let ((level (org-current-level)))
22735 (if level (1+ level) 0))))
22736 ((item plain-list) (org-list-item-body-column post-affiliated))
22738 (goto-char start)
22739 (org-get-indentation))))
22740 ((memq type '(headline inlinetask nil))
22741 (if (org-match-line "[ \t]*$")
22742 (org--get-expected-indentation element t)
22744 ((memq type '(diary-sexp footnote-definition)) 0)
22745 ;; First paragraph of a footnote definition or an item.
22746 ;; Indent like parent.
22747 ((< (line-beginning-position) start)
22748 (org--get-expected-indentation
22749 (org-element-property :parent element) t))
22750 ;; At first line: indent according to previous sibling, if any,
22751 ;; ignoring footnote definitions and inline tasks, or parent's
22752 ;; contents.
22753 ((= (line-beginning-position) start)
22754 (catch 'exit
22755 (while t
22756 (if (= (point-min) start) (throw 'exit 0)
22757 (goto-char (1- start))
22758 (let* ((previous (org-element-at-point))
22759 (parent previous))
22760 (while (and parent (<= (org-element-property :end parent) start))
22761 (setq previous parent
22762 parent (org-element-property :parent parent)))
22763 (cond
22764 ((not previous) (throw 'exit 0))
22765 ((> (org-element-property :end previous) start)
22766 (throw 'exit (org--get-expected-indentation previous t)))
22767 ((memq (org-element-type previous)
22768 '(footnote-definition inlinetask))
22769 (setq start (org-element-property :begin previous)))
22770 (t (goto-char (org-element-property :begin previous))
22771 (throw 'exit
22772 (if (bolp) (org-get-indentation)
22773 ;; At first paragraph in an item or
22774 ;; a footnote definition.
22775 (org--get-expected-indentation
22776 (org-element-property :parent previous) t))))))))))
22777 ;; Otherwise, move to the first non-blank line above.
22779 (beginning-of-line)
22780 (let ((pos (point)))
22781 (skip-chars-backward " \r\t\n")
22782 (cond
22783 ;; Two blank lines end a footnote definition or a plain
22784 ;; list. When we indent an empty line after them, the
22785 ;; containing list or footnote definition is over, so it
22786 ;; qualifies as a previous sibling. Therefore, we indent
22787 ;; like its first line.
22788 ((and (memq type '(footnote-definition plain-list))
22789 (> (count-lines (point) pos) 2))
22790 (goto-char start)
22791 (org-get-indentation))
22792 ;; Line above is the first one of a paragraph at the
22793 ;; beginning of an item or a footnote definition. Indent
22794 ;; like parent.
22795 ((< (line-beginning-position) start)
22796 (org--get-expected-indentation
22797 (org-element-property :parent element) t))
22798 ;; Line above is the beginning of an element, i.e., point
22799 ;; was originally on the blank lines between element's start
22800 ;; and contents.
22801 ((= (line-beginning-position) post-affiliated)
22802 (org--get-expected-indentation element t))
22803 ;; POS is after contents in a greater element. Indent like
22804 ;; the beginning of the element.
22806 ;; As a special case, if point is at the end of a footnote
22807 ;; definition or an item, indent like the very last element
22808 ;; within. If that last element is an item, indent like its
22809 ;; contents.
22810 ((and (not (eq type 'paragraph))
22811 (let ((cend (org-element-property :contents-end element)))
22812 (and cend (<= cend pos))))
22813 (if (memq type '(footnote-definition item plain-list))
22814 (let ((last (org-element-at-point)))
22815 (org--get-expected-indentation
22816 last (eq (org-element-type last) 'item)))
22817 (goto-char start)
22818 (org-get-indentation)))
22819 ;; In any other case, indent like the current line.
22820 (t (org-get-indentation)))))))))
22822 (defun org--align-node-property ()
22823 "Align node property at point.
22824 Alignment is done according to `org-property-format', which see."
22825 (when (save-excursion
22826 (beginning-of-line)
22827 (looking-at org-property-re))
22828 (replace-match
22829 (concat (match-string 4)
22830 (org-trim
22831 (format org-property-format (match-string 1) (match-string 3))))
22832 t t)))
22834 (defun org-indent-line ()
22835 "Indent line depending on context.
22837 Indentation is done according to the following rules:
22839 - Footnote definitions, diary sexps, headlines and inline tasks
22840 have to start at column 0.
22842 - On the very first line of an element, consider, in order, the
22843 next rules until one matches:
22845 1. If there's a sibling element before, ignoring footnote
22846 definitions and inline tasks, indent like its first line.
22848 2. If element has a parent, indent like its contents. More
22849 precisely, if parent is an item, indent after the
22850 description part, if any, or the bullet (see
22851 `org-list-description-max-indent'). Else, indent like
22852 parent's first line.
22854 3. Otherwise, indent relatively to current level, if
22855 `org-adapt-indentation' is non-nil, or to left margin.
22857 - On a blank line at the end of an element, indent according to
22858 the type of the element. More precisely
22860 1. If element is a plain list, an item, or a footnote
22861 definition, indent like the very last element within.
22863 2. If element is a paragraph, indent like its last non blank
22864 line.
22866 3. Otherwise, indent like its very first line.
22868 - In the code part of a source block, use language major mode
22869 to indent current line if `org-src-tab-acts-natively' is
22870 non-nil. If it is nil, do nothing.
22872 - Otherwise, indent like the first non-blank line above.
22874 The function doesn't indent an item as it could break the whole
22875 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22876 `\\[org-shiftmetaright]'.
22878 Also align node properties according to `org-property-format'."
22879 (interactive)
22880 (cond
22881 (orgstruct-is-++
22882 (let ((indent-line-function
22883 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22884 (indent-according-to-mode)))
22885 ((org-at-heading-p) 'noindent)
22887 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22888 (type (org-element-type element)))
22889 (cond ((and (memq type '(plain-list item))
22890 (= (line-beginning-position)
22891 (org-element-property :post-affiliated element)))
22892 'noindent)
22893 ((and (eq type 'latex-environment)
22894 (>= (point) (org-element-property :post-affiliated element))
22895 (< (point) (org-with-wide-buffer
22896 (goto-char (org-element-property :end element))
22897 (skip-chars-backward " \r\t\n")
22898 (line-beginning-position 2))))
22899 'noindent)
22900 ((and (eq type 'src-block)
22901 org-src-tab-acts-natively
22902 (> (line-beginning-position)
22903 (org-element-property :post-affiliated element))
22904 (< (line-beginning-position)
22905 (org-with-wide-buffer
22906 (goto-char (org-element-property :end element))
22907 (skip-chars-backward " \r\t\n")
22908 (line-beginning-position))))
22909 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22911 (let ((column (org--get-expected-indentation element nil)))
22912 ;; Preserve current column.
22913 (if (<= (current-column) (current-indentation))
22914 (indent-line-to column)
22915 (save-excursion (indent-line-to column))))
22916 ;; Align node property. Also preserve current column.
22917 (when (eq type 'node-property)
22918 (let ((column (current-column)))
22919 (org--align-node-property)
22920 (org-move-to-column column)))))))))
22922 (defun org-indent-region (start end)
22923 "Indent each non-blank line in the region.
22924 Called from a program, START and END specify the region to
22925 indent. The function will not indent contents of example blocks,
22926 verse blocks and export blocks as leading white spaces are
22927 assumed to be significant there."
22928 (interactive "r")
22929 (save-excursion
22930 (goto-char start)
22931 (skip-chars-forward " \r\t\n")
22932 (unless (eobp) (beginning-of-line))
22933 (let ((indent-to
22934 (lambda (ind pos)
22935 ;; Set IND as indentation for all lines between point and
22936 ;; POS. Blank lines are ignored. Leave point after POS
22937 ;; once done.
22938 (let ((limit (copy-marker pos)))
22939 (while (< (point) limit)
22940 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22941 (forward-line))
22942 (set-marker limit nil))))
22943 (end (copy-marker end)))
22944 (while (< (point) end)
22945 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22946 (let* ((element (org-element-at-point))
22947 (type (org-element-type element))
22948 (element-end (copy-marker (org-element-property :end element)))
22949 (ind (org--get-expected-indentation element nil)))
22950 (cond
22951 ;; Element indented as a single block. Example blocks
22952 ;; preserving indentation are a special case since the
22953 ;; "contents" must not be indented whereas the block
22954 ;; boundaries can.
22955 ((or (memq type '(export-block latex-environment))
22956 (and (eq type 'example-block)
22957 (not
22958 (or org-src-preserve-indentation
22959 (org-element-property :preserve-indent element)))))
22960 (let ((offset (- ind (org-get-indentation))))
22961 (unless (zerop offset)
22962 (indent-rigidly (org-element-property :begin element)
22963 (org-element-property :end element)
22964 offset)))
22965 (goto-char element-end))
22966 ;; Elements indented line wise. Be sure to exclude
22967 ;; example blocks (preserving indentation) and source
22968 ;; blocks from this category as they are treated
22969 ;; specially later.
22970 ((or (memq type '(paragraph table table-row))
22971 (not (or (org-element-property :contents-begin element)
22972 (memq type '(example-block src-block)))))
22973 (when (eq type 'node-property)
22974 (org--align-node-property)
22975 (beginning-of-line))
22976 (funcall indent-to ind (min element-end end)))
22977 ;; Elements consisting of three parts: before the
22978 ;; contents, the contents, and after the contents. The
22979 ;; contents are treated specially, according to the
22980 ;; element type, or not indented at all. Other parts are
22981 ;; indented as a single block.
22983 (let* ((post (copy-marker
22984 (org-element-property :post-affiliated element)))
22985 (cbeg
22986 (copy-marker
22987 (cond
22988 ((not (org-element-property :contents-begin element))
22989 ;; Fake contents for source blocks.
22990 (org-with-wide-buffer
22991 (goto-char post)
22992 (line-beginning-position 2)))
22993 ((memq type '(footnote-definition item plain-list))
22994 ;; Contents in these elements could start on
22995 ;; the same line as the beginning of the
22996 ;; element. Make sure we start indenting
22997 ;; from the second line.
22998 (org-with-wide-buffer
22999 (goto-char post)
23000 (end-of-line)
23001 (skip-chars-forward " \r\t\n")
23002 (if (eobp) (point) (line-beginning-position))))
23003 (t (org-element-property :contents-begin element)))))
23004 (cend (copy-marker
23005 (or (org-element-property :contents-end element)
23006 ;; Fake contents for source blocks.
23007 (org-with-wide-buffer
23008 (goto-char element-end)
23009 (skip-chars-backward " \r\t\n")
23010 (line-beginning-position)))
23011 t)))
23012 ;; Do not change items indentation individually as it
23013 ;; might break the list as a whole. On the other
23014 ;; hand, when at a plain list, indent it as a whole.
23015 (cond ((eq type 'plain-list)
23016 (let ((offset (- ind (org-get-indentation))))
23017 (unless (zerop offset)
23018 (indent-rigidly (org-element-property :begin element)
23019 (org-element-property :end element)
23020 offset))
23021 (goto-char cbeg)))
23022 ((eq type 'item) (goto-char cbeg))
23023 (t (funcall indent-to ind (min cbeg end))))
23024 (when (< (point) end)
23025 (cl-case type
23026 ((example-block verse-block))
23027 (src-block
23028 ;; In a source block, indent source code
23029 ;; according to language major mode, but only if
23030 ;; `org-src-tab-acts-natively' is non-nil.
23031 (when (and (< (point) end) org-src-tab-acts-natively)
23032 (ignore-errors
23033 (org-babel-do-in-edit-buffer
23034 (indent-region (point-min) (point-max))))))
23035 (t (org-indent-region (point) (min cend end))))
23036 (goto-char (min cend end))
23037 (when (< (point) end)
23038 (funcall indent-to ind (min element-end end))))
23039 (set-marker post nil)
23040 (set-marker cbeg nil)
23041 (set-marker cend nil))))
23042 (set-marker element-end nil))))
23043 (set-marker end nil))))
23045 (defun org-indent-drawer ()
23046 "Indent the drawer at point."
23047 (interactive)
23048 (unless (save-excursion
23049 (beginning-of-line)
23050 (looking-at-p org-drawer-regexp))
23051 (user-error "Not at a drawer"))
23052 (let ((element (org-element-at-point)))
23053 (unless (memq (org-element-type element) '(drawer property-drawer))
23054 (user-error "Not at a drawer"))
23055 (org-with-wide-buffer
23056 (org-indent-region (org-element-property :begin element)
23057 (org-element-property :end element))))
23058 (message "Drawer at point indented"))
23060 (defun org-indent-block ()
23061 "Indent the block at point."
23062 (interactive)
23063 (unless (save-excursion
23064 (beginning-of-line)
23065 (let ((case-fold-search t))
23066 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23067 (user-error "Not at a block"))
23068 (let ((element (org-element-at-point)))
23069 (unless (memq (org-element-type element)
23070 '(comment-block center-block dynamic-block example-block
23071 export-block quote-block special-block
23072 src-block verse-block))
23073 (user-error "Not at a block"))
23074 (org-with-wide-buffer
23075 (org-indent-region (org-element-property :begin element)
23076 (org-element-property :end element))))
23077 (message "Block at point indented"))
23080 ;;; Filling
23082 ;; We use our own fill-paragraph and auto-fill functions.
23084 ;; `org-fill-paragraph' relies on adaptive filling and context
23085 ;; checking. Appropriate `fill-prefix' is computed with
23086 ;; `org-adaptive-fill-function'.
23088 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23089 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23090 ;; `org-adaptive-fill-function' value. Internally,
23091 ;; `org-comment-line-break-function' breaks the line.
23093 ;; `org-setup-filling' installs filling and auto-filling related
23094 ;; variables during `org-mode' initialization.
23096 (defvar org-element-paragraph-separate) ; org-element.el
23097 (defun org-setup-filling ()
23098 (require 'org-element)
23099 ;; Prevent auto-fill from inserting unwanted new items.
23100 (when (boundp 'fill-nobreak-predicate)
23101 (setq-local
23102 fill-nobreak-predicate
23103 (org-uniquify
23104 (append fill-nobreak-predicate
23105 '(org-fill-line-break-nobreak-p
23106 org-fill-paragraph-with-timestamp-nobreak-p)))))
23107 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23108 (setq-local paragraph-start paragraph-ending)
23109 (setq-local paragraph-separate paragraph-ending))
23110 (setq-local fill-paragraph-function 'org-fill-paragraph)
23111 (setq-local auto-fill-inhibit-regexp nil)
23112 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23113 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23114 (setq-local comment-line-break-function 'org-comment-line-break-function))
23116 (defun org-fill-line-break-nobreak-p ()
23117 "Non-nil when a new line at point would create an Org line break."
23118 (save-excursion
23119 (skip-chars-backward "[ \t]")
23120 (skip-chars-backward "\\\\")
23121 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23123 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23124 "Non-nil when a new line at point would split a timestamp."
23125 (and (org-at-timestamp-p t)
23126 (not (looking-at org-ts-regexp-both))))
23128 (declare-function message-in-body-p "message" ())
23129 (defvar orgtbl-line-start-regexp) ; From org-table.el
23130 (defun org-adaptive-fill-function ()
23131 "Compute a fill prefix for the current line.
23132 Return fill prefix, as a string, or nil if current line isn't
23133 meant to be filled. For convenience, if `adaptive-fill-regexp'
23134 matches in paragraphs or comments, use it."
23135 (catch 'exit
23136 (when (derived-mode-p 'message-mode)
23137 (save-excursion
23138 (beginning-of-line)
23139 (cond ((not (message-in-body-p)) (throw 'exit nil))
23140 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23141 ((looking-at message-cite-prefix-regexp)
23142 (throw 'exit (match-string-no-properties 0)))
23143 ((looking-at org-outline-regexp)
23144 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23145 (org-with-wide-buffer
23146 (unless (org-at-heading-p)
23147 (let* ((p (line-beginning-position))
23148 (element (save-excursion
23149 (beginning-of-line)
23150 (org-element-at-point)))
23151 (type (org-element-type element))
23152 (post-affiliated (org-element-property :post-affiliated element)))
23153 (unless (< p post-affiliated)
23154 (cl-case type
23155 (comment
23156 (save-excursion
23157 (beginning-of-line)
23158 (looking-at "[ \t]*")
23159 (concat (match-string 0) "# ")))
23160 (footnote-definition "")
23161 ((item plain-list)
23162 (make-string (org-list-item-body-column post-affiliated) ?\s))
23163 (paragraph
23164 ;; Fill prefix is usually the same as the current line,
23165 ;; unless the paragraph is at the beginning of an item.
23166 (let ((parent (org-element-property :parent element)))
23167 (save-excursion
23168 (beginning-of-line)
23169 (cond ((eq (org-element-type parent) 'item)
23170 (make-string (org-list-item-body-column
23171 (org-element-property :begin parent))
23172 ?\s))
23173 ((and adaptive-fill-regexp
23174 ;; Locally disable
23175 ;; `adaptive-fill-function' to let
23176 ;; `fill-context-prefix' handle
23177 ;; `adaptive-fill-regexp' variable.
23178 (let (adaptive-fill-function)
23179 (fill-context-prefix
23180 post-affiliated
23181 (org-element-property :end element)))))
23182 ((looking-at "[ \t]+") (match-string 0))
23183 (t "")))))
23184 (comment-block
23185 ;; Only fill contents if P is within block boundaries.
23186 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23187 (forward-line)
23188 (point)))
23189 (cend (save-excursion
23190 (goto-char (org-element-property :end element))
23191 (skip-chars-backward " \r\t\n")
23192 (line-beginning-position))))
23193 (when (and (>= p cbeg) (< p cend))
23194 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23195 (match-string 0)
23196 "")))))))))))
23198 (declare-function message-goto-body "message" ())
23199 (defvar message-cite-prefix-regexp) ; From message.el
23200 (defun org-fill-paragraph (&optional justify)
23201 "Fill element at point, when applicable.
23203 This function only applies to comment blocks, comments, example
23204 blocks and paragraphs. Also, as a special case, re-align table
23205 when point is at one.
23207 If JUSTIFY is non-nil (interactively, with prefix argument),
23208 justify as well. If `sentence-end-double-space' is non-nil, then
23209 period followed by one space does not end a sentence, so don't
23210 break a line there. The variable `fill-column' controls the
23211 width for filling.
23213 For convenience, when point is at a plain list, an item or
23214 a footnote definition, try to fill the first paragraph within."
23215 (interactive)
23216 (if (and (derived-mode-p 'message-mode)
23217 (or (not (message-in-body-p))
23218 (save-excursion (move-beginning-of-line 1)
23219 (looking-at message-cite-prefix-regexp))))
23220 ;; First ensure filling is correct in message-mode.
23221 (let ((fill-paragraph-function
23222 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23223 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23224 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23225 (paragraph-separate
23226 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23227 (fill-paragraph nil))
23228 (with-syntax-table org-mode-transpose-word-syntax-table
23229 ;; Move to end of line in order to get the first paragraph
23230 ;; within a plain list or a footnote definition.
23231 (let ((element (save-excursion
23232 (end-of-line)
23233 (or (ignore-errors (org-element-at-point))
23234 (user-error "An element cannot be parsed line %d"
23235 (line-number-at-pos (point)))))))
23236 ;; First check if point is in a blank line at the beginning of
23237 ;; the buffer. In that case, ignore filling.
23238 (cl-case (org-element-type element)
23239 ;; Use major mode filling function is src blocks.
23240 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23241 ;; Align Org tables, leave table.el tables as-is.
23242 (table-row (org-table-align) t)
23243 (table
23244 (when (eq (org-element-property :type element) 'org)
23245 (save-excursion
23246 (goto-char (org-element-property :post-affiliated element))
23247 (org-table-align)))
23249 (paragraph
23250 ;; Paragraphs may contain `line-break' type objects.
23251 (let ((beg (max (point-min)
23252 (org-element-property :contents-begin element)))
23253 (end (min (point-max)
23254 (org-element-property :contents-end element))))
23255 ;; Do nothing if point is at an affiliated keyword.
23256 (if (< (line-end-position) beg) t
23257 (when (derived-mode-p 'message-mode)
23258 ;; In `message-mode', do not fill following citation
23259 ;; in current paragraph nor text before message body.
23260 (let ((body-start (save-excursion (message-goto-body))))
23261 (when body-start (setq beg (max body-start beg))))
23262 (when (save-excursion
23263 (re-search-forward
23264 (concat "^" message-cite-prefix-regexp) end t))
23265 (setq end (match-beginning 0))))
23266 ;; Fill paragraph, taking line breaks into account.
23267 (save-excursion
23268 (goto-char beg)
23269 (let ((cuts (list beg)))
23270 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23271 (when (eq 'line-break
23272 (org-element-type
23273 (save-excursion (backward-char)
23274 (org-element-context))))
23275 (push (point) cuts)))
23276 (dolist (c (delq end cuts))
23277 (fill-region-as-paragraph c end justify)
23278 (setq end c))))
23279 t)))
23280 ;; Contents of `comment-block' type elements should be
23281 ;; filled as plain text, but only if point is within block
23282 ;; markers.
23283 (comment-block
23284 (let* ((case-fold-search t)
23285 (beg (save-excursion
23286 (goto-char (org-element-property :begin element))
23287 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23288 (forward-line)
23289 (point)))
23290 (end (save-excursion
23291 (goto-char (org-element-property :end element))
23292 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23293 (line-beginning-position))))
23294 (if (or (< (point) beg) (> (point) end)) t
23295 (fill-region-as-paragraph
23296 (save-excursion (end-of-line)
23297 (re-search-backward "^[ \t]*$" beg 'move)
23298 (line-beginning-position))
23299 (save-excursion (beginning-of-line)
23300 (re-search-forward "^[ \t]*$" end 'move)
23301 (line-beginning-position))
23302 justify))))
23303 ;; Fill comments.
23304 (comment
23305 (let ((begin (org-element-property :post-affiliated element))
23306 (end (org-element-property :end element)))
23307 (when (and (>= (point) begin) (<= (point) end))
23308 (let ((begin (save-excursion
23309 (end-of-line)
23310 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23311 (progn (forward-line) (point))
23312 begin)))
23313 (end (save-excursion
23314 (end-of-line)
23315 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23316 (1- (line-beginning-position))
23317 (skip-chars-backward " \r\t\n")
23318 (line-end-position)))))
23319 ;; Do not fill comments when at a blank line.
23320 (when (> end begin)
23321 (let ((fill-prefix
23322 (save-excursion
23323 (beginning-of-line)
23324 (looking-at "[ \t]*#")
23325 (let ((comment-prefix (match-string 0)))
23326 (goto-char (match-end 0))
23327 (if (looking-at adaptive-fill-regexp)
23328 (concat comment-prefix (match-string 0))
23329 (concat comment-prefix " "))))))
23330 (save-excursion
23331 (fill-region-as-paragraph begin end justify))))))
23333 ;; Ignore every other element.
23334 (otherwise t))))))
23336 (defun org-auto-fill-function ()
23337 "Auto-fill function."
23338 ;; Check if auto-filling is meaningful.
23339 (let ((fc (current-fill-column)))
23340 (when (and fc (> (current-column) fc))
23341 (let* ((fill-prefix (org-adaptive-fill-function))
23342 ;; Enforce empty fill prefix, if required. Otherwise, it
23343 ;; will be computed again.
23344 (adaptive-fill-mode (not (equal fill-prefix ""))))
23345 (when fill-prefix (do-auto-fill))))))
23347 (defun org-comment-line-break-function (&optional soft)
23348 "Break line at point and indent, continuing comment if within one.
23349 The inserted newline is marked hard if variable
23350 `use-hard-newlines' is true, unless optional argument SOFT is
23351 non-nil."
23352 (if soft (insert-and-inherit ?\n) (newline 1))
23353 (save-excursion (forward-char -1) (delete-horizontal-space))
23354 (delete-horizontal-space)
23355 (indent-to-left-margin)
23356 (insert-before-markers-and-inherit fill-prefix))
23359 ;;; Fixed Width Areas
23361 (defun org-toggle-fixed-width ()
23362 "Toggle fixed-width markup.
23364 Add or remove fixed-width markup on current line, whenever it
23365 makes sense. Return an error otherwise.
23367 If a region is active and if it contains only fixed-width areas
23368 or blank lines, remove all fixed-width markup in it. If the
23369 region contains anything else, convert all non-fixed-width lines
23370 to fixed-width ones.
23372 Blank lines at the end of the region are ignored unless the
23373 region only contains such lines."
23374 (interactive)
23375 (if (not (org-region-active-p))
23376 ;; No region:
23378 ;; Remove fixed width marker only in a fixed-with element.
23380 ;; Add fixed width maker in paragraphs, in blank lines after
23381 ;; elements or at the beginning of a headline or an inlinetask,
23382 ;; and before any one-line elements (e.g., a clock).
23383 (progn
23384 (beginning-of-line)
23385 (let* ((element (org-element-at-point))
23386 (type (org-element-type element)))
23387 (cond
23388 ((and (eq type 'fixed-width)
23389 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23390 (replace-match
23391 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23392 ((and (memq type '(babel-call clock comment diary-sexp headline
23393 horizontal-rule keyword paragraph
23394 planning))
23395 (<= (org-element-property :post-affiliated element) (point)))
23396 (skip-chars-forward " \t")
23397 (insert ": "))
23398 ((and (looking-at-p "[ \t]*$")
23399 (or (eq type 'inlinetask)
23400 (save-excursion
23401 (skip-chars-forward " \r\t\n")
23402 (<= (org-element-property :end element) (point)))))
23403 (delete-region (point) (line-end-position))
23404 (org-indent-line)
23405 (insert ": "))
23406 (t (user-error "Cannot insert a fixed-width line here")))))
23407 ;; Region active.
23408 (let* ((begin (save-excursion
23409 (goto-char (region-beginning))
23410 (line-beginning-position)))
23411 (end (copy-marker
23412 (save-excursion
23413 (goto-char (region-end))
23414 (unless (eolp) (beginning-of-line))
23415 (if (save-excursion (re-search-backward "\\S-" begin t))
23416 (progn (skip-chars-backward " \r\t\n") (point))
23417 (point)))))
23418 (all-fixed-width-p
23419 (catch 'not-all-p
23420 (save-excursion
23421 (goto-char begin)
23422 (skip-chars-forward " \r\t\n")
23423 (when (eobp) (throw 'not-all-p nil))
23424 (while (< (point) end)
23425 (let ((element (org-element-at-point)))
23426 (if (eq (org-element-type element) 'fixed-width)
23427 (goto-char (org-element-property :end element))
23428 (throw 'not-all-p nil))))
23429 t))))
23430 (if all-fixed-width-p
23431 (save-excursion
23432 (goto-char begin)
23433 (while (< (point) end)
23434 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23435 (replace-match
23436 "" nil nil nil
23437 (if (= (line-end-position) (match-end 0)) 0 1)))
23438 (forward-line)))
23439 (let ((min-ind (point-max)))
23440 ;; Find minimum indentation across all lines.
23441 (save-excursion
23442 (goto-char begin)
23443 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23444 (setq min-ind 0)
23445 (catch 'zerop
23446 (while (< (point) end)
23447 (unless (looking-at-p "[ \t]*$")
23448 (let ((ind (org-get-indentation)))
23449 (setq min-ind (min min-ind ind))
23450 (when (zerop ind) (throw 'zerop t))))
23451 (forward-line)))))
23452 ;; Loop over all lines and add fixed-width markup everywhere
23453 ;; but in fixed-width lines.
23454 (save-excursion
23455 (goto-char begin)
23456 (while (< (point) end)
23457 (cond
23458 ((org-at-heading-p)
23459 (insert ": ")
23460 (forward-line)
23461 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23462 (insert ":")
23463 (forward-line)))
23464 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23465 (let* ((element (org-element-at-point))
23466 (element-end (org-element-property :end element)))
23467 (if (eq (org-element-type element) 'fixed-width)
23468 (progn (goto-char element-end)
23469 (skip-chars-backward " \r\t\n")
23470 (forward-line))
23471 (let ((limit (min end element-end)))
23472 (while (< (point) limit)
23473 (org-move-to-column min-ind t)
23474 (insert ": ")
23475 (forward-line))))))
23477 (org-move-to-column min-ind t)
23478 (insert ": ")
23479 (forward-line)))))))
23480 (set-marker end nil))))
23483 ;;; Comments
23485 ;; Org comments syntax is quite complex. It requires the entire line
23486 ;; to be just a comment. Also, even with the right syntax at the
23487 ;; beginning of line, some some elements (i.e. verse-block or
23488 ;; example-block) don't accept comments. Usual Emacs comment commands
23489 ;; cannot cope with those requirements. Therefore, Org replaces them.
23491 ;; Org still relies on `comment-dwim', but cannot trust
23492 ;; `comment-only-p'. So, `comment-region-function' and
23493 ;; `uncomment-region-function' both point
23494 ;; to`org-comment-or-uncomment-region'. Eventually,
23495 ;; `org-insert-comment' takes care of insertion of comments at the
23496 ;; beginning of line.
23498 ;; `org-setup-comments-handling' install comments related variables
23499 ;; during `org-mode' initialization.
23501 (defun org-setup-comments-handling ()
23502 (interactive)
23503 (setq-local comment-use-syntax nil)
23504 (setq-local comment-start "# ")
23505 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23506 (setq-local comment-insert-comment-function 'org-insert-comment)
23507 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23508 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23510 (defun org-insert-comment ()
23511 "Insert an empty comment above current line.
23512 If the line is empty, insert comment at its beginning. When
23513 point is within a source block, comment according to the related
23514 major mode."
23515 (if (let ((element (org-element-at-point)))
23516 (and (eq (org-element-type element) 'src-block)
23517 (< (save-excursion
23518 (goto-char (org-element-property :post-affiliated element))
23519 (line-end-position))
23520 (point))
23521 (> (save-excursion
23522 (goto-char (org-element-property :end element))
23523 (skip-chars-backward " \r\t\n")
23524 (line-beginning-position))
23525 (point))))
23526 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23527 (beginning-of-line)
23528 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23529 (open-line 1))
23530 (org-indent-line)
23531 (insert "# ")))
23533 (defvar comment-empty-lines) ; From newcomment.el.
23534 (defun org-comment-or-uncomment-region (beg end &rest _)
23535 "Comment or uncomment each non-blank line in the region.
23536 Uncomment each non-blank line between BEG and END if it only
23537 contains commented lines. Otherwise, comment them. If region is
23538 strictly within a source block, use appropriate comment syntax."
23539 (if (let ((element (org-element-at-point)))
23540 (and (eq (org-element-type element) 'src-block)
23541 (< (save-excursion
23542 (goto-char (org-element-property :post-affiliated element))
23543 (line-end-position))
23544 beg)
23545 (>= (save-excursion
23546 (goto-char (org-element-property :end element))
23547 (skip-chars-backward " \r\t\n")
23548 (line-beginning-position))
23549 end)))
23550 ;; Translate region boundaries for the Org buffer to the source
23551 ;; buffer.
23552 (let ((offset (- end beg)))
23553 (save-excursion
23554 (goto-char beg)
23555 (org-babel-do-in-edit-buffer
23556 (comment-or-uncomment-region (point) (+ offset (point))))))
23557 (save-restriction
23558 ;; Restrict region
23559 (narrow-to-region (save-excursion (goto-char beg)
23560 (skip-chars-forward " \r\t\n" end)
23561 (line-beginning-position))
23562 (save-excursion (goto-char end)
23563 (skip-chars-backward " \r\t\n" beg)
23564 (line-end-position)))
23565 (let ((uncommentp
23566 ;; UNCOMMENTP is non-nil when every non blank line between
23567 ;; BEG and END is a comment.
23568 (save-excursion
23569 (goto-char (point-min))
23570 (while (and (not (eobp))
23571 (let ((element (org-element-at-point)))
23572 (and (eq (org-element-type element) 'comment)
23573 (goto-char (min (point-max)
23574 (org-element-property
23575 :end element)))))))
23576 (eobp))))
23577 (if uncommentp
23578 ;; Only blank lines and comments in region: uncomment it.
23579 (save-excursion
23580 (goto-char (point-min))
23581 (while (not (eobp))
23582 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23583 (replace-match "" nil nil nil 1))
23584 (forward-line)))
23585 ;; Comment each line in region.
23586 (let ((min-indent (point-max)))
23587 ;; First find the minimum indentation across all lines.
23588 (save-excursion
23589 (goto-char (point-min))
23590 (while (and (not (eobp)) (not (zerop min-indent)))
23591 (unless (looking-at "[ \t]*$")
23592 (setq min-indent (min min-indent (current-indentation))))
23593 (forward-line)))
23594 ;; Then loop over all lines.
23595 (save-excursion
23596 (goto-char (point-min))
23597 (while (not (eobp))
23598 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23599 ;; Don't get fooled by invisible text (e.g. link path)
23600 ;; when moving to column MIN-INDENT.
23601 (let ((buffer-invisibility-spec nil))
23602 (org-move-to-column min-indent t))
23603 (insert comment-start))
23604 (forward-line)))))))))
23606 (defun org-comment-dwim (_arg)
23607 "Call `comment-dwim' within a source edit buffer if needed."
23608 (interactive "*P")
23609 (if (org-in-src-block-p)
23610 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23611 (call-interactively 'comment-dwim)))
23614 ;;; Timestamps API
23616 ;; This section contains tools to operate on timestamp objects, as
23617 ;; returned by, e.g. `org-element-context'.
23619 (defun org-timestamp--to-internal-time (timestamp &optional end)
23620 "Encode TIMESTAMP object into Emacs internal time.
23621 Use end of date range or time range when END is non-nil."
23622 (apply #'encode-time
23623 (cons 0
23624 (mapcar
23625 (lambda (prop) (or (org-element-property prop timestamp) 0))
23626 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23627 '(:minute-start :hour-start :day-start :month-start
23628 :year-start))))))
23630 (defun org-timestamp-has-time-p (timestamp)
23631 "Non-nil when TIMESTAMP has a time specified."
23632 (org-element-property :hour-start timestamp))
23634 (defun org-timestamp-format (timestamp format &optional end utc)
23635 "Format a TIMESTAMP object into a string.
23637 FORMAT is a format specifier to be passed to
23638 `format-time-string'.
23640 When optional argument END is non-nil, use end of date-range or
23641 time-range, if possible.
23643 When optional argument UTC is non-nil, time will be expressed as
23644 Universal Time."
23645 (format-time-string
23646 format (org-timestamp--to-internal-time timestamp end)
23647 (and utc t)))
23649 (defun org-timestamp-split-range (timestamp &optional end)
23650 "Extract a TIMESTAMP object from a date or time range.
23652 END, when non-nil, means extract the end of the range.
23653 Otherwise, extract its start.
23655 Return a new timestamp object."
23656 (let ((type (org-element-property :type timestamp)))
23657 (if (memq type '(active inactive diary)) timestamp
23658 (let ((split-ts (org-element-copy timestamp)))
23659 ;; Set new type.
23660 (org-element-put-property
23661 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23662 ;; Copy start properties over end properties if END is
23663 ;; non-nil. Otherwise, copy end properties over `start' ones.
23664 (let ((p-alist '((:minute-start . :minute-end)
23665 (:hour-start . :hour-end)
23666 (:day-start . :day-end)
23667 (:month-start . :month-end)
23668 (:year-start . :year-end))))
23669 (dolist (p-cell p-alist)
23670 (org-element-put-property
23671 split-ts
23672 (funcall (if end #'car #'cdr) p-cell)
23673 (org-element-property
23674 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23675 ;; Eventually refresh `:raw-value'.
23676 (org-element-put-property split-ts :raw-value nil)
23677 (org-element-put-property
23678 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23680 (defun org-timestamp-translate (timestamp &optional boundary)
23681 "Translate TIMESTAMP object to custom format.
23683 Format string is defined in `org-time-stamp-custom-formats',
23684 which see.
23686 When optional argument BOUNDARY is non-nil, it is either the
23687 symbol `start' or `end'. In this case, only translate the
23688 starting or ending part of TIMESTAMP if it is a date or time
23689 range. Otherwise, translate both parts.
23691 Return timestamp as-is if `org-display-custom-times' is nil or if
23692 it has a `diary' type."
23693 (let ((type (org-element-property :type timestamp)))
23694 (if (or (not org-display-custom-times) (eq type 'diary))
23695 (org-element-interpret-data timestamp)
23696 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23697 org-time-stamp-custom-formats)))
23698 (if (and (not boundary) (memq type '(active-range inactive-range)))
23699 (concat (org-timestamp-format timestamp fmt)
23700 "--"
23701 (org-timestamp-format timestamp fmt t))
23702 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23706 ;;; Other stuff.
23708 (defvar reftex-docstruct-symbol)
23709 (defvar org--rds)
23711 (defun org-reftex-citation ()
23712 "Use reftex-citation to insert a citation into the buffer.
23713 This looks for a line like
23715 #+BIBLIOGRAPHY: foo plain option:-d
23717 and derives from it that foo.bib is the bibliography file relevant
23718 for this document. It then installs the necessary environment for RefTeX
23719 to work in this buffer and calls `reftex-citation' to insert a citation
23720 into the buffer.
23722 Export of such citations to both LaTeX and HTML is handled by the contributed
23723 package ox-bibtex by Taru Karttunen."
23724 (interactive)
23725 (let ((reftex-docstruct-symbol 'org--rds)
23726 org--rds bib)
23727 (org-with-wide-buffer
23728 (let ((case-fold-search t)
23729 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23730 (if (not (save-excursion
23731 (or (re-search-forward re nil t)
23732 (re-search-backward re nil t))))
23733 (user-error "No bibliography defined in file")
23734 (setq bib (concat (match-string 1) ".bib")
23735 org--rds (list (list 'bib bib))))))
23736 (call-interactively 'reftex-citation)))
23738 ;;;; Functions extending outline functionality
23740 (defun org-beginning-of-line (&optional n)
23741 "Go to the beginning of the current visible line.
23743 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23744 tags on the first attempt, and only move to after the tags when
23745 the cursor is already beyond the end of the headline.
23747 With argument N not nil or 1, move forward N - 1 lines first."
23748 (interactive "^p")
23749 (let ((origin (point))
23750 (special (pcase org-special-ctrl-a/e
23751 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23752 deactivate-mark)
23753 ;; First move to a visible line.
23754 (if (bound-and-true-p visual-line-mode)
23755 (beginning-of-visual-line n)
23756 (move-beginning-of-line n)
23757 ;; `move-beginning-of-line' may leave point after invisible
23758 ;; characters if line starts with such of these (e.g., with
23759 ;; a link at column 0). Really move to the beginning of the
23760 ;; current visible line.
23761 (beginning-of-line))
23762 (cond
23763 ;; No special behavior. Point is already at the beginning of
23764 ;; a line, logical or visual.
23765 ((not special))
23766 ;; `beginning-of-visual-line' left point before logical beginning
23767 ;; of line: point is at the beginning of a visual line. Bail
23768 ;; out.
23769 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23770 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23771 ;; At a headline, special position is before the title, but
23772 ;; after any TODO keyword or priority cookie.
23773 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23774 (line-end-position)))
23775 (bol (point)))
23776 (if (eq special 'reversed)
23777 (when (and (= origin bol) (eq last-command this-command))
23778 (goto-char refpos))
23779 (when (or (> origin refpos) (= origin bol))
23780 (goto-char refpos)))))
23781 ((and (looking-at org-list-full-item-re)
23782 (memq (org-element-type (save-match-data (org-element-at-point)))
23783 '(item plain-list)))
23784 ;; Set special position at first white space character after
23785 ;; bullet, and check-box, if any.
23786 (let ((after-bullet
23787 (let ((box (match-end 3)))
23788 (cond ((not box) (match-end 1))
23789 ((eq (char-after box) ?\s) (1+ box))
23790 (t box)))))
23791 (if (eq special 'reversed)
23792 (when (and (= (point) origin) (eq last-command this-command))
23793 (goto-char after-bullet))
23794 (when (or (> origin after-bullet) (= (point) origin))
23795 (goto-char after-bullet)))))
23796 ;; No special context. Point is already at beginning of line.
23797 (t nil))))
23799 (defun org-end-of-line (&optional n)
23800 "Go to the end of the line, but before ellipsis, if any.
23802 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23803 tags on the first attempt, and only move to after the tags when
23804 the cursor is already beyond the end of the headline.
23806 With argument N not nil or 1, move forward N - 1 lines first."
23807 (interactive "^p")
23808 (let ((origin (point))
23809 (special (pcase org-special-ctrl-a/e
23810 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23811 deactivate-mark)
23812 ;; First move to a visible line.
23813 (if (bound-and-true-p visual-line-mode)
23814 (beginning-of-visual-line n)
23815 (move-beginning-of-line n))
23816 (cond
23817 ;; At a headline, with tags.
23818 ((and special
23819 (save-excursion
23820 (beginning-of-line)
23821 (let ((case-fold-search nil))
23822 (looking-at org-complex-heading-regexp)))
23823 (match-end 5))
23824 (let ((tags (save-excursion
23825 (goto-char (match-beginning 5))
23826 (skip-chars-backward " \t")
23827 (point)))
23828 (visual-end (and (bound-and-true-p visual-line-mode)
23829 (save-excursion
23830 (end-of-visual-line)
23831 (point)))))
23832 ;; If `end-of-visual-line' brings us before end of line or
23833 ;; even tags, i.e., the headline spans over multiple visual
23834 ;; lines, move there.
23835 (cond ((and visual-end
23836 (< visual-end tags)
23837 (<= origin visual-end))
23838 (goto-char visual-end))
23839 ((eq special 'reversed)
23840 (if (and (= origin (line-end-position))
23841 (eq this-command last-command))
23842 (goto-char tags)
23843 (end-of-line)))
23845 (if (or (< origin tags) (= origin (line-end-position)))
23846 (goto-char tags)
23847 (end-of-line))))))
23848 ((bound-and-true-p visual-line-mode)
23849 (let ((bol (line-beginning-position)))
23850 (end-of-visual-line)
23851 ;; If `end-of-visual-line' gets us past the ellipsis at the
23852 ;; end of a line, backtrack and use `end-of-line' instead.
23853 (when (/= bol (line-beginning-position))
23854 (goto-char bol)
23855 (end-of-line))))
23856 (t (end-of-line)))))
23858 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23859 (define-key org-mode-map "\C-e" 'org-end-of-line)
23861 (defun org-backward-sentence (&optional _arg)
23862 "Go to beginning of sentence, or beginning of table field.
23863 This will call `backward-sentence' or `org-table-beginning-of-field',
23864 depending on context."
23865 (interactive)
23866 (let* ((element (org-element-at-point))
23867 (contents-begin (org-element-property :contents-begin element))
23868 (table (org-element-lineage element '(table) t)))
23869 (if (and table
23870 (> (point) contents-begin)
23871 (<= (point) (org-element-property :contents-end table)))
23872 (call-interactively #'org-table-beginning-of-field)
23873 (save-restriction
23874 (when (and contents-begin
23875 (< (point-min) contents-begin)
23876 (> (point) contents-begin))
23877 (narrow-to-region contents-begin
23878 (org-element-property :contents-end element)))
23879 (call-interactively #'backward-sentence)))))
23881 (defun org-forward-sentence (&optional _arg)
23882 "Go to end of sentence, or end of table field.
23883 This will call `forward-sentence' or `org-table-end-of-field',
23884 depending on context."
23885 (interactive)
23886 (let* ((element (org-element-at-point))
23887 (contents-end (org-element-property :contents-end element))
23888 (table (org-element-lineage element '(table) t)))
23889 (if (and table
23890 (>= (point) (org-element-property :contents-begin table))
23891 (< (point) contents-end))
23892 (call-interactively #'org-table-end-of-field)
23893 (save-restriction
23894 (when (and contents-end
23895 (> (point-max) contents-end)
23896 ;; Skip blank lines between elements.
23897 (< (org-element-property :end element)
23898 (save-excursion (goto-char contents-end)
23899 (skip-chars-forward " \r\t\n"))))
23900 (narrow-to-region (org-element-property :contents-begin element)
23901 contents-end))
23902 (call-interactively #'forward-sentence)))))
23904 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23905 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23907 (defun org-kill-line (&optional _arg)
23908 "Kill line, to tags or end of line."
23909 (interactive)
23910 (cond
23911 ((or (not org-special-ctrl-k)
23912 (bolp)
23913 (not (org-at-heading-p)))
23914 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23915 org-ctrl-k-protect-subtree
23916 (or (eq org-ctrl-k-protect-subtree 'error)
23917 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23918 (user-error "C-k aborted as it would kill a hidden subtree"))
23919 (call-interactively
23920 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23921 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23922 (kill-region (point) (match-beginning 1))
23923 (org-set-tags nil t))
23924 (t (kill-region (point) (point-at-eol)))))
23926 (define-key org-mode-map "\C-k" 'org-kill-line)
23928 (defun org-yank (&optional arg)
23929 "Yank. If the kill is a subtree, treat it specially.
23930 This command will look at the current kill and check if is a single
23931 subtree, or a series of subtrees[1]. If it passes the test, and if the
23932 cursor is at the beginning of a line or after the stars of a currently
23933 empty headline, then the yank is handled specially. How exactly depends
23934 on the value of the following variables.
23936 `org-yank-folded-subtrees'
23937 By default, this variable is non-nil, which results in
23938 subtree(s) being folded after insertion, except if doing so
23939 would swallow text after the yanked text.
23941 `org-yank-adjusted-subtrees'
23942 When non-nil (the default value is nil), the subtree will be
23943 promoted or demoted in order to fit into the local outline tree
23944 structure, which means that the level will be adjusted so that it
23945 becomes the smaller one of the two *visible* surrounding headings.
23947 Any prefix to this command will cause `yank' to be called directly with
23948 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23949 will just
23950 plainly yank the text as it is.
23952 \[1] The test checks if the first non-white line is a heading
23953 and if there are no other headings with fewer stars."
23954 (interactive "P")
23955 (org-yank-generic 'yank arg))
23957 (defun org-yank-generic (command arg)
23958 "Perform some yank-like command.
23960 This function implements the behavior described in the `org-yank'
23961 documentation. However, it has been generalized to work for any
23962 interactive command with similar behavior."
23964 ;; pretend to be command COMMAND
23965 (setq this-command command)
23967 (if arg
23968 (call-interactively command)
23970 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23971 (and (org-kill-is-subtree-p)
23972 (or (bolp)
23973 (and (looking-at "[ \t]*$")
23974 (string-match
23975 "\\`\\*+\\'"
23976 (buffer-substring (point-at-bol) (point)))))))
23977 swallowp)
23978 (cond
23979 ((and subtreep org-yank-folded-subtrees)
23980 (let ((beg (point))
23981 end)
23982 (if (and subtreep org-yank-adjusted-subtrees)
23983 (org-paste-subtree nil nil 'for-yank)
23984 (call-interactively command))
23986 (setq end (point))
23987 (goto-char beg)
23988 (when (and (bolp) subtreep
23989 (not (setq swallowp
23990 (org-yank-folding-would-swallow-text beg end))))
23991 (org-with-limited-levels
23992 (or (looking-at org-outline-regexp)
23993 (re-search-forward org-outline-regexp-bol end t))
23994 (while (and (< (point) end) (looking-at org-outline-regexp))
23995 (outline-hide-subtree)
23996 (org-cycle-show-empty-lines 'folded)
23997 (condition-case nil
23998 (outline-forward-same-level 1)
23999 (error (goto-char end))))))
24000 (when swallowp
24001 (message
24002 "Inserted text not folded because that would swallow text"))
24004 (goto-char end)
24005 (skip-chars-forward " \t\n\r")
24006 (beginning-of-line 1)
24007 (push-mark beg 'nomsg)))
24008 ((and subtreep org-yank-adjusted-subtrees)
24009 (let ((beg (point-at-bol)))
24010 (org-paste-subtree nil nil 'for-yank)
24011 (push-mark beg 'nomsg)))
24013 (call-interactively command))))))
24015 (defun org-yank-folding-would-swallow-text (beg end)
24016 "Would hide-subtree at BEG swallow any text after END?"
24017 (let (level)
24018 (org-with-limited-levels
24019 (save-excursion
24020 (goto-char beg)
24021 (when (or (looking-at org-outline-regexp)
24022 (re-search-forward org-outline-regexp-bol end t))
24023 (setq level (org-outline-level)))
24024 (goto-char end)
24025 (skip-chars-forward " \t\r\n\v\f")
24026 (not (or (eobp)
24027 (and (bolp) (looking-at-p org-outline-regexp)
24028 (<= (org-outline-level) level))))))))
24030 (define-key org-mode-map "\C-y" 'org-yank)
24032 (defun org-truely-invisible-p ()
24033 "Check if point is at a character currently not visible.
24034 This version does not only check the character property, but also
24035 `visible-mode'."
24036 ;; Early versions of noutline don't have `outline-invisible-p'.
24037 (unless (bound-and-true-p visible-mode)
24038 (outline-invisible-p)))
24040 (defun org-invisible-p2 ()
24041 "Check if point is at a character currently not visible."
24042 (save-excursion
24043 (when (and (eolp) (not (bobp))) (backward-char 1))
24044 ;; Early versions of noutline don't have `outline-invisible-p'.
24045 (outline-invisible-p)))
24047 (defun org-back-to-heading (&optional invisible-ok)
24048 "Call `outline-back-to-heading', but provide a better error message."
24049 (condition-case nil
24050 (outline-back-to-heading invisible-ok)
24051 (error (error "Before first headline at position %d in buffer %s"
24052 (point) (current-buffer)))))
24054 (defun org-before-first-heading-p ()
24055 "Before first heading?"
24056 (save-excursion
24057 (end-of-line)
24058 (null (re-search-backward org-outline-regexp-bol nil t))))
24060 (defun org-at-heading-p (&optional ignored)
24061 (outline-on-heading-p t))
24063 (defun org-in-commented-heading-p (&optional no-inheritance)
24064 "Non-nil if point is under a commented heading.
24065 This function also checks ancestors of the current headline,
24066 unless optional argument NO-INHERITANCE is non-nil."
24067 (cond
24068 ((org-before-first-heading-p) nil)
24069 ((let ((headline (nth 4 (org-heading-components))))
24070 (and headline
24071 (let ((case-fold-search nil))
24072 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24073 headline)))))
24074 (no-inheritance nil)
24076 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24078 (defun org-at-comment-p nil
24079 "Is cursor in a commented line?"
24080 (save-excursion
24081 (save-match-data
24082 (beginning-of-line)
24083 (looking-at "^[ \t]*# "))))
24085 (defun org-at-drawer-p nil
24086 "Is cursor at a drawer keyword?"
24087 (save-excursion
24088 (move-beginning-of-line 1)
24089 (looking-at org-drawer-regexp)))
24091 (defun org-at-block-p nil
24092 "Is cursor at a block keyword?"
24093 (save-excursion
24094 (move-beginning-of-line 1)
24095 (looking-at org-block-regexp)))
24097 (defun org-point-at-end-of-empty-headline ()
24098 "If point is at the end of an empty headline, return t, else nil.
24099 If the heading only contains a TODO keyword, it is still still considered
24100 empty."
24101 (let ((case-fold-search nil))
24102 (and (looking-at "[ \t]*$")
24103 org-todo-line-regexp
24104 (save-excursion
24105 (beginning-of-line)
24106 (looking-at org-todo-line-regexp)
24107 (string= (match-string 3) "")))))
24109 (defun org-at-heading-or-item-p ()
24110 (or (org-at-heading-p) (org-at-item-p)))
24112 (defun org-at-target-p ()
24113 (or (org-in-regexp org-radio-target-regexp)
24114 (org-in-regexp org-target-regexp)))
24115 ;; Compatibility alias with Org versions < 7.8.03
24116 (defalias 'org-on-target-p 'org-at-target-p)
24118 (defun org-up-heading-all (arg)
24119 "Move to the heading line of which the present line is a subheading.
24120 This function considers both visible and invisible heading lines.
24121 With argument, move up ARG levels."
24122 (outline-up-heading arg t))
24124 (defun org-up-heading-safe ()
24125 "Move to the heading line of which the present line is a subheading.
24126 This version will not throw an error. It will return the level of the
24127 headline found, or nil if no higher level is found.
24129 Also, this function will be a lot faster than `outline-up-heading',
24130 because it relies on stars being the outline starters. This can really
24131 make a significant difference in outlines with very many siblings."
24132 (when (ignore-errors (org-back-to-heading t))
24133 (let ((level-up (1- (funcall outline-level))))
24134 (and (> level-up 0)
24135 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24136 (funcall outline-level)))))
24138 (defun org-first-sibling-p ()
24139 "Is this heading the first child of its parents?"
24140 (interactive)
24141 (let ((re org-outline-regexp-bol)
24142 level l)
24143 (unless (org-at-heading-p t)
24144 (user-error "Not at a heading"))
24145 (setq level (funcall outline-level))
24146 (save-excursion
24147 (if (not (re-search-backward re nil t))
24149 (setq l (funcall outline-level))
24150 (< l level)))))
24152 (defun org-goto-sibling (&optional previous)
24153 "Goto the next sibling, even if it is invisible.
24154 When PREVIOUS is set, go to the previous sibling instead. Returns t
24155 when a sibling was found. When none is found, return nil and don't
24156 move point."
24157 (let ((fun (if previous 're-search-backward 're-search-forward))
24158 (pos (point))
24159 (re org-outline-regexp-bol)
24160 level l)
24161 (when (ignore-errors (org-back-to-heading t))
24162 (setq level (funcall outline-level))
24163 (catch 'exit
24164 (or previous (forward-char 1))
24165 (while (funcall fun re nil t)
24166 (setq l (funcall outline-level))
24167 (when (< l level) (goto-char pos) (throw 'exit nil))
24168 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24169 (goto-char pos)
24170 nil))))
24172 (defun org-show-siblings ()
24173 "Show all siblings of the current headline."
24174 (save-excursion
24175 (while (org-goto-sibling) (org-flag-heading nil)))
24176 (save-excursion
24177 (while (org-goto-sibling 'previous)
24178 (org-flag-heading nil))))
24180 (defun org-goto-first-child ()
24181 "Goto the first child, even if it is invisible.
24182 Return t when a child was found. Otherwise don't move point and
24183 return nil."
24184 (let (level (pos (point)) (re org-outline-regexp-bol))
24185 (when (ignore-errors (org-back-to-heading t))
24186 (setq level (outline-level))
24187 (forward-char 1)
24188 (if (and (re-search-forward re nil t) (> (outline-level) level))
24189 (progn (goto-char (match-beginning 0)) t)
24190 (goto-char pos) nil))))
24192 (defun org-show-hidden-entry ()
24193 "Show an entry where even the heading is hidden."
24194 (save-excursion
24195 (org-show-entry)))
24197 (defun org-flag-heading (flag &optional entry)
24198 "Flag the current heading. FLAG non-nil means make invisible.
24199 When ENTRY is non-nil, show the entire entry."
24200 (save-excursion
24201 (org-back-to-heading t)
24202 ;; Check if we should show the entire entry
24203 (if entry
24204 (progn
24205 (org-show-entry)
24206 (save-excursion
24207 (and (outline-next-heading)
24208 (org-flag-heading nil))))
24209 (outline-flag-region (max (point-min) (1- (point)))
24210 (save-excursion (outline-end-of-heading) (point))
24211 flag))))
24213 (defun org-get-next-sibling ()
24214 "Move to next heading of the same level, and return point.
24215 If there is no such heading, return nil.
24216 This is like outline-next-sibling, but invisible headings are ok."
24217 (let ((level (funcall outline-level)))
24218 (outline-next-heading)
24219 (while (and (not (eobp)) (> (funcall outline-level) level))
24220 (outline-next-heading))
24221 (unless (or (eobp) (< (funcall outline-level) level))
24222 (point))))
24224 (defun org-get-last-sibling ()
24225 "Move to previous heading of the same level, and return point.
24226 If there is no such heading, return nil."
24227 (let ((opoint (point))
24228 (level (funcall outline-level)))
24229 (outline-previous-heading)
24230 (when (and (/= (point) opoint) (outline-on-heading-p t))
24231 (while (and (> (funcall outline-level) level)
24232 (not (bobp)))
24233 (outline-previous-heading))
24234 (unless (< (funcall outline-level) level)
24235 (point)))))
24237 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24238 "Goto to the end of a subtree."
24239 ;; This contains an exact copy of the original function, but it uses
24240 ;; `org-back-to-heading', to make it work also in invisible
24241 ;; trees. And is uses an invisible-ok argument.
24242 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24243 ;; Furthermore, when used inside Org, finding the end of a large subtree
24244 ;; with many children and grandchildren etc, this can be much faster
24245 ;; than the outline version.
24246 (org-back-to-heading invisible-ok)
24247 (let ((first t)
24248 (level (funcall outline-level)))
24249 (if (and (derived-mode-p 'org-mode) (< level 1000))
24250 ;; A true heading (not a plain list item), in Org
24251 ;; This means we can easily find the end by looking
24252 ;; only for the right number of stars. Using a regexp to do
24253 ;; this is so much faster than using a Lisp loop.
24254 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24255 (forward-char 1)
24256 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24257 ;; something else, do it the slow way
24258 (while (and (not (eobp))
24259 (or first (> (funcall outline-level) level)))
24260 (setq first nil)
24261 (outline-next-heading)))
24262 (unless to-heading
24263 (when (memq (preceding-char) '(?\n ?\^M))
24264 ;; Go to end of line before heading
24265 (forward-char -1)
24266 (when (memq (preceding-char) '(?\n ?\^M))
24267 ;; leave blank line before heading
24268 (forward-char -1)))))
24269 (point))
24271 (defun org-end-of-meta-data (&optional full)
24272 "Skip planning line and properties drawer in current entry.
24273 When optional argument FULL is non-nil, also skip empty lines,
24274 clocking lines and regular drawers at the beginning of the
24275 entry."
24276 (org-back-to-heading t)
24277 (forward-line)
24278 (when (looking-at-p org-planning-line-re) (forward-line))
24279 (when (looking-at org-property-drawer-re)
24280 (goto-char (match-end 0))
24281 (forward-line))
24282 (when (and full (not (org-at-heading-p)))
24283 (catch 'exit
24284 (let ((end (save-excursion (outline-next-heading) (point)))
24285 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24286 (while (not (eobp))
24287 (cond ((looking-at-p org-drawer-regexp)
24288 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24289 (forward-line)
24290 (throw 'exit t)))
24291 ((looking-at-p re) (forward-line))
24292 (t (throw 'exit t))))))))
24294 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24295 "Move forward to the ARG'th subheading at same level as this one.
24296 Stop at the first and last subheadings of a superior heading.
24297 Normally this only looks at visible headings, but when INVISIBLE-OK is
24298 non-nil it will also look at invisible ones."
24299 (interactive "p")
24300 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24301 (if (and arg (< arg 0))
24302 (goto-char (point-min))
24303 (outline-next-heading))
24304 (org-at-heading-p)
24305 (let ((level (- (match-end 0) (match-beginning 0) 1))
24306 (f (if (and arg (< arg 0))
24307 're-search-backward
24308 're-search-forward))
24309 (count (if arg (abs arg) 1))
24310 (result (point)))
24311 (while (and (prog1 (> count 0)
24312 (forward-char (if (and arg (< arg 0)) -1 1)))
24313 (funcall f org-outline-regexp-bol nil 'move))
24314 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24315 (cond ((< l level) (setq count 0))
24316 ((and (= l level)
24317 (or invisible-ok
24318 (progn
24319 (goto-char (line-beginning-position))
24320 (not (outline-invisible-p)))))
24321 (setq count (1- count))
24322 (when (eq l level)
24323 (setq result (point)))))))
24324 (goto-char result))
24325 (beginning-of-line 1)))
24327 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24328 "Move backward to the ARG'th subheading at same level as this one.
24329 Stop at the first and last subheadings of a superior heading."
24330 (interactive "p")
24331 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24333 (defun org-next-visible-heading (arg)
24334 "Move to the next visible heading.
24336 This function wraps `outline-next-visible-heading' with
24337 `org-with-limited-levels' in order to skip over inline tasks and
24338 respect customization of `org-odd-levels-only'."
24339 (interactive "p")
24340 (org-with-limited-levels
24341 (outline-next-visible-heading arg)))
24343 (defun org-previous-visible-heading (arg)
24344 "Move to the previous visible heading.
24346 This function wraps `outline-previous-visible-heading' with
24347 `org-with-limited-levels' in order to skip over inline tasks and
24348 respect customization of `org-odd-levels-only'."
24349 (interactive "p")
24350 (org-with-limited-levels
24351 (outline-previous-visible-heading arg)))
24353 (defun org-next-block (arg &optional backward block-regexp)
24354 "Jump to the next block.
24356 With a prefix argument ARG, jump forward ARG many blocks.
24358 When BACKWARD is non-nil, jump to the previous block.
24360 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24361 Match data is set according to this regexp when the function
24362 returns.
24364 Return point at beginning of the opening line of found block.
24365 Throw an error if no block is found."
24366 (interactive "p")
24367 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24368 (case-fold-search t)
24369 (search-fn (if backward #'re-search-backward #'re-search-forward))
24370 (count (or arg 1))
24371 (origin (point))
24372 last-element)
24373 (if backward (beginning-of-line) (end-of-line))
24374 (while (and (> count 0) (funcall search-fn re nil t))
24375 (let ((element (save-excursion
24376 (goto-char (match-beginning 0))
24377 (save-match-data (org-element-at-point)))))
24378 (when (and (memq (org-element-type element)
24379 '(center-block comment-block dynamic-block
24380 example-block export-block quote-block
24381 special-block src-block verse-block))
24382 (<= (match-beginning 0)
24383 (org-element-property :post-affiliated element)))
24384 (setq last-element element)
24385 (cl-decf count))))
24386 (if (= count 0)
24387 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24388 (save-match-data (org-show-context)))
24389 (goto-char origin)
24390 (user-error "No %s code blocks" (if backward "previous" "further")))))
24392 (defun org-previous-block (arg &optional block-regexp)
24393 "Jump to the previous block.
24394 With a prefix argument ARG, jump backward ARG many source blocks.
24395 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24396 (interactive "p")
24397 (org-next-block arg t block-regexp))
24399 (defun org-forward-paragraph ()
24400 "Move forward to beginning of next paragraph or equivalent.
24402 The function moves point to the beginning of the next visible
24403 structural element, which can be a paragraph, a table, a list
24404 item, etc. It also provides some special moves for convenience:
24406 - On an affiliated keyword, jump to the beginning of the
24407 relative element.
24408 - On an item or a footnote definition, move to the second
24409 element inside, if any.
24410 - On a table or a property drawer, jump after it.
24411 - On a verse or source block, stop after blank lines."
24412 (interactive)
24413 (when (eobp) (user-error "Cannot move further down"))
24414 (let* ((deactivate-mark nil)
24415 (element (org-element-at-point))
24416 (type (org-element-type element))
24417 (post-affiliated (org-element-property :post-affiliated element))
24418 (contents-begin (org-element-property :contents-begin element))
24419 (contents-end (org-element-property :contents-end element))
24420 (end (let ((end (org-element-property :end element)) (parent element))
24421 (while (and (setq parent (org-element-property :parent parent))
24422 (= (org-element-property :contents-end parent) end))
24423 (setq end (org-element-property :end parent)))
24424 end)))
24425 (cond ((not element)
24426 (skip-chars-forward " \r\t\n")
24427 (or (eobp) (beginning-of-line)))
24428 ;; On affiliated keywords, move to element's beginning.
24429 ((< (point) post-affiliated)
24430 (goto-char post-affiliated))
24431 ;; At a table row, move to the end of the table. Similarly,
24432 ;; at a node property, move to the end of the property
24433 ;; drawer.
24434 ((memq type '(node-property table-row))
24435 (goto-char (org-element-property
24436 :end (org-element-property :parent element))))
24437 ((memq type '(property-drawer table)) (goto-char end))
24438 ;; Consider blank lines as separators in verse and source
24439 ;; blocks to ease editing.
24440 ((memq type '(src-block verse-block))
24441 (when (eq type 'src-block)
24442 (setq contents-end
24443 (save-excursion (goto-char end)
24444 (skip-chars-backward " \r\t\n")
24445 (line-beginning-position))))
24446 (beginning-of-line)
24447 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24448 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24449 (goto-char end)
24450 (skip-chars-forward " \r\t\n")
24451 (if (= (point) contents-end) (goto-char end)
24452 (beginning-of-line))))
24453 ;; With no contents, just skip element.
24454 ((not contents-begin) (goto-char end))
24455 ;; If contents are invisible, skip the element altogether.
24456 ((outline-invisible-p (line-end-position))
24457 (cl-case type
24458 (headline
24459 (org-with-limited-levels (outline-next-visible-heading 1)))
24460 ;; At a plain list, make sure we move to the next item
24461 ;; instead of skipping the whole list.
24462 (plain-list (forward-char)
24463 (org-forward-paragraph))
24464 (otherwise (goto-char end))))
24465 ((>= (point) contents-end) (goto-char end))
24466 ((>= (point) contents-begin)
24467 ;; This can only happen on paragraphs and plain lists.
24468 (cl-case type
24469 (paragraph (goto-char end))
24470 ;; At a plain list, try to move to second element in
24471 ;; first item, if possible.
24472 (plain-list (end-of-line)
24473 (org-forward-paragraph))))
24474 ;; When contents start on the middle of a line (e.g. in
24475 ;; items and footnote definitions), try to reach first
24476 ;; element starting after current line.
24477 ((> (line-end-position) contents-begin)
24478 (end-of-line)
24479 (org-forward-paragraph))
24480 (t (goto-char contents-begin)))))
24482 (defun org-backward-paragraph ()
24483 "Move backward to start of previous paragraph or equivalent.
24485 The function moves point to the beginning of the current
24486 structural element, which can be a paragraph, a table, a list
24487 item, etc., or to the beginning of the previous visible one if
24488 point is already there. It also provides some special moves for
24489 convenience:
24491 - On an affiliated keyword, jump to the first one.
24492 - On a table or a property drawer, move to its beginning.
24493 - On a verse or source block, stop before blank lines."
24494 (interactive)
24495 (when (bobp) (user-error "Cannot move further up"))
24496 (let* ((deactivate-mark nil)
24497 (element (org-element-at-point))
24498 (type (org-element-type element))
24499 (contents-begin (org-element-property :contents-begin element))
24500 (contents-end (org-element-property :contents-end element))
24501 (post-affiliated (org-element-property :post-affiliated element))
24502 (begin (org-element-property :begin element)))
24503 (cond
24504 ((not element) (goto-char (point-min)))
24505 ((= (point) begin)
24506 (backward-char)
24507 (org-backward-paragraph))
24508 ((<= (point) post-affiliated) (goto-char begin))
24509 ((memq type '(node-property table-row))
24510 (goto-char (org-element-property
24511 :post-affiliated (org-element-property :parent element))))
24512 ((memq type '(property-drawer table)) (goto-char begin))
24513 ((memq type '(src-block verse-block))
24514 (when (eq type 'src-block)
24515 (setq contents-begin
24516 (save-excursion (goto-char begin) (forward-line) (point))))
24517 (if (= (point) contents-begin) (goto-char post-affiliated)
24518 ;; Inside a verse block, see blank lines as paragraph
24519 ;; separators.
24520 (let ((origin (point)))
24521 (skip-chars-backward " \r\t\n" contents-begin)
24522 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24523 (skip-chars-forward " \r\t\n" origin)
24524 (if (= (point) origin) (goto-char contents-begin)
24525 (beginning-of-line))))))
24526 ((not contents-begin) (goto-char (or post-affiliated begin)))
24527 ((eq type 'paragraph)
24528 (goto-char contents-begin)
24529 ;; When at first paragraph in an item or a footnote definition,
24530 ;; move directly to beginning of line.
24531 (let ((parent-contents
24532 (org-element-property
24533 :contents-begin (org-element-property :parent element))))
24534 (when (and parent-contents (= parent-contents contents-begin))
24535 (beginning-of-line))))
24536 ;; At the end of a greater element, move to the beginning of the
24537 ;; last element within.
24538 ((>= (point) contents-end)
24539 (goto-char (1- contents-end))
24540 (org-backward-paragraph))
24541 (t (goto-char (or post-affiliated begin))))
24542 ;; Ensure we never leave point invisible.
24543 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24545 (defun org-forward-element ()
24546 "Move forward by one element.
24547 Move to the next element at the same level, when possible."
24548 (interactive)
24549 (cond ((eobp) (user-error "Cannot move further down"))
24550 ((org-with-limited-levels (org-at-heading-p))
24551 (let ((origin (point)))
24552 (goto-char (org-end-of-subtree nil t))
24553 (unless (org-with-limited-levels (org-at-heading-p))
24554 (goto-char origin)
24555 (user-error "Cannot move further down"))))
24557 (let* ((elem (org-element-at-point))
24558 (end (org-element-property :end elem))
24559 (parent (org-element-property :parent elem)))
24560 (cond ((and parent (= (org-element-property :contents-end parent) end))
24561 (goto-char (org-element-property :end parent)))
24562 ((integer-or-marker-p end) (goto-char end))
24563 (t (message "No element at point")))))))
24565 (defun org-backward-element ()
24566 "Move backward by one element.
24567 Move to the previous element at the same level, when possible."
24568 (interactive)
24569 (cond ((bobp) (user-error "Cannot move further up"))
24570 ((org-with-limited-levels (org-at-heading-p))
24571 ;; At a headline, move to the previous one, if any, or stay
24572 ;; here.
24573 (let ((origin (point)))
24574 (org-with-limited-levels (org-backward-heading-same-level 1))
24575 ;; When current headline has no sibling above, move to its
24576 ;; parent.
24577 (when (= (point) origin)
24578 (or (org-with-limited-levels (org-up-heading-safe))
24579 (progn (goto-char origin)
24580 (user-error "Cannot move further up"))))))
24582 (let* ((elem (org-element-at-point))
24583 (beg (org-element-property :begin elem)))
24584 (cond
24585 ;; Move to beginning of current element if point isn't
24586 ;; there already.
24587 ((null beg) (message "No element at point"))
24588 ((/= (point) beg) (goto-char beg))
24589 (t (goto-char beg)
24590 (skip-chars-backward " \r\t\n")
24591 (unless (bobp)
24592 (let ((prev (org-element-at-point)))
24593 (goto-char (org-element-property :begin prev))
24594 (while (and (setq prev (org-element-property :parent prev))
24595 (<= (org-element-property :end prev) beg))
24596 (goto-char (org-element-property :begin prev)))))))))))
24598 (defun org-up-element ()
24599 "Move to upper element."
24600 (interactive)
24601 (if (org-with-limited-levels (org-at-heading-p))
24602 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24603 (let* ((elem (org-element-at-point))
24604 (parent (org-element-property :parent elem)))
24605 (if parent (goto-char (org-element-property :begin parent))
24606 (if (org-with-limited-levels (org-before-first-heading-p))
24607 (user-error "No surrounding element")
24608 (org-with-limited-levels (org-back-to-heading)))))))
24610 (defvar org-element-greater-elements)
24611 (defun org-down-element ()
24612 "Move to inner element."
24613 (interactive)
24614 (let ((element (org-element-at-point)))
24615 (cond
24616 ((memq (org-element-type element) '(plain-list table))
24617 (goto-char (org-element-property :contents-begin element))
24618 (forward-char))
24619 ((memq (org-element-type element) org-element-greater-elements)
24620 ;; If contents are hidden, first disclose them.
24621 (when (outline-invisible-p (line-end-position)) (org-cycle))
24622 (goto-char (or (org-element-property :contents-begin element)
24623 (user-error "No content for this element"))))
24624 (t (user-error "No inner element")))))
24626 (defun org-drag-element-backward ()
24627 "Move backward element at point."
24628 (interactive)
24629 (let ((elem (or (org-element-at-point)
24630 (user-error "No element at point"))))
24631 (if (eq (org-element-type elem) 'headline)
24632 ;; Preserve point when moving a whole tree, even if point was
24633 ;; on blank lines below the headline.
24634 (let ((offset (skip-chars-backward " \t\n")))
24635 (unwind-protect (org-move-subtree-up)
24636 (forward-char (- offset))))
24637 (let ((prev-elem
24638 (save-excursion
24639 (goto-char (org-element-property :begin elem))
24640 (skip-chars-backward " \r\t\n")
24641 (unless (bobp)
24642 (let* ((beg (org-element-property :begin elem))
24643 (prev (org-element-at-point))
24644 (up prev))
24645 (while (and (setq up (org-element-property :parent up))
24646 (<= (org-element-property :end up) beg))
24647 (setq prev up))
24648 prev)))))
24649 ;; Error out if no previous element or previous element is
24650 ;; a parent of the current one.
24651 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24652 (user-error "Cannot drag element backward")
24653 (let ((pos (point)))
24654 (org-element-swap-A-B prev-elem elem)
24655 (goto-char (+ (org-element-property :begin prev-elem)
24656 (- pos (org-element-property :begin elem))))))))))
24658 (defun org-drag-element-forward ()
24659 "Move forward element at point."
24660 (interactive)
24661 (let* ((pos (point))
24662 (elem (or (org-element-at-point)
24663 (user-error "No element at point"))))
24664 (when (= (point-max) (org-element-property :end elem))
24665 (user-error "Cannot drag element forward"))
24666 (goto-char (org-element-property :end elem))
24667 (let ((next-elem (org-element-at-point)))
24668 (when (or (org-element-nested-p elem next-elem)
24669 (and (eq (org-element-type next-elem) 'headline)
24670 (not (eq (org-element-type elem) 'headline))))
24671 (goto-char pos)
24672 (user-error "Cannot drag element forward"))
24673 ;; Compute new position of point: it's shifted by NEXT-ELEM
24674 ;; body's length (without final blanks) and by the length of
24675 ;; blanks between ELEM and NEXT-ELEM.
24676 (let ((size-next (- (save-excursion
24677 (goto-char (org-element-property :end next-elem))
24678 (skip-chars-backward " \r\t\n")
24679 (forward-line)
24680 ;; Small correction if buffer doesn't end
24681 ;; with a newline character.
24682 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24683 (org-element-property :begin next-elem)))
24684 (size-blank (- (org-element-property :end elem)
24685 (save-excursion
24686 (goto-char (org-element-property :end elem))
24687 (skip-chars-backward " \r\t\n")
24688 (forward-line)
24689 (point)))))
24690 (org-element-swap-A-B elem next-elem)
24691 (goto-char (+ pos size-next size-blank))))))
24693 (defun org-drag-line-forward (arg)
24694 "Drag the line at point ARG lines forward."
24695 (interactive "p")
24696 (dotimes (_ (abs arg))
24697 (let ((c (current-column)))
24698 (if (< 0 arg)
24699 (progn
24700 (beginning-of-line 2)
24701 (transpose-lines 1)
24702 (beginning-of-line 0))
24703 (transpose-lines 1)
24704 (beginning-of-line -1))
24705 (org-move-to-column c))))
24707 (defun org-drag-line-backward (arg)
24708 "Drag the line at point ARG lines backward."
24709 (interactive "p")
24710 (org-drag-line-forward (- arg)))
24712 (defun org-mark-element ()
24713 "Put point at beginning of this element, mark at end.
24715 Interactively, if this command is repeated or (in Transient Mark
24716 mode) if the mark is active, it marks the next element after the
24717 ones already marked."
24718 (interactive)
24719 (let (deactivate-mark)
24720 (if (and (called-interactively-p 'any)
24721 (or (and (eq last-command this-command) (mark t))
24722 (and transient-mark-mode mark-active)))
24723 (set-mark
24724 (save-excursion
24725 (goto-char (mark))
24726 (goto-char (org-element-property :end (org-element-at-point)))))
24727 (let ((element (org-element-at-point)))
24728 (end-of-line)
24729 (push-mark (org-element-property :end element) t t)
24730 (goto-char (org-element-property :begin element))))))
24732 (defun org-narrow-to-element ()
24733 "Narrow buffer to current element."
24734 (interactive)
24735 (let ((elem (org-element-at-point)))
24736 (cond
24737 ((eq (car elem) 'headline)
24738 (narrow-to-region
24739 (org-element-property :begin elem)
24740 (org-element-property :end elem)))
24741 ((memq (car elem) org-element-greater-elements)
24742 (narrow-to-region
24743 (org-element-property :contents-begin elem)
24744 (org-element-property :contents-end elem)))
24746 (narrow-to-region
24747 (org-element-property :begin elem)
24748 (org-element-property :end elem))))))
24750 (defun org-transpose-element ()
24751 "Transpose current and previous elements, keeping blank lines between.
24752 Point is moved after both elements."
24753 (interactive)
24754 (org-skip-whitespace)
24755 (let ((end (org-element-property :end (org-element-at-point))))
24756 (org-drag-element-backward)
24757 (goto-char end)))
24759 (defun org-unindent-buffer ()
24760 "Un-indent the visible part of the buffer.
24761 Relative indentation (between items, inside blocks, etc.) isn't
24762 modified."
24763 (interactive)
24764 (unless (eq major-mode 'org-mode)
24765 (user-error "Cannot un-indent a buffer not in Org mode"))
24766 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24767 (unindent-tree
24768 (lambda (contents)
24769 (dolist (element (reverse contents))
24770 (if (memq (org-element-type element) '(headline section))
24771 (funcall unindent-tree (org-element-contents element))
24772 (save-excursion
24773 (save-restriction
24774 (narrow-to-region
24775 (org-element-property :begin element)
24776 (org-element-property :end element))
24777 (org-do-remove-indentation))))))))
24778 (funcall unindent-tree (org-element-contents parse-tree))))
24780 (defun org-show-children (&optional level)
24781 "Show all direct subheadings of this heading.
24782 Prefix arg LEVEL is how many levels below the current level
24783 should be shown. Default is enough to cause the following
24784 heading to appear."
24785 (interactive "p")
24786 ;; If `orgstruct-mode' is active, use the slower version.
24787 (if orgstruct-mode (call-interactively #'outline-show-children)
24788 (save-excursion
24789 (org-back-to-heading t)
24790 (let* ((current-level (funcall outline-level))
24791 (max-level (org-get-valid-level
24792 current-level
24793 (if level (prefix-numeric-value level) 1)))
24794 (end (save-excursion (org-end-of-subtree t t)))
24795 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24796 (past-first-child nil)
24797 ;; Make sure to skip inlinetasks.
24798 (re (format regexp-fmt
24799 current-level
24800 (cond
24801 ((not (featurep 'org-inlinetask)) "")
24802 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24804 (t (1- org-inlinetask-min-level))))))
24805 ;; Display parent heading.
24806 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24807 (forward-line)
24808 ;; Display children. First child may be deeper than expected
24809 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24810 ;; MAX-LEVEL accordingly.
24811 (while (re-search-forward re end t)
24812 (unless past-first-child
24813 (setq re (format regexp-fmt
24814 current-level
24815 (max (funcall outline-level) max-level)))
24816 (setq past-first-child t))
24817 (outline-flag-region
24818 (line-end-position 0) (line-end-position) nil))))))
24820 (defun org-show-subtree ()
24821 "Show everything after this heading at deeper levels."
24822 (interactive)
24823 (outline-flag-region
24824 (point)
24825 (save-excursion
24826 (org-end-of-subtree t t))
24827 nil))
24829 (defun org-show-entry ()
24830 "Show the body directly following this heading.
24831 Show the heading too, if it is currently invisible."
24832 (interactive)
24833 (save-excursion
24834 (ignore-errors
24835 (org-back-to-heading t)
24836 (outline-flag-region
24837 (max (point-min) (1- (point)))
24838 (save-excursion
24839 (if (re-search-forward
24840 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24841 (match-beginning 1)
24842 (point-max)))
24843 nil)
24844 (org-cycle-hide-drawers 'children))))
24846 (defun org-make-options-regexp (kwds &optional extra)
24847 "Make a regular expression for keyword lines.
24848 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24849 when non-nil, is a regexp matching keywords names."
24850 (concat "^[ \t]*#\\+\\("
24851 (regexp-opt kwds)
24852 (and extra (concat (and kwds "\\|") extra))
24853 "\\):[ \t]*\\(.*\\)"))
24855 ;;;; Integration with and fixes for other packages
24857 ;;; Imenu support
24859 (defvar-local org-imenu-markers nil
24860 "All markers currently used by Imenu.")
24862 (defun org-imenu-new-marker (&optional pos)
24863 "Return a new marker for use by Imenu, and remember the marker."
24864 (let ((m (make-marker)))
24865 (move-marker m (or pos (point)))
24866 (push m org-imenu-markers)
24869 (defun org-imenu-get-tree ()
24870 "Produce the index for Imenu."
24871 (dolist (x org-imenu-markers) (move-marker x nil))
24872 (setq org-imenu-markers nil)
24873 (let* ((case-fold-search nil)
24874 (n org-imenu-depth)
24875 (re (concat "^" (org-get-limited-outline-regexp)))
24876 (subs (make-vector (1+ n) nil))
24877 (last-level 0)
24878 m level head0 head)
24879 (org-with-wide-buffer
24880 (goto-char (point-max))
24881 (while (re-search-backward re nil t)
24882 (setq level (org-reduced-level (funcall outline-level)))
24883 (when (and (<= level n)
24884 (looking-at org-complex-heading-regexp)
24885 (setq head0 (match-string-no-properties 4)))
24886 (setq head (org-link-display-format head0)
24887 m (org-imenu-new-marker))
24888 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24889 (if (>= level last-level)
24890 (push (cons head m) (aref subs level))
24891 (push (cons head (aref subs (1+ level))) (aref subs level))
24892 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24893 (setq last-level level))))
24894 (aref subs 1)))
24896 (eval-after-load "imenu"
24897 '(progn
24898 (add-hook 'imenu-after-jump-hook
24899 (lambda ()
24900 (when (derived-mode-p 'org-mode)
24901 (org-show-context 'org-goto))))))
24903 (defun org-link-display-format (s)
24904 "Replace links in string S with their description.
24905 If there is no description, use the link target."
24906 (save-match-data
24907 (replace-regexp-in-string
24908 org-bracket-link-analytic-regexp
24909 (lambda (m)
24910 (if (match-end 5) (match-string 5 m)
24911 (concat (match-string 1 m) (match-string 3 m))))
24912 s nil t)))
24914 (defun org-toggle-link-display ()
24915 "Toggle the literal or descriptive display of links."
24916 (interactive)
24917 (if org-descriptive-links
24918 (progn (org-remove-from-invisibility-spec '(org-link))
24919 (org-restart-font-lock)
24920 (setq org-descriptive-links nil))
24921 (progn (add-to-invisibility-spec '(org-link))
24922 (org-restart-font-lock)
24923 (setq org-descriptive-links t))))
24925 ;; Speedbar support
24927 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24928 "Overlay marking the agenda restriction line in speedbar.")
24929 (overlay-put org-speedbar-restriction-lock-overlay
24930 'face 'org-agenda-restriction-lock)
24931 (overlay-put org-speedbar-restriction-lock-overlay
24932 'help-echo "Agendas are currently limited to this item.")
24933 (delete-overlay org-speedbar-restriction-lock-overlay)
24935 (defun org-speedbar-set-agenda-restriction ()
24936 "Restrict future agenda commands to the location at point in speedbar.
24937 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24938 (interactive)
24939 (require 'org-agenda)
24940 (let (p m tp np dir txt)
24941 (cond
24942 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24943 'org-imenu t))
24944 (setq m (get-text-property p 'org-imenu-marker))
24945 (with-current-buffer (marker-buffer m)
24946 (goto-char m)
24947 (org-agenda-set-restriction-lock 'subtree)))
24948 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24949 'speedbar-function 'speedbar-find-file))
24950 (setq tp (previous-single-property-change
24951 (1+ p) 'speedbar-function)
24952 np (next-single-property-change
24953 tp 'speedbar-function)
24954 dir (speedbar-line-directory)
24955 txt (buffer-substring-no-properties (or tp (point-min))
24956 (or np (point-max))))
24957 (with-current-buffer (find-file-noselect
24958 (let ((default-directory dir))
24959 (expand-file-name txt)))
24960 (unless (derived-mode-p 'org-mode)
24961 (user-error "Cannot restrict to non-Org mode file"))
24962 (org-agenda-set-restriction-lock 'file)))
24963 (t (user-error "Don't know how to restrict Org mode agenda")))
24964 (move-overlay org-speedbar-restriction-lock-overlay
24965 (point-at-bol) (point-at-eol))
24966 (setq current-prefix-arg nil)
24967 (org-agenda-maybe-redo)))
24969 (defvar speedbar-file-key-map)
24970 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24971 (eval-after-load "speedbar"
24972 '(progn
24973 (speedbar-add-supported-extension ".org")
24974 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24975 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24976 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24977 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24978 (add-hook 'speedbar-visiting-tag-hook
24979 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24981 ;;; Fixes and Hacks for problems with other packages
24983 (defun org--flyspell-object-check-p (element)
24984 "Non-nil when Flyspell can check object at point.
24985 ELEMENT is the element at point."
24986 (let ((object (save-excursion
24987 (when (looking-at-p "\\>") (backward-char))
24988 (org-element-context element))))
24989 (cl-case (org-element-type object)
24990 ;; Prevent checks in links due to keybinding conflict with
24991 ;; Flyspell.
24992 ((code entity export-snippet inline-babel-call
24993 inline-src-block line-break latex-fragment link macro
24994 statistics-cookie target timestamp verbatim)
24995 nil)
24996 (footnote-reference
24997 ;; Only in inline footnotes, within the definition.
24998 (and (eq (org-element-property :type object) 'inline)
24999 (< (save-excursion
25000 (goto-char (org-element-property :begin object))
25001 (search-forward ":" nil t 2))
25002 (point))))
25003 (otherwise t))))
25005 (defun org-mode-flyspell-verify ()
25006 "Function used for `flyspell-generic-check-word-predicate'."
25007 (if (org-at-heading-p)
25008 ;; At a headline or an inlinetask, check title only. This is
25009 ;; faster than relying on `org-element-at-point'.
25010 (and (save-excursion (beginning-of-line)
25011 (and (let ((case-fold-search t))
25012 (not (looking-at-p "\\*+ END[ \t]*$")))
25013 (let ((case-fold-search nil))
25014 (looking-at org-complex-heading-regexp))))
25015 (match-beginning 4)
25016 (>= (point) (match-beginning 4))
25017 (or (not (match-beginning 5))
25018 (< (point) (match-beginning 5))))
25019 (let* ((element (org-element-at-point))
25020 (post-affiliated (org-element-property :post-affiliated element)))
25021 (cond
25022 ;; Ignore checks in all affiliated keywords but captions.
25023 ((< (point) post-affiliated)
25024 (and (save-excursion
25025 (beginning-of-line)
25026 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25027 (> (point) (match-end 0))
25028 (org--flyspell-object-check-p element)))
25029 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25030 ((let ((log (org-log-into-drawer)))
25031 (and log
25032 (let ((drawer (org-element-lineage element '(drawer))))
25033 (and drawer
25034 (eq (compare-strings
25035 log nil nil
25036 (org-element-property :drawer-name drawer) nil nil t)
25037 t)))))
25038 nil)
25040 (cl-case (org-element-type element)
25041 ((comment quote-section) t)
25042 (comment-block
25043 ;; Allow checks between block markers, not on them.
25044 (and (> (line-beginning-position) post-affiliated)
25045 (save-excursion
25046 (end-of-line)
25047 (skip-chars-forward " \r\t\n")
25048 (< (point) (org-element-property :end element)))))
25049 ;; Arbitrary list of keywords where checks are meaningful.
25050 ;; Make sure point is on the value part of the element.
25051 (keyword
25052 (and (member (org-element-property :key element)
25053 '("DESCRIPTION" "TITLE"))
25054 (save-excursion
25055 (search-backward ":" (line-beginning-position) t))))
25056 ;; Check is globally allowed in paragraphs verse blocks and
25057 ;; table rows (after affiliated keywords) but some objects
25058 ;; must not be affected.
25059 ((paragraph table-row verse-block)
25060 (let ((cbeg (org-element-property :contents-begin element))
25061 (cend (org-element-property :contents-end element)))
25062 (and cbeg (>= (point) cbeg) (< (point) cend)
25063 (org--flyspell-object-check-p element))))))))))
25064 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25066 (defun org-remove-flyspell-overlays-in (beg end)
25067 "Remove flyspell overlays in region."
25068 (and (bound-and-true-p flyspell-mode)
25069 (fboundp 'flyspell-delete-region-overlays)
25070 (flyspell-delete-region-overlays beg end)))
25072 (defvar flyspell-delayed-commands)
25073 (eval-after-load "flyspell"
25074 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25076 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25077 (eval-after-load "bookmark"
25078 '(if (boundp 'bookmark-after-jump-hook)
25079 ;; We can use the hook
25080 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25081 ;; Hook not available, use advice
25082 (defadvice bookmark-jump (after org-make-visible activate)
25083 "Make the position visible."
25084 (org-bookmark-jump-unhide))))
25086 ;; Make sure saveplace shows the location if it was hidden
25087 (eval-after-load "saveplace"
25088 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25089 "Make the position visible."
25090 (org-bookmark-jump-unhide)))
25092 ;; Make sure ecb shows the location if it was hidden
25093 (eval-after-load "ecb"
25094 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25095 "Make hierarchy visible when jumping into location from ECB tree buffer."
25096 (when (derived-mode-p 'org-mode)
25097 (org-show-context))))
25099 (defun org-bookmark-jump-unhide ()
25100 "Unhide the current position, to show the bookmark location."
25101 (and (derived-mode-p 'org-mode)
25102 (or (outline-invisible-p)
25103 (save-excursion (goto-char (max (point-min) (1- (point))))
25104 (outline-invisible-p)))
25105 (org-show-context 'bookmark-jump)))
25107 (defun org-mark-jump-unhide ()
25108 "Make the point visible with `org-show-context' after jumping to the mark."
25109 (when (and (derived-mode-p 'org-mode)
25110 (outline-invisible-p))
25111 (org-show-context 'mark-goto)))
25113 (eval-after-load "simple"
25114 '(defadvice pop-to-mark-command (after org-make-visible activate)
25115 "Make the point visible with `org-show-context'."
25116 (org-mark-jump-unhide)))
25118 (eval-after-load "simple"
25119 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25120 "Make the point visible with `org-show-context'."
25121 (org-mark-jump-unhide)))
25123 (eval-after-load "simple"
25124 '(defadvice pop-global-mark (after org-make-visible activate)
25125 "Make the point visible with `org-show-context'."
25126 (org-mark-jump-unhide)))
25128 ;; Make session.el ignore our circular variable
25129 (defvar session-globals-exclude)
25130 (eval-after-load "session"
25131 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25133 ;;;; Finish up
25135 (provide 'org)
25137 (run-hooks 'org-load-hook)
25139 ;;; org.el ends here