Change `org-align-tags-here' into `org--align-tags-here'
[org-mode.git] / lisp / org.el
blob6d5201b1af2bc3424448a03c648dc841fa4a018f
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-2016 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"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
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))
175 (defsubst org-uniquify (list)
176 "Non-destructively remove duplicate elements from LIST."
177 (let ((res (copy-sequence list))) (delete-dups res)))
179 (defsubst org-get-at-bol (property)
180 "Get text property PROPERTY at the beginning of line."
181 (get-text-property (point-at-bol) property))
183 (defsubst org-trim (s &optional keep-lead)
184 "Remove whitespace at the beginning and the end of string S.
185 When optional argument KEEP-LEAD is non-nil, removing blank lines
186 at the beginning of the string does not affect leading indentation."
187 (replace-regexp-in-string
188 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
189 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
191 ;; load languages based on value of `org-babel-load-languages'
192 (defvar org-babel-load-languages)
194 ;;;###autoload
195 (defun org-babel-do-load-languages (sym value)
196 "Load the languages defined in `org-babel-load-languages'."
197 (set-default sym value)
198 (dolist (pair org-babel-load-languages)
199 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
200 (if active
201 (require (intern (concat "ob-" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-execute:" lang)))
204 (funcall 'fmakunbound
205 (intern (concat "org-babel-expand-body:" lang)))))))
207 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
208 ;;;###autoload
209 (defun org-babel-load-file (file &optional compile)
210 "Load Emacs Lisp source code blocks in the Org FILE.
211 This function exports the source code using `org-babel-tangle'
212 and then loads the resulting file using `load-file'. With prefix
213 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
214 file to byte-code before it is loaded."
215 (interactive "fFile to load: \nP")
216 (let* ((age (lambda (file)
217 (float-time
218 (time-subtract (current-time)
219 (nth 5 (or (file-attributes (file-truename file))
220 (file-attributes file)))))))
221 (base-name (file-name-sans-extension file))
222 (exported-file (concat base-name ".el")))
223 ;; tangle if the Org file is newer than the elisp file
224 (unless (and (file-exists-p exported-file)
225 (> (funcall age file) (funcall age exported-file)))
226 ;; Tangle-file traversal returns reversed list of tangled files
227 ;; and we want to evaluate the first target.
228 (setq exported-file
229 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
230 (message "%s %s"
231 (if compile
232 (progn (byte-compile-file exported-file 'load)
233 "Compiled and loaded")
234 (progn (load-file exported-file) "Loaded"))
235 exported-file)))
237 (defcustom org-babel-load-languages '((emacs-lisp . t))
238 "Languages which can be evaluated in Org buffers.
239 This list can be used to load support for any of the languages
240 below, note that each language will depend on a different set of
241 system executables and/or Emacs modes. When a language is
242 \"loaded\", then code blocks in that language can be evaluated
243 with `org-babel-execute-src-block' bound by default to C-c
244 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
245 be set to remove code block evaluation from the C-c C-c
246 keybinding. By default only Emacs Lisp (which has no
247 requirements) is loaded."
248 :group 'org-babel
249 :set 'org-babel-do-load-languages
250 :version "24.1"
251 :type '(alist :tag "Babel Languages"
252 :key-type
253 (choice
254 (const :tag "Awk" awk)
255 (const :tag "C" C)
256 (const :tag "R" R)
257 (const :tag "Asymptote" asymptote)
258 (const :tag "Calc" calc)
259 (const :tag "Clojure" clojure)
260 (const :tag "CSS" css)
261 (const :tag "Ditaa" ditaa)
262 (const :tag "Dot" dot)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "ebnf2ps" ebnf2ps))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 A deadline is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-deadline].")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 A schedule is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-schedule].")
385 (defconst org-ds-keyword-length
386 (+ 2
387 (apply #'max
388 (mapcar #'length
389 (list org-deadline-string org-scheduled-string
390 org-clock-string org-closed-string))))
391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
393 (defconst org-planning-line-re
394 (concat "^[ \t]*"
395 (regexp-opt
396 (list org-closed-string org-deadline-string org-scheduled-string)
398 "Matches a line with planning info.
399 Matched keyword is in group 1.")
401 (defconst org-clock-line-re
402 (concat "^[ \t]*" org-clock-string)
403 "Matches a line with clock info.")
405 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
406 "Matches the DEADLINE keyword.")
408 (defconst org-deadline-time-regexp
409 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
410 "Matches the DEADLINE keyword together with a time stamp.")
412 (defconst org-deadline-time-hour-regexp
413 (concat "\\<" org-deadline-string
414 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
415 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
417 (defconst org-deadline-line-regexp
418 (concat "\\<\\(" org-deadline-string "\\).*")
419 "Matches the DEADLINE keyword and the rest of the line.")
421 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
422 "Matches the SCHEDULED keyword.")
424 (defconst org-scheduled-time-regexp
425 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
426 "Matches the SCHEDULED keyword together with a time stamp.")
428 (defconst org-scheduled-time-hour-regexp
429 (concat "\\<" org-scheduled-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
433 (defconst org-closed-time-regexp
434 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
435 "Matches the CLOSED keyword together with a time stamp.")
437 (defconst org-keyword-time-regexp
438 (concat "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string
441 org-clock-string)
443 " *[[<]\\([^]>]+\\)[]>]")
444 "Matches any of the 4 keywords, together with the time stamp.")
446 (defconst org-keyword-time-not-clock-regexp
447 (concat
448 "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string) t)
451 " *[[<]\\([^]>]+\\)[]>]")
452 "Matches any of the 3 keywords, together with the time stamp.")
454 (defconst org-maybe-keyword-time-regexp
455 (concat "\\(\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string
458 org-clock-string)
460 "\\)?"
461 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
462 "\\|"
463 "<%%([^\r\n>]*>\\)")
464 "Matches a timestamp, possibly preceded by a keyword.")
466 (defconst org-all-time-keywords
467 (mapcar (lambda (w) (substring w 0 -1))
468 (list org-scheduled-string org-deadline-string
469 org-clock-string org-closed-string))
470 "List of time keywords.")
472 ;;;; Drawer
474 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
475 "Matches first or last line of a hidden block.
476 Group 1 contains drawer's name or \"END\".")
478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
479 "Regular expression matching the first line of a property drawer.")
481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a property drawer.")
484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
485 "Regular expression matching the first line of a clock drawer.")
487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a clock drawer.")
490 (defconst org-property-drawer-re
491 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
492 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
493 "[ \t]*:END:[ \t]*$")
494 "Matches an entire property drawer.")
496 (defconst org-clock-drawer-re
497 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
498 org-clock-drawer-end-re "\\)\n?")
499 "Matches an entire clock drawer.")
501 ;;;; Headline
503 (defconst org-heading-keyword-regexp-format
504 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
505 "Printf format for a regexp matching a headline with some keyword.
506 This regexp will match the headline of any node which has the
507 exact keyword that is put into the format. The keyword isn't in
508 any group by default, but the stars and the body are.")
510 (defconst org-heading-keyword-maybe-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline, possibly with some keyword.
513 This regexp can match any headline with the specified keyword, or
514 without a keyword. The keyword isn't in any group by default,
515 but the stars and the body are.")
517 (defconst org-archive-tag "ARCHIVE"
518 "The tag that marks a subtree as archived.
519 An archived subtree does not open during visibility cycling, and does
520 not contribute to the agenda listings.")
522 (defconst org-comment-string "COMMENT"
523 "Entries starting with this keyword will never be exported.
524 An entry can be toggled between COMMENT and normal with
525 \\[org-toggle-comment].")
528 ;;;; LaTeX Environments and Fragments
530 (defconst org-latex-regexps
531 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
532 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
533 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
534 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
535 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
536 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
537 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
538 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
539 "Regular expressions for matching embedded LaTeX.")
541 ;;;; Node Property
543 (defconst org-effort-property "Effort"
544 "The property that is being used to keep track of effort estimates.
545 Effort estimates given in this property need to have the format H:MM.")
547 ;;;; Table
549 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
550 "Detect an org-type or table-type table.")
552 (defconst org-table-line-regexp "^[ \t]*|"
553 "Detect an org-type table line.")
555 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
556 "Detect an org-type table line.")
558 (defconst org-table-hline-regexp "^[ \t]*|-"
559 "Detect an org-type table hline.")
561 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
562 "Detect a table-type table hline.")
564 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
565 "Detect the first line outside a table when searching from within it.
566 This works for both table types.")
568 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
569 "Detect a #+TBLFM line.")
571 ;;;; Timestamp
573 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
574 "Regular expression for fast time stamp matching.")
576 (defconst org-ts-regexp-inactive
577 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
578 "Regular expression for fast inactive time stamp matching.")
580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp0
584 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
585 "Regular expression matching time strings for analysis.
586 This one does not require the space after the date, so it can be used
587 on a string that terminates immediately after the date.")
589 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.")
592 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
593 "Regular expression matching time stamps, with groups.")
595 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
596 "Regular expression matching time stamps (also [..]), with groups.")
598 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tr-regexp-both
602 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
606 org-ts-regexp "\\)?")
607 "Regular expression matching a time stamp or time stamp range.")
609 (defconst org-tsr-regexp-both
610 (concat org-ts-regexp-both "\\(--?-?"
611 org-ts-regexp-both "\\)?")
612 "Regular expression matching a time stamp or time stamp range.
613 The time stamps may be either active or inactive.")
615 (defconst org-repeat-re
616 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
617 "Regular expression for specifying repeated events.
618 After a match, group 1 contains the repeat expression.")
620 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
621 "Formats for `format-time-string' which are used for time stamps.")
624 ;;; The custom variables
626 (defgroup org nil
627 "Outline-based notes management and organizer."
628 :tag "Org"
629 :group 'outlines
630 :group 'calendar)
632 (defcustom org-mode-hook nil
633 "Mode hook for Org mode, run after the mode was turned on."
634 :group 'org
635 :type 'hook)
637 (defcustom org-load-hook nil
638 "Hook that is run after org.el has been loaded."
639 :group 'org
640 :type 'hook)
642 (defcustom org-log-buffer-setup-hook nil
643 "Hook that is run after an Org log buffer is created."
644 :group 'org
645 :version "24.1"
646 :type 'hook)
648 (defvar org-modules) ; defined below
649 (defvar org-modules-loaded nil
650 "Have the modules been loaded already?")
652 (defun org-load-modules-maybe (&optional force)
653 "Load all extensions listed in `org-modules'."
654 (when (or force (not org-modules-loaded))
655 (dolist (ext org-modules)
656 (condition-case nil (require ext)
657 (error (message "Problems while trying to load feature `%s'" ext))))
658 (setq org-modules-loaded t)))
660 (defun org-set-modules (var value)
661 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
662 (set var value)
663 (when (featurep 'org)
664 (org-load-modules-maybe 'force)
665 (org-element-cache-reset 'all)))
667 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
668 "Modules that should always be loaded together with org.el.
670 If a description starts with <C>, the file is not part of Emacs
671 and loading it will require that you have downloaded and properly
672 installed the Org mode distribution.
674 You can also use this system to load external packages (i.e. neither Org
675 core modules, nor modules from the CONTRIB directory). Just add symbols
676 to the end of the list. If the package is called org-xyz.el, then you need
677 to add the symbol `xyz', and the package must have a call to:
679 (provide \\='org-xyz)
681 For export specific modules, see also `org-export-backends'."
682 :group 'org
683 :set 'org-set-modules
684 :version "24.4"
685 :package-version '(Org . "8.0")
686 :type
687 '(set :greedy t
688 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
689 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
690 (const :tag " crypt: Encryption of subtrees" org-crypt)
691 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
692 (const :tag " docview: Links to doc-view buffers" org-docview)
693 (const :tag " eww: Store link to url of eww" org-eww)
694 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
695 (const :tag " habit: Track your consistency with habits" org-habit)
696 (const :tag " id: Global IDs for identifying entries" org-id)
697 (const :tag " info: Links to Info nodes" org-info)
698 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
699 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
700 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
701 (const :tag " mouse: Additional mouse support" org-mouse)
702 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
703 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
704 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
706 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
707 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
708 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
709 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
710 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
711 (const :tag "C collector: Collect properties into tables" org-collector)
712 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
713 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
714 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
715 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
716 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
717 (const :tag "C eval: Include command output as text" org-eval)
718 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
719 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
720 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
721 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
722 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
723 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
724 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
725 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
726 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
727 (const :tag "C man: Support for links to manpages in Org mode" org-man)
728 (const :tag "C mew: Links to Mew folders/messages" org-mew)
729 (const :tag "C mtags: Support for muse-like tags" org-mtags)
730 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
731 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
732 (const :tag "C registry: A registry for Org links" org-registry)
733 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
734 (const :tag "C secretary: Team management with org-mode" org-secretary)
735 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
736 (const :tag "C toc: Table of contents for Org buffer" org-toc)
737 (const :tag "C track: Keep up with Org mode development" org-track)
738 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
739 (const :tag "C vm: Links to VM folders/messages" org-vm)
740 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
741 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
742 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
744 (defvar org-export-registered-backends) ; From ox.el.
745 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
746 (declare-function org-export-backend-name "ox" (backend) t)
747 (defcustom org-export-backends '(ascii html icalendar latex odt)
748 "List of export back-ends that should be always available.
750 If a description starts with <C>, the file is not part of Emacs
751 and loading it will require that you have downloaded and properly
752 installed the Org mode distribution.
754 Unlike to `org-modules', libraries in this list will not be
755 loaded along with Org, but only once the export framework is
756 needed.
758 This variable needs to be set before org.el is loaded. If you
759 need to make a change while Emacs is running, use the customize
760 interface or run the following code, where VAL stands for the new
761 value of the variable, after updating it:
763 (progn
764 (setq org-export-registered-backends
765 (cl-remove-if-not
766 (lambda (backend)
767 (let ((name (org-export-backend-name backend)))
768 (or (memq name val)
769 (catch \\='parentp
770 (dolist (b val)
771 (and (org-export-derived-backend-p b name)
772 (throw \\='parentp t)))))))
773 org-export-registered-backends))
774 (let ((new-list (mapcar #\\='org-export-backend-name
775 org-export-registered-backends)))
776 (dolist (backend val)
777 (cond
778 ((not (load (format \"ox-%s\" backend) t t))
779 (message \"Problems while trying to load export back-end \\=`%s\\='\"
780 backend))
781 ((not (memq backend new-list)) (push backend new-list))))
782 (set-default \\='org-export-backends new-list)))
784 Adding a back-end to this list will also pull the back-end it
785 depends on, if any."
786 :group 'org
787 :group 'org-export
788 :version "25.2"
789 :package-version '(Org . "9.0")
790 :initialize 'custom-initialize-set
791 :set (lambda (var val)
792 (if (not (featurep 'ox)) (set-default var val)
793 ;; Any back-end not required anymore (not present in VAL and not
794 ;; a parent of any back-end in the new value) is removed from the
795 ;; list of registered back-ends.
796 (setq org-export-registered-backends
797 (cl-remove-if-not
798 (lambda (backend)
799 (let ((name (org-export-backend-name backend)))
800 (or (memq name val)
801 (catch 'parentp
802 (dolist (b val)
803 (and (org-export-derived-backend-p b name)
804 (throw 'parentp t)))))))
805 org-export-registered-backends))
806 ;; Now build NEW-LIST of both new back-ends and required
807 ;; parents.
808 (let ((new-list (mapcar #'org-export-backend-name
809 org-export-registered-backends)))
810 (dolist (backend val)
811 (cond
812 ((not (load (format "ox-%s" backend) t t))
813 (message "Problems while trying to load export back-end `%s'"
814 backend))
815 ((not (memq backend new-list)) (push backend new-list))))
816 ;; Set VAR to that list with fixed dependencies.
817 (set-default var new-list))))
818 :type '(set :greedy t
819 (const :tag " ascii Export buffer to ASCII format" ascii)
820 (const :tag " beamer Export buffer to Beamer presentation" beamer)
821 (const :tag " html Export buffer to HTML format" html)
822 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
823 (const :tag " latex Export buffer to LaTeX format" latex)
824 (const :tag " man Export buffer to MAN format" man)
825 (const :tag " md Export buffer to Markdown format" md)
826 (const :tag " odt Export buffer to ODT format" odt)
827 (const :tag " org Export buffer to Org format" org)
828 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
829 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
830 (const :tag "C deck Export buffer to deck.js presentations" deck)
831 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
832 (const :tag "C groff Export buffer to Groff format" groff)
833 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
834 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
835 (const :tag "C s5 Export buffer to s5 presentations" s5)
836 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
838 (eval-after-load 'ox
839 '(dolist (backend org-export-backends)
840 (condition-case nil (require (intern (format "ox-%s" backend)))
841 (error (message "Problems while trying to load export back-end `%s'"
842 backend)))))
844 (defcustom org-support-shift-select nil
845 "Non-nil means make shift-cursor commands select text when possible.
846 \\<org-mode-map>\
848 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
849 start selecting a region, or enlarge regions started in this way.
850 In Org mode, in special contexts, these same keys are used for
851 other purposes, important enough to compete with shift selection.
852 Org tries to balance these needs by supporting `shift-select-mode'
853 outside these special contexts, under control of this variable.
855 The default of this variable is nil, to avoid confusing behavior. Shifted
856 cursor keys will then execute Org commands in the following contexts:
857 - on a headline, changing TODO state (left/right) and priority (up/down)
858 - on a time stamp, changing the time
859 - in a plain list item, changing the bullet type
860 - in a property definition line, switching between allowed values
861 - in the BEGIN line of a clock table (changing the time block).
862 Outside these contexts, the commands will throw an error.
864 When this variable is t and the cursor is not in a special
865 context, Org mode will support shift-selection for making and
866 enlarging regions. To make this more effective, the bullet
867 cycling will no longer happen anywhere in an item line, but only
868 if the cursor is exactly on the bullet.
870 If you set this variable to the symbol `always', then the keys
871 will not be special in headlines, property lines, and item lines,
872 to make shift selection work there as well. If this is what you
873 want, you can use the following alternative commands:
874 `\\[org-todo]' and `\\[org-priority]' \
875 to change TODO state and priority,
876 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
877 can be used to switch TODO sets,
878 `\\[org-ctrl-c-minus]' to cycle item bullet types,
879 and properties can be edited by hand or in column view.
881 However, when the cursor is on a timestamp, shift-cursor commands
882 will still edit the time stamp - this is just too good to give up."
883 :group 'org
884 :type '(choice
885 (const :tag "Never" nil)
886 (const :tag "When outside special context" t)
887 (const :tag "Everywhere except timestamps" always)))
889 (defcustom org-loop-over-headlines-in-active-region nil
890 "Shall some commands act upon headlines in the active region?
892 When set to t, some commands will be performed in all headlines
893 within the active region.
895 When set to `start-level', some commands will be performed in all
896 headlines within the active region, provided that these headlines
897 are of the same level than the first one.
899 When set to a string, those commands will be performed on the
900 matching headlines within the active region. Such string must be
901 a tags/property/todo match as it is used in the agenda tags view.
903 The list of commands is: `org-schedule', `org-deadline',
904 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
905 `org-archive-to-archive-sibling'. The archiving commands skip
906 already archived entries."
907 :type '(choice (const :tag "Don't loop" nil)
908 (const :tag "All headlines in active region" t)
909 (const :tag "In active region, headlines at the same level than the first one" start-level)
910 (string :tag "Tags/Property/Todo matcher"))
911 :version "24.1"
912 :group 'org-todo
913 :group 'org-archive)
915 (defgroup org-startup nil
916 "Options concerning startup of Org mode."
917 :tag "Org Startup"
918 :group 'org)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
922 This can also be configured on a per-file basis by adding one of
923 the following lines anywhere in the buffer:
925 #+STARTUP: fold (or `overview', this is equivalent)
926 #+STARTUP: nofold (or `showall', this is equivalent)
927 #+STARTUP: content
928 #+STARTUP: showeverything
930 By default, this option is ignored when Org opens agenda files
931 for the first time. If you want the agenda to honor the startup
932 option, set `org-agenda-inhibit-startup' to nil."
933 :group 'org-startup
934 :type '(choice
935 (const :tag "nofold: show all" nil)
936 (const :tag "fold: overview" t)
937 (const :tag "content: all headlines" content)
938 (const :tag "show everything, even drawers" showeverything)))
940 (defcustom org-startup-truncated t
941 "Non-nil means entering Org mode will set `truncate-lines'.
942 This is useful since some lines containing links can be very long and
943 uninteresting. Also tables look terrible when wrapped.
945 The variable `org-startup-truncated' allows to configure
946 truncation for Org mode different to the other modes that use the
947 variable `truncate-lines' and as a shortcut instead of putting
948 the variable `truncate-lines' into the `org-mode-hook'. If one
949 wants to configure truncation for Org mode not statically but
950 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
951 the variable `truncate-lines' has to be used because in such a
952 case it is too late to set the variable `org-startup-truncated'."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org mode.
1048 To ensure that the file will always be in Org mode in the future, a
1049 line enforcing Org mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org mode together with one of these other modes,
1060 or more generally if you would like to move some Org mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if `window-system' is nil. This
1073 variable lets you do the same manually. You must set it before
1074 loading Org."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1080 (defcustom org-disputed-keys
1081 '(([(shift up)] . [(meta p)])
1082 ([(shift down)] . [(meta n)])
1083 ([(shift left)] . [(meta -)])
1084 ([(shift right)] . [(meta +)])
1085 ([(control shift right)] . [(meta shift +)])
1086 ([(control shift left)] . [(meta shift -)]))
1087 "Keys for which Org mode and other modes compete.
1088 This is an alist, cars are the default keys, second element specifies
1089 the alternative to use when `org-replace-disputed-keys' is t.
1091 Keys can be specified in any syntax supported by `define-key'.
1092 The value of this option takes effect only at Org mode startup,
1093 therefore you'll have to restart Emacs to apply it after changing."
1094 :group 'org-startup
1095 :type 'alist)
1097 (defun org-key (key)
1098 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1099 Or return the original if not disputed."
1100 (when org-replace-disputed-keys
1101 (let* ((nkey (key-description key))
1102 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1103 org-disputed-keys)))
1104 (setq key (if x (cdr x) key))))
1105 key)
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((agenda . local)
1151 (bookmark-jump . lineage)
1152 (isearch . lineage)
1153 (default . ancestors))
1154 "Alist between context and visibility span when revealing a location.
1156 \\<org-mode-map>Some actions may move point into invisible
1157 locations. As a consequence, Org always expose a neighborhood
1158 around point. How much is shown depends on the initial action,
1159 or context. Valid contexts are
1161 agenda when exposing an entry from the agenda
1162 org-goto when using the command `org-goto' (\\[org-goto])
1163 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1164 tags-tree when constructing a sparse tree based on tags matches
1165 link-search when exposing search matches associated with a link
1166 mark-goto when exposing the jump goal of a mark
1167 bookmark-jump when exposing a bookmark location
1168 isearch when exiting from an incremental search
1169 default default for all contexts not set explicitly
1171 Allowed visibility spans are
1173 minimal show current headline; if point is not on headline,
1174 also show entry
1176 local show current headline, entry and next headline
1178 ancestors show current headline and its direct ancestors; if
1179 point is not on headline, also show entry
1181 lineage show current headline, its direct ancestors and all
1182 their children; if point is not on headline, also show
1183 entry and first child
1185 tree show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and all children
1189 canonical show current headline, its direct ancestors along with
1190 their entries and children; if point is not located on
1191 the headline, also show current entry and all children
1193 As special cases, a nil or t value means show all contexts in
1194 `minimal' or `canonical' view, respectively.
1196 Some views can make displayed information very compact, but also
1197 make it harder to edit the location of the match. In such
1198 a case, use the command `org-reveal' (\\[org-reveal]) to show
1199 more context."
1200 :group 'org-reveal-location
1201 :version "25.2"
1202 :package-version '(Org . "9.0")
1203 :type '(choice
1204 (const :tag "Canonical" t)
1205 (const :tag "Minimal" nil)
1206 (repeat :greedy t :tag "Individual contexts"
1207 (cons
1208 (choice :tag "Context"
1209 (const agenda)
1210 (const org-goto)
1211 (const occur-tree)
1212 (const tags-tree)
1213 (const link-search)
1214 (const mark-goto)
1215 (const bookmark-jump)
1216 (const isearch)
1217 (const default))
1218 (choice :tag "Detail level"
1219 (const minimal)
1220 (const local)
1221 (const ancestors)
1222 (const lineage)
1223 (const tree)
1224 (const canonical))))))
1226 (defcustom org-indirect-buffer-display 'other-window
1227 "How should indirect tree buffers be displayed?
1228 This applies to indirect buffers created with the commands
1229 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1230 Valid values are:
1231 current-window Display in the current window
1232 other-window Just display in another window.
1233 dedicated-frame Create one new frame, and re-use it each time.
1234 new-frame Make a new frame each time. Note that in this case
1235 previously-made indirect buffers are kept, and you need to
1236 kill these buffers yourself."
1237 :group 'org-structure
1238 :group 'org-agenda-windows
1239 :type '(choice
1240 (const :tag "In current window" current-window)
1241 (const :tag "In current frame, other window" other-window)
1242 (const :tag "Each time a new frame" new-frame)
1243 (const :tag "One dedicated frame" dedicated-frame)))
1245 (defcustom org-use-speed-commands nil
1246 "Non-nil means activate single letter commands at beginning of a headline.
1247 This may also be a function to test for appropriate locations where speed
1248 commands should be active.
1250 For example, to activate speed commands when the point is on any
1251 star at the beginning of the headline, you can do this:
1253 (setq org-use-speed-commands
1254 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1255 :group 'org-structure
1256 :type '(choice
1257 (const :tag "Never" nil)
1258 (const :tag "At beginning of headline stars" t)
1259 (function)))
1261 (defcustom org-speed-commands-user nil
1262 "Alist of additional speed commands.
1263 This list will be checked before `org-speed-commands-default'
1264 when the variable `org-use-speed-commands' is non-nil
1265 and when the cursor is at the beginning of a headline.
1266 The car if each entry is a string with a single letter, which must
1267 be assigned to `self-insert-command' in the global map.
1268 The cdr is either a command to be called interactively, a function
1269 to be called, or a form to be evaluated.
1270 An entry that is just a list with a single string will be interpreted
1271 as a descriptive headline that will be added when listing the speed
1272 commands in the Help buffer using the `?' speed command."
1273 :group 'org-structure
1274 :type '(repeat :value ("k" . ignore)
1275 (choice :value ("k" . ignore)
1276 (list :tag "Descriptive Headline" (string :tag "Headline"))
1277 (cons :tag "Letter and Command"
1278 (string :tag "Command letter")
1279 (choice
1280 (function)
1281 (sexp))))))
1283 (defcustom org-bookmark-names-plist
1284 '(:last-capture "org-capture-last-stored"
1285 :last-refile "org-refile-last-stored"
1286 :last-capture-marker "org-capture-last-stored-marker")
1287 "Names for bookmarks automatically set by some Org commands.
1288 This can provide strings as names for a number of bookmarks Org sets
1289 automatically. The following keys are currently implemented:
1290 :last-capture
1291 :last-capture-marker
1292 :last-refile
1293 When a key does not show up in the property list, the corresponding bookmark
1294 is not set."
1295 :group 'org-structure
1296 :type 'plist)
1298 (defgroup org-cycle nil
1299 "Options concerning visibility cycling in Org mode."
1300 :tag "Org Cycle"
1301 :group 'org-structure)
1303 (defcustom org-cycle-skip-children-state-if-no-children t
1304 "Non-nil means skip CHILDREN state in entries that don't have any."
1305 :group 'org-cycle
1306 :type 'boolean)
1308 (defcustom org-cycle-max-level nil
1309 "Maximum level which should still be subject to visibility cycling.
1310 Levels higher than this will, for cycling, be treated as text, not a headline.
1311 When `org-odd-levels-only' is set, a value of N in this variable actually
1312 means 2N-1 stars as the limiting headline.
1313 When nil, cycle all levels.
1314 Note that the limiting level of cycling is also influenced by
1315 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1316 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1317 than its value."
1318 :group 'org-cycle
1319 :type '(choice
1320 (const :tag "No limit" nil)
1321 (integer :tag "Maximum level")))
1323 (defcustom org-hide-block-startup nil
1324 "Non-nil means entering Org mode will fold all blocks.
1325 This can also be set in on a per-file basis with
1327 #+STARTUP: hideblocks
1328 #+STARTUP: showblocks"
1329 :group 'org-startup
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-global-at-bob nil
1334 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1335 This makes it possible to do global cycling without having to use S-TAB or
1336 \\[universal-argument] TAB. For this special case to work, the first line
1337 of the buffer must not be a headline -- it may be empty or some other text.
1338 When used in this way, `org-cycle-hook' is disabled temporarily to make
1339 sure the cursor stays at the beginning of the buffer. When this option is
1340 nil, don't do anything special at the beginning of the buffer."
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-level-after-item/entry-creation t
1345 "Non-nil means cycle entry level or item indentation in new empty entries.
1347 When the cursor is at the end of an empty headline, i.e., with only stars
1348 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1349 and then all possible ancestor states, before returning to the original state.
1350 This makes data entry extremely fast: M-RET to create a new headline,
1351 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1353 When the cursor is at the end of an empty plain list item, one TAB will
1354 make it a subitem, two or more tabs will back up to make this an item
1355 higher up in the item hierarchy."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-emulate-tab t
1360 "Where should `org-cycle' emulate TAB.
1361 nil Never
1362 white Only in completely white lines
1363 whitestart Only at the beginning of lines, before the first non-white char
1364 t Everywhere except in headlines
1365 exc-hl-bol Everywhere except at the start of a headline
1366 If TAB is used in a place where it does not emulate TAB, the current subtree
1367 visibility is cycled."
1368 :group 'org-cycle
1369 :type '(choice (const :tag "Never" nil)
1370 (const :tag "Only in completely white lines" white)
1371 (const :tag "Before first char in a line" whitestart)
1372 (const :tag "Everywhere except in headlines" t)
1373 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1375 (defcustom org-cycle-separator-lines 2
1376 "Number of empty lines needed to keep an empty line between collapsed trees.
1377 If you leave an empty line between the end of a subtree and the following
1378 headline, this empty line is hidden when the subtree is folded.
1379 Org mode will leave (exactly) one empty line visible if the number of
1380 empty lines is equal or larger to the number given in this variable.
1381 So the default 2 means at least 2 empty lines after the end of a subtree
1382 are needed to produce free space between a collapsed subtree and the
1383 following headline.
1385 If the number is negative, and the number of empty lines is at least -N,
1386 all empty lines are shown.
1388 Special case: when 0, never leave empty lines in collapsed view."
1389 :group 'org-cycle
1390 :type 'integer)
1391 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1393 (defcustom org-pre-cycle-hook nil
1394 "Hook that is run before visibility cycling is happening.
1395 The function(s) in this hook must accept a single argument which indicates
1396 the new state that will be set right after running this hook. The
1397 argument is a symbol. Before a global state change, it can have the values
1398 `overview', `content', or `all'. Before a local state change, it can have
1399 the values `folded', `children', or `subtree'."
1400 :group 'org-cycle
1401 :type 'hook)
1403 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1404 org-cycle-hide-drawers
1405 org-cycle-show-empty-lines
1406 org-optimize-window-after-visibility-change)
1407 "Hook that is run after `org-cycle' has changed the buffer visibility.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that was set by the most recent `org-cycle' command. The
1410 argument is a symbol. After a global state change, it can have the values
1411 `overview', `contents', or `all'. After a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook
1415 :version "25.2"
1416 :package-version '(Org . "8.3"))
1418 (defgroup org-edit-structure nil
1419 "Options concerning structure editing in Org mode."
1420 :tag "Org Edit Structure"
1421 :group 'org-structure)
1423 (defcustom org-odd-levels-only nil
1424 "Non-nil means skip even levels and only use odd levels for the outline.
1425 This has the effect that two stars are being added/taken away in
1426 promotion/demotion commands. It also influences how levels are
1427 handled by the exporters.
1428 Changing it requires restart of `font-lock-mode' to become effective
1429 for fontification also in regions already fontified.
1430 You may also set this on a per-file basis by adding one of the following
1431 lines to the buffer:
1433 #+STARTUP: odd
1434 #+STARTUP: oddeven"
1435 :group 'org-edit-structure
1436 :group 'org-appearance
1437 :type 'boolean)
1439 (defcustom org-adapt-indentation t
1440 "Non-nil means adapt indentation to outline node level.
1442 When this variable is set, Org assumes that you write outlines by
1443 indenting text in each node to align with the headline (after the
1444 stars). The following issues are influenced by this variable:
1446 - The indentation is increased by one space in a demotion
1447 command, and decreased by one in a promotion command. However,
1448 in the latter case, if shifting some line in the entry body
1449 would alter document structure (e.g., insert a new headline),
1450 indentation is not changed at all.
1452 - Property drawers and planning information is inserted indented
1453 when this variable is set. When nil, they will not be indented.
1455 - TAB indents a line relative to current level. The lines below
1456 a headline will be indented when this variable is set.
1458 Note that this is all about true indentation, by adding and
1459 removing space characters. See also `org-indent.el' which does
1460 level-dependent indentation in a virtual way, i.e. at display
1461 time in Emacs."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-special-ctrl-a/e nil
1466 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1468 When t, `C-a' will bring back the cursor to the beginning of the
1469 headline text, i.e. after the stars and after a possible TODO
1470 keyword. In an item, this will be the position after bullet and
1471 check-box, if any. When the cursor is already at that position,
1472 another `C-a' will bring it to the beginning of the line.
1474 `C-e' will jump to the end of the headline, ignoring the presence
1475 of tags in the headline. A second `C-e' will then jump to the
1476 true end of the line, after any tags. This also means that, when
1477 this variable is non-nil, `C-e' also will never jump beyond the
1478 end of the heading of a folded section, i.e. not after the
1479 ellipses.
1481 When set to the symbol `reversed', the first `C-a' or `C-e' works
1482 normally, going to the true line boundary first. Only a directly
1483 following, identical keypress will bring the cursor to the
1484 special positions.
1486 This may also be a cons cell where the behavior for `C-a' and
1487 `C-e' is set separately."
1488 :group 'org-edit-structure
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on: after stars/bullet and before tags first" t)
1492 (const :tag "reversed: true line boundary first" reversed)
1493 (cons :tag "Set C-a and C-e separately"
1494 (choice :tag "Special C-a"
1495 (const :tag "off" nil)
1496 (const :tag "on: after stars/bullet first" t)
1497 (const :tag "reversed: before stars/bullet first" reversed))
1498 (choice :tag "Special C-e"
1499 (const :tag "off" nil)
1500 (const :tag "on: before tags first" t)
1501 (const :tag "reversed: after tags first" reversed)))))
1502 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1504 (defcustom org-special-ctrl-k nil
1505 "Non-nil means `C-k' will behave specially in headlines.
1506 When nil, `C-k' will call the default `kill-line' command.
1507 When t, the following will happen while the cursor is in the headline:
1509 - When the cursor is at the beginning of a headline, kill the entire
1510 line and possible the folded subtree below the line.
1511 - When in the middle of the headline text, kill the headline up to the tags.
1512 - When after the headline text, kill the tags."
1513 :group 'org-edit-structure
1514 :type 'boolean)
1516 (defcustom org-ctrl-k-protect-subtree nil
1517 "Non-nil means, do not delete a hidden subtree with C-k.
1518 When set to the symbol `error', simply throw an error when C-k is
1519 used to kill (part-of) a headline that has hidden text behind it.
1520 Any other non-nil value will result in a query to the user, if it is
1521 OK to kill that hidden subtree. When nil, kill without remorse."
1522 :group 'org-edit-structure
1523 :version "24.1"
1524 :type '(choice
1525 (const :tag "Do not protect hidden subtrees" nil)
1526 (const :tag "Protect hidden subtrees with a security query" t)
1527 (const :tag "Never kill a hidden subtree with C-k" error)))
1529 (defcustom org-special-ctrl-o t
1530 "Non-nil means, make `C-o' insert a row in tables."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-catch-invisible-edits nil
1535 "Check if in invisible region before inserting or deleting a character.
1536 Valid values are:
1538 nil Do not check, so just do invisible edits.
1539 error Throw an error and do nothing.
1540 show Make point visible, and do the requested edit.
1541 show-and-error Make point visible, then throw an error and abort the edit.
1542 smart Make point visible, and do insertion/deletion if it is
1543 adjacent to visible text and the change feels predictable.
1544 Never delete a previously invisible character or add in the
1545 middle or right after an invisible region. Basically, this
1546 allows insertion and backward-delete right before ellipses.
1547 FIXME: maybe in this case we should not even show?"
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not check" nil)
1552 (const :tag "Throw error when trying to edit" error)
1553 (const :tag "Unhide, but do not do the edit" show-and-error)
1554 (const :tag "Show invisible part and do the edit" show)
1555 (const :tag "Be smart and do the right thing" smart)))
1557 (defcustom org-yank-folded-subtrees t
1558 "Non-nil means when yanking subtrees, fold them.
1559 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1560 it starts with a heading and all other headings in it are either children
1561 or siblings, then fold all the subtrees. However, do this only if no
1562 text after the yank would be swallowed into a folded tree by this action."
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defcustom org-yank-adjusted-subtrees nil
1567 "Non-nil means when yanking subtrees, adjust the level.
1568 With this setting, `org-paste-subtree' is used to insert the subtree, see
1569 this function for details."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-M-RET-may-split-line '((default . t))
1574 "Non-nil means M-RET will split the line at the cursor position.
1575 When nil, it will go to the end of the line before making a
1576 new line.
1577 You may also set this option in a different way for different
1578 contexts. Valid contexts are:
1580 headline when creating a new headline
1581 item when creating a new item
1582 table in a table field
1583 default the value to be used for all contexts not explicitly
1584 customized"
1585 :group 'org-structure
1586 :group 'org-table
1587 :type '(choice
1588 (const :tag "Always" t)
1589 (const :tag "Never" nil)
1590 (repeat :greedy t :tag "Individual contexts"
1591 (cons
1592 (choice :tag "Context"
1593 (const headline)
1594 (const item)
1595 (const table)
1596 (const default))
1597 (boolean)))))
1600 (defcustom org-insert-heading-respect-content nil
1601 "Non-nil means insert new headings after the current subtree.
1602 When nil, the new heading is created directly after the current line.
1603 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1604 this variable on for the duration of the command."
1605 :group 'org-structure
1606 :type 'boolean)
1608 (defcustom org-blank-before-new-entry '((heading . auto)
1609 (plain-list-item . auto))
1610 "Should `org-insert-heading' leave a blank line before new heading/item?
1611 The value is an alist, with `heading' and `plain-list-item' as CAR,
1612 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1613 which case Org will look at the surrounding headings/items and try to
1614 make an intelligent decision whether to insert a blank line or not."
1615 :group 'org-edit-structure
1616 :type '(list
1617 (cons (const heading)
1618 (choice (const :tag "Never" nil)
1619 (const :tag "Always" t)
1620 (const :tag "Auto" auto)))
1621 (cons (const plain-list-item)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))))
1626 (defcustom org-insert-heading-hook nil
1627 "Hook being run after inserting a new heading."
1628 :group 'org-edit-structure
1629 :type 'hook)
1631 (defcustom org-enable-fixed-width-editor t
1632 "Non-nil means lines starting with \":\" are treated as fixed-width.
1633 This currently only means they are never auto-wrapped.
1634 When nil, such lines will be treated like ordinary lines."
1635 :group 'org-edit-structure
1636 :type 'boolean)
1638 (defcustom org-goto-auto-isearch t
1639 "Non-nil means typing characters in `org-goto' starts incremental search.
1640 When nil, you can use these keybindings to navigate the buffer:
1642 q Quit the org-goto interface
1643 n Go to the next visible heading
1644 p Go to the previous visible heading
1645 f Go one heading forward on same level
1646 b Go one heading backward on same level
1647 u Go one heading up"
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defgroup org-sparse-trees nil
1652 "Options concerning sparse trees in Org mode."
1653 :tag "Org Sparse Trees"
1654 :group 'org-structure)
1656 (defcustom org-highlight-sparse-tree-matches t
1657 "Non-nil means highlight all matches that define a sparse tree.
1658 The highlights will automatically disappear the next time the buffer is
1659 changed by an edit command."
1660 :group 'org-sparse-trees
1661 :type 'boolean)
1663 (defcustom org-remove-highlights-with-change t
1664 "Non-nil means any change to the buffer will remove temporary highlights.
1665 \\<org-mode-map>\
1666 Such highlights are created by `org-occur' and `org-clock-display'.
1667 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1668 to get rid of the highlights.
1669 The highlights created by `org-toggle-latex-fragment' always need
1670 `\\[org-toggle-latex-fragment]' to be removed."
1671 :group 'org-sparse-trees
1672 :group 'org-time
1673 :type 'boolean)
1675 (defcustom org-occur-case-fold-search t
1676 "Non-nil means `org-occur' should be case-insensitive.
1677 If set to `smart' the search will be case-insensitive only if it
1678 doesn't specify any upper case character."
1679 :group 'org-sparse-trees
1680 :version "25.2"
1681 :type '(choice
1682 (const :tag "Case-sensitive" nil)
1683 (const :tag "Case-insensitive" t)
1684 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1686 (defcustom org-occur-hook '(org-first-headline-recenter)
1687 "Hook that is run after `org-occur' has constructed a sparse tree.
1688 This can be used to recenter the window to show as much of the structure
1689 as possible."
1690 :group 'org-sparse-trees
1691 :type 'hook)
1693 (defgroup org-imenu-and-speedbar nil
1694 "Options concerning imenu and speedbar in Org mode."
1695 :tag "Org Imenu and Speedbar"
1696 :group 'org-structure)
1698 (defcustom org-imenu-depth 2
1699 "The maximum level for Imenu access to Org headlines.
1700 This also applied for speedbar access."
1701 :group 'org-imenu-and-speedbar
1702 :type 'integer)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-enable-table-editor 'optimized
1710 "Non-nil means lines starting with \"|\" are handled by the table editor.
1711 When nil, such lines will be treated like ordinary lines.
1713 When equal to the symbol `optimized', the table editor will be optimized to
1714 do the following:
1715 - Automatic overwrite mode in front of whitespace in table fields.
1716 This makes the structure of the table stay in tact as long as the edited
1717 field does not exceed the column width.
1718 - Minimize the number of realigns. Normally, the table is aligned each time
1719 TAB or RET are pressed to move to another field. With optimization this
1720 happens only if changes to a field might have changed the column width.
1721 Optimization requires replacing the functions `self-insert-command',
1722 `delete-char', and `backward-delete-char' in Org buffers, with a
1723 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1724 good at guessing when a re-align will be necessary, but you can always
1725 force one with \\[org-ctrl-c-ctrl-c].
1727 If you would like to use the optimized version in Org mode, but the
1728 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1730 This variable can be used to turn on and off the table editor during a session,
1731 but in order to toggle optimization, a restart is required.
1733 See also the variable `org-table-auto-blank-field'."
1734 :group 'org-table
1735 :type '(choice
1736 (const :tag "off" nil)
1737 (const :tag "on" t)
1738 (const :tag "on, optimized" optimized)))
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-parameters
1765 '(("doi" :follow org--open-doi-link)
1766 ("elisp" :follow org--open-elisp-link)
1767 ("file" :complete org-file-complete-link)
1768 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1769 ("help" :follow org--open-help-link)
1770 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1771 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1772 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1773 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1774 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1775 ("shell" :follow org--open-shell-link))
1776 "An alist of properties that defines all the links in Org mode.
1777 The key in each association is a string of the link type.
1778 Subsequent optional elements make up a p-list of link properties.
1780 :follow - A function that takes the link path as an argument.
1782 :export - A function that takes the link path, description and
1783 export-backend as arguments.
1785 :store - A function responsible for storing the link. See the
1786 function `org-store-link-functions'.
1788 :complete - A function that inserts a link with completion. The
1789 function takes one optional prefix arg.
1791 :face - A face for the link, or a function that returns a face.
1792 The function takes one argument which is the link path. The
1793 default face is `org-link'.
1795 :mouse-face - The mouse-face. The default is `highlight'.
1797 :display - `full' will not fold the link in descriptive
1798 display. Default is `org-link'.
1800 :help-echo - A string or function that takes (window object position)
1801 as arguments and returns a string.
1803 :keymap - A keymap that is active on the link. The default is
1804 `org-mouse-map'.
1806 :htmlize-link - A function for the htmlize-link. Defaults
1807 to (list :uri \"type:path\")
1809 :activate-func - A function to run at the end of font-lock
1810 activation. The function must accept (link-start link-end path bracketp)
1811 as arguments."
1812 :group 'org-link
1813 :type '(alist :tag "Link display parameters"
1814 :value-type plist))
1816 (defun org-link-get-parameter (type key)
1817 "Get TYPE link property for KEY.
1818 TYPE is a string and KEY is a plist keyword."
1819 (plist-get
1820 (cdr (assoc type org-link-parameters))
1821 key))
1823 (defun org-link-set-parameters (type &rest parameters)
1824 "Set link TYPE properties to PARAMETERS.
1825 PARAMETERS should be :key val pairs."
1826 (let ((data (assoc type org-link-parameters)))
1827 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1828 (push (cons type parameters) org-link-parameters)
1829 (org-make-link-regexps)
1830 (org-element-update-syntax))))
1832 (defun org-link-types ()
1833 "Return a list of known link types."
1834 (mapcar #'car org-link-parameters))
1836 (defcustom org-link-abbrev-alist nil
1837 "Alist of link abbreviations.
1838 The car of each element is a string, to be replaced at the start of a link.
1839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1840 links in Org buffers can have an optional tag after a double colon, e.g.,
1842 [[linkkey:tag][description]]
1844 The `linkkey' must be a single word, starting with a letter, followed
1845 by letters, numbers, `-' or `_'.
1847 If REPLACE is a string, the tag will simply be appended to create the link.
1848 If the string contains \"%s\", the tag will be inserted there. If the string
1849 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1850 at that point (see the function `url-hexify-string'). If the string contains
1851 the specifier \"%(my-function)\", then the custom function `my-function' will
1852 be invoked: this function takes the tag as its only argument and must return
1853 a string.
1855 REPLACE may also be a function that will be called with the tag as the
1856 only argument to create the link, which should be returned as a string.
1858 See the manual for examples."
1859 :group 'org-link
1860 :type '(repeat
1861 (cons
1862 (string :tag "Protocol")
1863 (choice
1864 (string :tag "Format")
1865 (function)))))
1867 (defcustom org-descriptive-links t
1868 "Non-nil means Org will display descriptive links.
1869 E.g. [[http://orgmode.org][Org website]] will be displayed as
1870 \"Org Website\", hiding the link itself and just displaying its
1871 description. When set to nil, Org will display the full links
1872 literally.
1874 You can interactively set the value of this variable by calling
1875 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1876 :group 'org-link
1877 :type 'boolean)
1879 (defcustom org-link-file-path-type 'adaptive
1880 "How the path name in file links should be stored.
1881 Valid values are:
1883 relative Relative to the current directory, i.e. the directory of the file
1884 into which the link is being inserted.
1885 absolute Absolute path, if possible with ~ for home directory.
1886 noabbrev Absolute path, no abbreviation of home directory.
1887 adaptive Use relative path for files in the current directory and sub-
1888 directories of it. For other files, use an absolute path."
1889 :group 'org-link
1890 :type '(choice
1891 (const relative)
1892 (const absolute)
1893 (const noabbrev)
1894 (const adaptive)))
1896 (defvaralias 'org-activate-links 'org-highlight-links)
1897 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1898 "Types of links that should be highlighted in Org files.
1900 This is a list of symbols, each one of them leading to the
1901 highlighting of a certain link type.
1903 You can still open links that are not highlighted.
1905 In principle, it does not hurt to turn on highlighting for all
1906 link types. There may be a small gain when turning off unused
1907 link types. The types are:
1909 bracket The recommended [[link][description]] or [[link]] links with hiding.
1910 angle Links in angular brackets that may contain whitespace like
1911 <bbdb:Carsten Dominik>.
1912 plain Plain links in normal text, no whitespace, like http://google.com.
1913 radio Text that is matched by a radio target, see manual for details.
1914 tag Tag settings in a headline (link to tag search).
1915 date Time stamps (link to calendar).
1916 footnote Footnote labels.
1918 If you set this variable during an Emacs session, use `org-mode-restart'
1919 in the Org buffer so that the change takes effect."
1920 :group 'org-link
1921 :group 'org-appearance
1922 :type '(set :greedy t
1923 (const :tag "Double bracket links" bracket)
1924 (const :tag "Angular bracket links" angle)
1925 (const :tag "Plain text links" plain)
1926 (const :tag "Radio target matches" radio)
1927 (const :tag "Tags" tag)
1928 (const :tag "Timestamps" date)
1929 (const :tag "Footnotes" footnote)))
1931 (defcustom org-make-link-description-function nil
1932 "Function to use for generating link descriptions from links.
1933 When nil, the link location will be used. This function must take
1934 two parameters: the first one is the link, the second one is the
1935 description generated by `org-insert-link'. The function should
1936 return the description to use."
1937 :group 'org-link
1938 :type '(choice (const nil) (function)))
1940 (defgroup org-link-store nil
1941 "Options concerning storing links in Org mode."
1942 :tag "Org Store Link"
1943 :group 'org-link)
1945 (defcustom org-url-hexify-p t
1946 "When non-nil, hexify URL when creating a link."
1947 :type 'boolean
1948 :version "24.3"
1949 :group 'org-link-store)
1951 (defcustom org-email-link-description-format "Email %c: %.30s"
1952 "Format of the description part of a link to an email or usenet message.
1953 The following %-escapes will be replaced by corresponding information:
1955 %F full \"From\" field
1956 %f name, taken from \"From\" field, address if no name
1957 %T full \"To\" field
1958 %t first name in \"To\" field, address if no name
1959 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1960 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1961 %s subject
1962 %d date
1963 %m message-id.
1965 You may use normal field width specification between the % and the letter.
1966 This is for example useful to limit the length of the subject.
1968 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1969 :group 'org-link-store
1970 :type 'string)
1972 (defcustom org-from-is-user-regexp
1973 (let (r1 r2)
1974 (when (and user-mail-address (not (string= user-mail-address "")))
1975 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1976 (when (and user-full-name (not (string= user-full-name "")))
1977 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1978 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1979 "Regexp matched against the \"From:\" header of an email or usenet message.
1980 It should match if the message is from the user him/herself."
1981 :group 'org-link-store
1982 :type 'regexp)
1984 (defcustom org-context-in-file-links t
1985 "Non-nil means file links from `org-store-link' contain context.
1986 A search string will be added to the file name with :: as separator and
1987 used to find the context when the link is activated by the command
1988 `org-open-at-point'. When this option is t, the entire active region
1989 will be placed in the search string of the file link. If set to a
1990 positive integer, only the first n lines of context will be stored.
1992 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links). When this option
2004 is nil, every link which has been inserted once using \\[org-insert-link]
2005 will be removed from the list, to make completing the unused links
2006 more efficient."
2007 :group 'org-link-store
2008 :type 'boolean)
2010 (defgroup org-link-follow nil
2011 "Options concerning following links in Org mode."
2012 :tag "Org Follow Link"
2013 :group 'org-link)
2015 (defcustom org-link-translation-function nil
2016 "Function to translate links with different syntax to Org syntax.
2017 This can be used to translate links created for example by the Planner
2018 or emacs-wiki packages to Org syntax.
2019 The function must accept two parameters, a TYPE containing the link
2020 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2021 which is everything after the link protocol. It should return a cons
2022 with possibly modified values of type and path.
2023 Org contains a function for this, so if you set this variable to
2024 `org-translate-link-from-planner', you should be able follow many
2025 links created by planner."
2026 :group 'org-link-follow
2027 :type '(choice (const nil) (function)))
2029 (defcustom org-follow-link-hook nil
2030 "Hook that is run after a link has been followed."
2031 :group 'org-link-follow
2032 :type 'hook)
2034 (defcustom org-tab-follows-link nil
2035 "Non-nil means on links TAB will follow the link.
2036 Needs to be set before org.el is loaded.
2037 This really should not be used, it does not make sense, and the
2038 implementation is bad."
2039 :group 'org-link-follow
2040 :type 'boolean)
2042 (defcustom org-return-follows-link nil
2043 "Non-nil means on links RET will follow the link.
2044 In tables, the special behavior of RET has precedence."
2045 :group 'org-link-follow
2046 :type 'boolean)
2048 (defcustom org-mouse-1-follows-link
2049 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2050 "Non-nil means mouse-1 on a link will follow the link.
2051 A longer mouse click will still set point. Needs to be set
2052 before org.el is loaded."
2053 :group 'org-link-follow
2054 :version "24.4"
2055 :package-version '(Org . "8.3")
2056 :type '(choice
2057 (const :tag "A double click follows the link" double)
2058 (const :tag "Unconditionally follow the link with mouse-1" t)
2059 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2061 (defcustom org-mark-ring-length 4
2062 "Number of different positions to be recorded in the ring.
2063 Changing this requires a restart of Emacs to work correctly."
2064 :group 'org-link-follow
2065 :type 'integer)
2067 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2068 "Non-nil means internal links in Org files must exactly match a headline.
2069 When nil, the link search tries to match a phrase with all words
2070 in the search text."
2071 :group 'org-link-follow
2072 :version "24.1"
2073 :type '(choice
2074 (const :tag "Use fuzzy text search" nil)
2075 (const :tag "Match only exact headline" t)
2076 (const :tag "Match exact headline or query to create it"
2077 query-to-create)))
2079 (defcustom org-link-frame-setup
2080 '((vm . vm-visit-folder-other-frame)
2081 (vm-imap . vm-visit-imap-folder-other-frame)
2082 (gnus . org-gnus-no-new-news)
2083 (file . find-file-other-window)
2084 (wl . wl-other-frame))
2085 "Setup the frame configuration for following links.
2086 When following a link with Emacs, it may often be useful to display
2087 this link in another window or frame. This variable can be used to
2088 set this up for the different types of links.
2089 For VM, use any of
2090 `vm-visit-folder'
2091 `vm-visit-folder-other-window'
2092 `vm-visit-folder-other-frame'
2093 For Gnus, use any of
2094 `gnus'
2095 `gnus-other-frame'
2096 `org-gnus-no-new-news'
2097 For FILE, use any of
2098 `find-file'
2099 `find-file-other-window'
2100 `find-file-other-frame'
2101 For Wanderlust use any of
2102 `wl'
2103 `wl-other-frame'
2104 For the calendar, use the variable `calendar-setup'.
2105 For BBDB, it is currently only possible to display the matches in
2106 another window."
2107 :group 'org-link-follow
2108 :type '(list
2109 (cons (const vm)
2110 (choice
2111 (const vm-visit-folder)
2112 (const vm-visit-folder-other-window)
2113 (const vm-visit-folder-other-frame)))
2114 (cons (const vm-imap)
2115 (choice
2116 (const vm-visit-imap-folder)
2117 (const vm-visit-imap-folder-other-window)
2118 (const vm-visit-imap-folder-other-frame)))
2119 (cons (const gnus)
2120 (choice
2121 (const gnus)
2122 (const gnus-other-frame)
2123 (const org-gnus-no-new-news)))
2124 (cons (const file)
2125 (choice
2126 (const find-file)
2127 (const find-file-other-window)
2128 (const find-file-other-frame)))
2129 (cons (const wl)
2130 (choice
2131 (const wl)
2132 (const wl-other-frame)))))
2134 (defcustom org-display-internal-link-with-indirect-buffer nil
2135 "Non-nil means use indirect buffer to display infile links.
2136 Activating internal links (from one location in a file to another location
2137 in the same file) normally just jumps to the location. When the link is
2138 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2139 is displayed in
2140 another window. When this option is set, the other window actually displays
2141 an indirect buffer clone of the current buffer, to avoid any visibility
2142 changes to the current buffer."
2143 :group 'org-link-follow
2144 :type 'boolean)
2146 (defcustom org-open-non-existing-files nil
2147 "Non-nil means `org-open-file' will open non-existing files.
2148 When nil, an error will be generated.
2149 This variable applies only to external applications because they
2150 might choke on non-existing files. If the link is to a file that
2151 will be opened in Emacs, the variable is ignored."
2152 :group 'org-link-follow
2153 :type 'boolean)
2155 (defcustom org-open-directory-means-index-dot-org nil
2156 "Non-nil means a link to a directory really means to index.org.
2157 When nil, following a directory link will run dired or open a finder/explorer
2158 window on that directory."
2159 :group 'org-link-follow
2160 :type 'boolean)
2162 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing shell links.
2164 Shell links can be dangerous: just think about a link
2166 [[shell:rm -rf ~/*][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-shell-link-not-regexp ""
2183 "A regexp to skip confirmation for shell links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2189 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2190 Elisp links can be dangerous: just think about a link
2192 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2194 This link would show up in your Org document as \"Google Search\",
2195 but really it would remove your entire home directory.
2196 Therefore we advise against setting this variable to nil.
2197 Just change it to `y-or-n-p' if you want to confirm with a
2198 single keystroke rather than having to type \"yes\"."
2199 :group 'org-link-follow
2200 :type '(choice
2201 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2202 (const :tag "with y-or-n (faster)" y-or-n-p)
2203 (const :tag "no confirmation (dangerous)" nil)))
2204 (put 'org-confirm-shell-link-function
2205 'safe-local-variable
2206 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2208 (defcustom org-confirm-elisp-link-not-regexp ""
2209 "A regexp to skip confirmation for Elisp links."
2210 :group 'org-link-follow
2211 :version "24.1"
2212 :type 'regexp)
2214 (defconst org-file-apps-defaults-gnu
2215 '((remote . emacs)
2216 (system . mailcap)
2217 (t . mailcap))
2218 "Default file applications on a UNIX or GNU/Linux system.
2219 See `org-file-apps'.")
2221 (defconst org-file-apps-defaults-macosx
2222 '((remote . emacs)
2223 (system . "open %s")
2224 ("ps.gz" . "gv %s")
2225 ("eps.gz" . "gv %s")
2226 ("dvi" . "xdvi %s")
2227 ("fig" . "xfig %s")
2228 (t . "open %s"))
2229 "Default file applications on a MacOS X system.
2230 The system \"open\" is known as a default, but we use X11 applications
2231 for some files for which the OS does not have a good default.
2232 See `org-file-apps'.")
2234 (defconst org-file-apps-defaults-windowsnt
2235 (list '(remote . emacs)
2236 (cons 'system (lambda (file _path)
2237 (with-no-warnings (w32-shell-execute "open" file))))
2238 (cons t (lambda (file _path)
2239 (with-no-warnings (w32-shell-execute "open" file)))))
2240 "Default file applications on a Windows NT system.
2241 The system \"open\" is used for most files.
2242 See `org-file-apps'.")
2244 (defcustom org-file-apps
2245 '((auto-mode . emacs)
2246 ("\\.mm\\'" . default)
2247 ("\\.x?html?\\'" . default)
2248 ("\\.pdf\\'" . default))
2249 "External applications for opening `file:path' items in a document.
2250 \\<org-mode-map>\
2252 Org mode uses system defaults for different file types, but
2253 you can use this variable to set the application for a given file
2254 extension. The entries in this list are cons cells where the car identifies
2255 files and the cdr the corresponding command.
2257 Possible values for the file identifier are:
2259 \"string\" A string as a file identifier can be interpreted in different
2260 ways, depending on its contents:
2262 - Alphanumeric characters only:
2263 Match links with this file extension.
2264 Example: (\"pdf\" . \"evince %s\")
2265 to open PDFs with evince.
2267 - Regular expression: Match links where the
2268 filename matches the regexp. If you want to
2269 use groups here, use shy groups.
2271 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2272 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2273 to open *.html and *.xhtml with firefox.
2275 - Regular expression which contains (non-shy) groups:
2276 Match links where the whole link, including \"::\", and
2277 anything after that, matches the regexp.
2278 In a custom command string, %1, %2, etc. are replaced with
2279 the parts of the link that were matched by the groups.
2280 For backwards compatibility, if a command string is given
2281 that does not use any of the group matches, this case is
2282 handled identically to the second one (i.e. match against
2283 file name only).
2284 In a custom function, you can access the group matches with
2285 \(match-string n link).
2287 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2288 \"evince -p %1 %s\")
2289 to open [[file:document.pdf::5]] with evince at page 5.
2291 `directory' Matches a directory
2292 `remote' Matches a remote file, accessible through tramp or efs.
2293 Remote files most likely should be visited through Emacs
2294 because external applications cannot handle such paths.
2295 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2296 so all files Emacs knows how to handle. Using this with
2297 command `emacs' will open most files in Emacs. Beware that this
2298 will also open html files inside Emacs, unless you add
2299 \(\"html\" . default) to the list as well.
2300 `system' The system command to open files, like `open' on Windows
2301 and Mac OS X, and mailcap under GNU/Linux. This is the command
2302 that will be selected if you call \\[org-open-at-point] with a double
2303 \\[universal-argument] \\[universal-argument] prefix.
2304 t Default for files not matched by any of the other options.
2306 Possible values for the command are:
2308 `emacs' The file will be visited by the current Emacs process.
2309 `default' Use the default application for this file type, which is the
2310 association for t in the list, most likely in the system-specific
2311 part. This can be used to overrule an unwanted setting in the
2312 system-specific variable.
2313 `system' Use the system command for opening files, like \"open\".
2314 This command is specified by the entry whose car is `system'.
2315 Most likely, the system-specific version of this variable
2316 does define this command, but you can overrule/replace it
2317 here.
2318 `mailcap' Use command specified in the mailcaps.
2319 string A command to be executed by a shell; %s will be replaced
2320 by the path to the file.
2321 function A Lisp function, which will be called with two arguments:
2322 the file path and the original link string, without the
2323 \"file:\" prefix.
2325 For more examples, see the system specific constants
2326 `org-file-apps-defaults-macosx'
2327 `org-file-apps-defaults-windowsnt'
2328 `org-file-apps-defaults-gnu'."
2329 :group 'org-link-follow
2330 :type '(repeat
2331 (cons (choice :value ""
2332 (string :tag "Extension")
2333 (const :tag "System command to open files" system)
2334 (const :tag "Default for unrecognized files" t)
2335 (const :tag "Remote file" remote)
2336 (const :tag "Links to a directory" directory)
2337 (const :tag "Any files that have Emacs modes"
2338 auto-mode))
2339 (choice :value ""
2340 (const :tag "Visit with Emacs" emacs)
2341 (const :tag "Use default" default)
2342 (const :tag "Use the system command" system)
2343 (string :tag "Command")
2344 (function :tag "Function")))))
2346 (defcustom org-doi-server-url "http://dx.doi.org/"
2347 "The URL of the DOI server."
2348 :type 'string
2349 :version "24.3"
2350 :group 'org-link-follow)
2352 (defgroup org-refile nil
2353 "Options concerning refiling entries in Org mode."
2354 :tag "Org Refile"
2355 :group 'org)
2357 (defcustom org-directory "~/org"
2358 "Directory with Org files.
2359 This is just a default location to look for Org files. There is no need
2360 at all to put your files into this directory. It is used in the
2361 following situations:
2363 1. When a capture template specifies a target file that is not an
2364 absolute path. The path will then be interpreted relative to
2365 `org-directory'
2366 2. When the value of variable `org-agenda-files' is a single file, any
2367 relative paths in this file will be taken as relative to
2368 `org-directory'."
2369 :group 'org-refile
2370 :group 'org-capture
2371 :type 'directory)
2373 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2374 "Default target for storing notes.
2375 Used as a fall back file for org-capture.el, for templates that
2376 do not specify a target file."
2377 :group 'org-refile
2378 :group 'org-capture
2379 :type 'file)
2381 (defcustom org-goto-interface 'outline
2382 "The default interface to be used for `org-goto'.
2383 Allowed values are:
2384 outline The interface shows an outline of the relevant file
2385 and the correct heading is found by moving through
2386 the outline or by searching with incremental search.
2387 outline-path-completion Headlines in the current buffer are offered via
2388 completion. This is the interface also used by
2389 the refile command."
2390 :group 'org-refile
2391 :type '(choice
2392 (const :tag "Outline" outline)
2393 (const :tag "Outline-path-completion" outline-path-completion)))
2395 (defcustom org-goto-max-level 5
2396 "Maximum target level when running `org-goto' with refile interface."
2397 :group 'org-refile
2398 :type 'integer)
2400 (defcustom org-reverse-note-order nil
2401 "Non-nil means store new notes at the beginning of a file or entry.
2402 When nil, new notes will be filed to the end of a file or entry.
2403 This can also be a list with cons cells of regular expressions that
2404 are matched against file names, and values."
2405 :group 'org-capture
2406 :group 'org-refile
2407 :type '(choice
2408 (const :tag "Reverse always" t)
2409 (const :tag "Reverse never" nil)
2410 (repeat :tag "By file name regexp"
2411 (cons regexp boolean))))
2413 (defcustom org-log-refile nil
2414 "Information to record when a task is refiled.
2416 Possible values are:
2418 nil Don't add anything
2419 time Add a time stamp to the task
2420 note Prompt for a note and add it with template `org-log-note-headings'
2422 This option can also be set with on a per-file-basis with
2424 #+STARTUP: nologrefile
2425 #+STARTUP: logrefile
2426 #+STARTUP: lognoterefile
2428 You can have local logging settings for a subtree by setting the LOGGING
2429 property to one or more of these keywords.
2431 When bulk-refiling from the agenda, the value `note' is forbidden and
2432 will temporarily be changed to `time'."
2433 :group 'org-refile
2434 :group 'org-progress
2435 :version "24.1"
2436 :type '(choice
2437 (const :tag "No logging" nil)
2438 (const :tag "Record timestamp" time)
2439 (const :tag "Record timestamp with note." note)))
2441 (defcustom org-refile-targets nil
2442 "Targets for refiling entries with \\[org-refile].
2443 This is a list of cons cells. Each cell contains:
2444 - a specification of the files to be considered, either a list of files,
2445 or a symbol whose function or variable value will be used to retrieve
2446 a file name or a list of file names. If you use `org-agenda-files' for
2447 that, all agenda files will be scanned for targets. Nil means consider
2448 headings in the current buffer.
2449 - A specification of how to find candidate refile targets. This may be
2450 any of:
2451 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2452 This tag has to be present in all target headlines, inheritance will
2453 not be considered.
2454 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2455 todo keyword.
2456 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2457 headlines that are refiling targets.
2458 - a cons cell (:level . N). Any headline of level N is considered a target.
2459 Note that, when `org-odd-levels-only' is set, level corresponds to
2460 order in hierarchy, not to the number of stars.
2461 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2462 Note that, when `org-odd-levels-only' is set, level corresponds to
2463 order in hierarchy, not to the number of stars.
2465 Each element of this list generates a set of possible targets.
2466 The union of these sets is presented (with completion) to
2467 the user by `org-refile'.
2469 You can set the variable `org-refile-target-verify-function' to a function
2470 to verify each headline found by the simple criteria above.
2472 When this variable is nil, all top-level headlines in the current buffer
2473 are used, equivalent to the value `((nil . (:level . 1))'."
2474 :group 'org-refile
2475 :type '(repeat
2476 (cons
2477 (choice :value org-agenda-files
2478 (const :tag "All agenda files" org-agenda-files)
2479 (const :tag "Current buffer" nil)
2480 (function) (variable) (file))
2481 (choice :tag "Identify target headline by"
2482 (cons :tag "Specific tag" (const :value :tag) (string))
2483 (cons :tag "TODO keyword" (const :value :todo) (string))
2484 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2485 (cons :tag "Level number" (const :value :level) (integer))
2486 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2488 (defcustom org-refile-target-verify-function nil
2489 "Function to verify if the headline at point should be a refile target.
2490 The function will be called without arguments, with point at the
2491 beginning of the headline. It should return t and leave point
2492 where it is if the headline is a valid target for refiling.
2494 If the target should not be selected, the function must return nil.
2495 In addition to this, it may move point to a place from where the search
2496 should be continued. For example, the function may decide that the entire
2497 subtree of the current entry should be excluded and move point to the end
2498 of the subtree."
2499 :group 'org-refile
2500 :type '(choice
2501 (const nil)
2502 (function)))
2504 (defcustom org-refile-use-cache nil
2505 "Non-nil means cache refile targets to speed up the process.
2506 \\<org-mode-map>\
2507 The cache for a particular file will be updated automatically when
2508 the buffer has been killed, or when any of the marker used for flagging
2509 refile targets no longer points at a live buffer.
2510 If you have added new entries to a buffer that might themselves be targets,
2511 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2512 if you find that easier, \
2513 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2514 \\[org-refile]'."
2515 :group 'org-refile
2516 :version "24.1"
2517 :type 'boolean)
2519 (defcustom org-refile-use-outline-path nil
2520 "Non-nil means provide refile targets as paths.
2521 So a level 3 headline will be available as level1/level2/level3.
2523 When the value is `file', also include the file name (without directory)
2524 into the path. In this case, you can also stop the completion after
2525 the file name, to get entries inserted as top level in the file.
2527 When `full-file-path', include the full file path."
2528 :group 'org-refile
2529 :type '(choice
2530 (const :tag "Not" nil)
2531 (const :tag "Yes" t)
2532 (const :tag "Start with file name" file)
2533 (const :tag "Start with full file path" full-file-path)))
2535 (defcustom org-outline-path-complete-in-steps t
2536 "Non-nil means complete the outline path in hierarchical steps.
2537 When Org uses the refile interface to select an outline path (see
2538 `org-refile-use-outline-path'), the completion of the path can be
2539 done in a single go, or it can be done in steps down the headline
2540 hierarchy. Going in steps is probably the best if you do not use
2541 a special completion package like `ido' or `icicles'. However,
2542 when using these packages, going in one step can be very fast,
2543 while still showing the whole path to the entry."
2544 :group 'org-refile
2545 :type 'boolean)
2547 (defcustom org-refile-allow-creating-parent-nodes nil
2548 "Non-nil means allow the creation of new nodes as refile targets.
2549 New nodes are then created by adding \"/new node name\" to the completion
2550 of an existing node. When the value of this variable is `confirm',
2551 new node creation must be confirmed by the user (recommended).
2552 When nil, the completion must match an existing entry.
2554 Note that, if the new heading is not seen by the criteria
2555 listed in `org-refile-targets', multiple instances of the same
2556 heading would be created by trying again to file under the new
2557 heading."
2558 :group 'org-refile
2559 :type '(choice
2560 (const :tag "Never" nil)
2561 (const :tag "Always" t)
2562 (const :tag "Prompt for confirmation" confirm)))
2564 (defcustom org-refile-active-region-within-subtree nil
2565 "Non-nil means also refile active region within a subtree.
2567 By default `org-refile' doesn't allow refiling regions if they
2568 don't contain a set of subtrees, but it might be convenient to
2569 do so sometimes: in that case, the first line of the region is
2570 converted to a headline before refiling."
2571 :group 'org-refile
2572 :version "24.1"
2573 :type 'boolean)
2575 (defgroup org-todo nil
2576 "Options concerning TODO items in Org mode."
2577 :tag "Org TODO"
2578 :group 'org)
2580 (defgroup org-progress nil
2581 "Options concerning Progress logging in Org mode."
2582 :tag "Org Progress"
2583 :group 'org-time)
2585 (defvar org-todo-interpretation-widgets
2586 '((:tag "Sequence (cycling hits every state)" sequence)
2587 (:tag "Type (cycling directly to DONE)" type))
2588 "The available interpretation symbols for customizing `org-todo-keywords'.
2589 Interested libraries should add to this list.")
2591 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2592 "List of TODO entry keyword sequences and their interpretation.
2593 \\<org-mode-map>This is a list of sequences.
2595 Each sequence starts with a symbol, either `sequence' or `type',
2596 indicating if the keywords should be interpreted as a sequence of
2597 action steps, or as different types of TODO items. The first
2598 keywords are states requiring action - these states will select a headline
2599 for inclusion into the global TODO list Org produces. If one of the
2600 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2601 signify that no further action is necessary. If \"|\" is not found,
2602 the last keyword is treated as the only DONE state of the sequence.
2604 The command \\[org-todo] cycles an entry through these states, and one
2605 additional state where no keyword is present. For details about this
2606 cycling, see the manual.
2608 TODO keywords and interpretation can also be set on a per-file basis with
2609 the special #+SEQ_TODO and #+TYP_TODO lines.
2611 Each keyword can optionally specify a character for fast state selection
2612 \(in combination with the variable `org-use-fast-todo-selection')
2613 and specifiers for state change logging, using the same syntax that
2614 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2615 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2616 indicates to record a time stamp each time this state is selected.
2618 Each keyword may also specify if a timestamp or a note should be
2619 recorded when entering or leaving the state, by adding additional
2620 characters in the parenthesis after the keyword. This looks like this:
2621 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2622 record only the time of the state change. With X and Y being either
2623 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2624 Y when leaving the state if and only if the *target* state does not
2625 define X. You may omit any of the fast-selection key or X or /Y,
2626 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2628 For backward compatibility, this variable may also be just a list
2629 of keywords. In this case the interpretation (sequence or type) will be
2630 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2631 :group 'org-todo
2632 :group 'org-keywords
2633 :type '(choice
2634 (repeat :tag "Old syntax, just keywords"
2635 (string :tag "Keyword"))
2636 (repeat :tag "New syntax"
2637 (cons
2638 (choice
2639 :tag "Interpretation"
2640 ;;Quick and dirty way to see
2641 ;;`org-todo-interpretations'. This takes the
2642 ;;place of item arguments
2643 :convert-widget
2644 (lambda (widget)
2645 (widget-put widget
2646 :args (mapcar
2647 (lambda (x)
2648 (widget-convert
2649 (cons 'const x)))
2650 org-todo-interpretation-widgets))
2651 widget))
2652 (repeat
2653 (string :tag "Keyword"))))))
2655 (defvar-local org-todo-keywords-1 nil
2656 "All TODO and DONE keywords active in a buffer.")
2657 (defvar org-todo-keywords-for-agenda nil)
2658 (defvar org-done-keywords-for-agenda nil)
2659 (defvar org-todo-keyword-alist-for-agenda nil)
2660 (defvar org-tag-alist-for-agenda nil
2661 "Alist of all tags from all agenda files.")
2662 (defvar org-tag-groups-alist-for-agenda nil
2663 "Alist of all groups tags from all current agenda files.")
2664 (defvar-local org-tag-groups-alist nil)
2665 (defvar org-agenda-contributing-files nil)
2666 (defvar-local org-current-tag-alist nil
2667 "Alist of all tag groups in current buffer.
2668 This variable takes into consideration `org-tag-alist',
2669 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2670 (defvar-local org-not-done-keywords nil)
2671 (defvar-local org-done-keywords nil)
2672 (defvar-local org-todo-heads nil)
2673 (defvar-local org-todo-sets nil)
2674 (defvar-local org-todo-log-states nil)
2675 (defvar-local org-todo-kwd-alist nil)
2676 (defvar-local org-todo-key-alist nil)
2677 (defvar-local org-todo-key-trigger nil)
2679 (defcustom org-todo-interpretation 'sequence
2680 "Controls how TODO keywords are interpreted.
2681 This variable is in principle obsolete and is only used for
2682 backward compatibility, if the interpretation of todo keywords is
2683 not given already in `org-todo-keywords'. See that variable for
2684 more information."
2685 :group 'org-todo
2686 :group 'org-keywords
2687 :type '(choice (const sequence)
2688 (const type)))
2690 (defcustom org-use-fast-todo-selection t
2691 "\\<org-mode-map>\
2692 Non-nil means use the fast todo selection scheme with \\[org-todo].
2693 This variable describes if and under what circumstances the cycling
2694 mechanism for TODO keywords will be replaced by a single-key, direct
2695 selection scheme.
2697 When nil, fast selection is never used.
2699 When the symbol `prefix', it will be used when `org-todo' is called
2700 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2701 in an Org buffer, and
2702 `\\[universal-argument] t' in an agenda buffer.
2704 When t, fast selection is used by default. In this case, the prefix
2705 argument forces cycling instead.
2707 In all cases, the special interface is only used if access keys have
2708 actually been assigned by the user, i.e. if keywords in the configuration
2709 are followed by a letter in parenthesis, like TODO(t)."
2710 :group 'org-todo
2711 :type '(choice
2712 (const :tag "Never" nil)
2713 (const :tag "By default" t)
2714 (const :tag "Only with C-u C-c C-t" prefix)))
2716 (defcustom org-provide-todo-statistics t
2717 "Non-nil means update todo statistics after insert and toggle.
2718 ALL-HEADLINES means update todo statistics by including headlines
2719 with no TODO keyword as well, counting them as not done.
2720 A list of TODO keywords means the same, but skip keywords that are
2721 not in this list.
2722 When set to a list of two lists, the first list contains keywords
2723 to consider as TODO keywords, the second list contains keywords
2724 to consider as DONE keywords.
2726 When this is set, todo statistics is updated in the parent of the
2727 current entry each time a todo state is changed."
2728 :group 'org-todo
2729 :type '(choice
2730 (const :tag "Yes, only for TODO entries" t)
2731 (const :tag "Yes, including all entries" all-headlines)
2732 (repeat :tag "Yes, for TODOs in this list"
2733 (string :tag "TODO keyword"))
2734 (list :tag "Yes, for TODOs and DONEs in these lists"
2735 (repeat (string :tag "TODO keyword"))
2736 (repeat (string :tag "DONE keyword")))
2737 (other :tag "No TODO statistics" nil)))
2739 (defcustom org-hierarchical-todo-statistics t
2740 "Non-nil means TODO statistics covers just direct children.
2741 When nil, all entries in the subtree are considered.
2742 This has only an effect if `org-provide-todo-statistics' is set.
2743 To set this to nil for only a single subtree, use a COOKIE_DATA
2744 property and include the word \"recursive\" into the value."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-after-todo-state-change-hook nil
2749 "Hook which is run after the state of a TODO item was changed.
2750 The new state (a string with a TODO keyword, or nil) is available in the
2751 Lisp variable `org-state'."
2752 :group 'org-todo
2753 :type 'hook)
2755 (defvar org-blocker-hook nil
2756 "Hook for functions that are allowed to block a state change.
2758 Functions in this hook should not modify the buffer.
2759 Each function gets as its single argument a property list,
2760 see `org-trigger-hook' for more information about this list.
2762 If any of the functions in this hook returns nil, the state change
2763 is blocked.")
2765 (defvar org-trigger-hook nil
2766 "Hook for functions that are triggered by a state change.
2768 Each function gets as its single argument a property list with at
2769 least the following elements:
2771 (:type type-of-change :position pos-at-entry-start
2772 :from old-state :to new-state)
2774 Depending on the type, more properties may be present.
2776 This mechanism is currently implemented for:
2778 TODO state changes
2779 ------------------
2780 :type todo-state-change
2781 :from previous state (keyword as a string), or nil, or a symbol
2782 `todo' or `done', to indicate the general type of state.
2783 :to new state, like in :from")
2785 (defcustom org-enforce-todo-dependencies nil
2786 "Non-nil means undone TODO entries will block switching the parent to DONE.
2787 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2788 be blocked if any prior sibling is not yet done.
2789 Finally, if the parent is blocked because of ordered siblings of its own,
2790 the child will also be blocked."
2791 :set (lambda (var val)
2792 (set var val)
2793 (if val
2794 (add-hook 'org-blocker-hook
2795 'org-block-todo-from-children-or-siblings-or-parent)
2796 (remove-hook 'org-blocker-hook
2797 'org-block-todo-from-children-or-siblings-or-parent)))
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-enforce-todo-checkbox-dependencies nil
2802 "Non-nil means unchecked boxes will block switching the parent to DONE.
2803 When this is nil, checkboxes have no influence on switching TODO states.
2804 When non-nil, you first need to check off all check boxes before the TODO
2805 entry can be switched to DONE.
2806 This variable needs to be set before org.el is loaded, and you need to
2807 restart Emacs after a change to make the change effective. The only way
2808 to change is while Emacs is running is through the customize interface."
2809 :set (lambda (var val)
2810 (set var val)
2811 (if val
2812 (add-hook 'org-blocker-hook
2813 'org-block-todo-from-checkboxes)
2814 (remove-hook 'org-blocker-hook
2815 'org-block-todo-from-checkboxes)))
2816 :group 'org-todo
2817 :type 'boolean)
2819 (defcustom org-treat-insert-todo-heading-as-state-change nil
2820 "Non-nil means inserting a TODO heading is treated as state change.
2821 So when the command \\[org-insert-todo-heading] is used, state change
2822 logging will apply if appropriate. When nil, the new TODO item will
2823 be inserted directly, and no logging will take place."
2824 :group 'org-todo
2825 :type 'boolean)
2827 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2828 "Non-nil means switching TODO states with S-cursor counts as state change.
2829 This is the default behavior. However, setting this to nil allows a
2830 convenient way to select a TODO state and bypass any logging associated
2831 with that."
2832 :group 'org-todo
2833 :type 'boolean)
2835 (defcustom org-todo-state-tags-triggers nil
2836 "Tag changes that should be triggered by TODO state changes.
2837 This is a list. Each entry is
2839 (state-change (tag . flag) .......)
2841 State-change can be a string with a state, and empty string to indicate the
2842 state that has no TODO keyword, or it can be one of the symbols `todo'
2843 or `done', meaning any not-done or done state, respectively."
2844 :group 'org-todo
2845 :group 'org-tags
2846 :type '(repeat
2847 (cons (choice :tag "When changing to"
2848 (const :tag "Not-done state" todo)
2849 (const :tag "Done state" done)
2850 (string :tag "State"))
2851 (repeat
2852 (cons :tag "Tag action"
2853 (string :tag "Tag")
2854 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2856 (defcustom org-log-done nil
2857 "Information to record when a task moves to the DONE state.
2859 Possible values are:
2861 nil Don't add anything, just change the keyword
2862 time Add a time stamp to the task
2863 note Prompt for a note and add it with template `org-log-note-headings'
2865 This option can also be set with on a per-file-basis with
2867 #+STARTUP: nologdone
2868 #+STARTUP: logdone
2869 #+STARTUP: lognotedone
2871 You can have local logging settings for a subtree by setting the LOGGING
2872 property to one or more of these keywords."
2873 :group 'org-todo
2874 :group 'org-progress
2875 :type '(choice
2876 (const :tag "No logging" nil)
2877 (const :tag "Record CLOSED timestamp" time)
2878 (const :tag "Record CLOSED timestamp with note." note)))
2880 ;; Normalize old uses of org-log-done.
2881 (cond
2882 ((eq org-log-done t) (setq org-log-done 'time))
2883 ((and (listp org-log-done) (memq 'done org-log-done))
2884 (setq org-log-done 'note)))
2886 (defcustom org-log-reschedule nil
2887 "Information to record when the scheduling date of a tasks is modified.
2889 Possible values are:
2891 nil Don't add anything, just change the date
2892 time Add a time stamp to the task
2893 note Prompt for a note and add it with template `org-log-note-headings'
2895 This option can also be set with on a per-file-basis with
2897 #+STARTUP: nologreschedule
2898 #+STARTUP: logreschedule
2899 #+STARTUP: lognotereschedule"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type '(choice
2903 (const :tag "No logging" nil)
2904 (const :tag "Record timestamp" time)
2905 (const :tag "Record timestamp with note." note)))
2907 (defcustom org-log-redeadline nil
2908 "Information to record when the deadline date of a tasks is modified.
2910 Possible values are:
2912 nil Don't add anything, just change the date
2913 time Add a time stamp to the task
2914 note Prompt for a note and add it with template `org-log-note-headings'
2916 This option can also be set with on a per-file-basis with
2918 #+STARTUP: nologredeadline
2919 #+STARTUP: logredeadline
2920 #+STARTUP: lognoteredeadline
2922 You can have local logging settings for a subtree by setting the LOGGING
2923 property to one or more of these keywords."
2924 :group 'org-todo
2925 :group 'org-progress
2926 :type '(choice
2927 (const :tag "No logging" nil)
2928 (const :tag "Record timestamp" time)
2929 (const :tag "Record timestamp with note." note)))
2931 (defcustom org-log-note-clock-out nil
2932 "Non-nil means record a note when clocking out of an item.
2933 This can also be configured on a per-file basis by adding one of
2934 the following lines anywhere in the buffer:
2936 #+STARTUP: lognoteclock-out
2937 #+STARTUP: nolognoteclock-out"
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type 'boolean)
2942 (defcustom org-log-done-with-time t
2943 "Non-nil means the CLOSED time stamp will contain date and time.
2944 When nil, only the date will be recorded."
2945 :group 'org-progress
2946 :type 'boolean)
2948 (defcustom org-log-note-headings
2949 '((done . "CLOSING NOTE %t")
2950 (state . "State %-12s from %-12S %t")
2951 (note . "Note taken on %t")
2952 (reschedule . "Rescheduled from %S on %t")
2953 (delschedule . "Not scheduled, was %S on %t")
2954 (redeadline . "New deadline from %S on %t")
2955 (deldeadline . "Removed deadline, was %S on %t")
2956 (refile . "Refiled on %t")
2957 (clock-out . ""))
2958 "Headings for notes added to entries.
2960 The value is an alist, with the car being a symbol indicating the
2961 note context, and the cdr is the heading to be used. The heading
2962 may also be the empty string. The following placeholders can be
2963 used:
2965 %t a time stamp.
2966 %T an active time stamp instead the default inactive one
2967 %d a short-format time stamp.
2968 %D an active short-format time stamp.
2969 %s the new TODO state or time stamp (inactive), in double quotes.
2970 %S the old TODO state or time stamp (inactive), in double quotes.
2971 %u the user name.
2972 %U full user name.
2974 In fact, it is not a good idea to change the `state' entry,
2975 because Agenda Log mode depends on the format of these entries."
2976 :group 'org-todo
2977 :group 'org-progress
2978 :type '(list :greedy t
2979 (cons (const :tag "Heading when closing an item" done) string)
2980 (cons (const :tag
2981 "Heading when changing todo state (todo sequence only)"
2982 state) string)
2983 (cons (const :tag "Heading when just taking a note" note) string)
2984 (cons (const :tag "Heading when rescheduling" reschedule) string)
2985 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2986 (cons (const :tag "Heading when changing deadline" redeadline) string)
2987 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2988 (cons (const :tag "Heading when refiling" refile) string)
2989 (cons (const :tag "Heading when clocking out" clock-out) string)))
2991 (unless (assq 'note org-log-note-headings)
2992 (push '(note . "%t") org-log-note-headings))
2994 (defcustom org-log-into-drawer nil
2995 "Non-nil means insert state change notes and time stamps into a drawer.
2996 When nil, state changes notes will be inserted after the headline and
2997 any scheduling and clock lines, but not inside a drawer.
2999 The value of this variable should be the name of the drawer to use.
3000 LOGBOOK is proposed as the default drawer for this purpose, you can
3001 also set this to a string to define the drawer of your choice.
3003 A value of t is also allowed, representing \"LOGBOOK\".
3005 A value of t or nil can also be set with on a per-file-basis with
3007 #+STARTUP: logdrawer
3008 #+STARTUP: nologdrawer
3010 If this variable is set, `org-log-state-notes-insert-after-drawers'
3011 will be ignored.
3013 You can set the property LOG_INTO_DRAWER to overrule this setting for
3014 a subtree.
3016 Do not check directly this variable in a Lisp program. Call
3017 function `org-log-into-drawer' instead."
3018 :group 'org-todo
3019 :group 'org-progress
3020 :type '(choice
3021 (const :tag "Not into a drawer" nil)
3022 (const :tag "LOGBOOK" t)
3023 (string :tag "Other")))
3025 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3027 (defun org-log-into-drawer ()
3028 "Name of the log drawer, as a string, or nil.
3029 This is the value of `org-log-into-drawer'. However, if the
3030 current entry has or inherits a LOG_INTO_DRAWER property, it will
3031 be used instead of the default value."
3032 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3033 (cond ((equal p "nil") nil)
3034 ((equal p "t") "LOGBOOK")
3035 ((stringp p) p)
3036 (p "LOGBOOK")
3037 ((stringp org-log-into-drawer) org-log-into-drawer)
3038 (org-log-into-drawer "LOGBOOK"))))
3040 (defcustom org-log-state-notes-insert-after-drawers nil
3041 "Non-nil means insert state change notes after any drawers in entry.
3042 Only the drawers that *immediately* follow the headline and the
3043 deadline/scheduled line are skipped.
3044 When nil, insert notes right after the heading and perhaps the line
3045 with deadline/scheduling if present.
3047 This variable will have no effect if `org-log-into-drawer' is
3048 set."
3049 :group 'org-todo
3050 :group 'org-progress
3051 :type 'boolean)
3053 (defcustom org-log-states-order-reversed t
3054 "Non-nil means the latest state note will be directly after heading.
3055 When nil, the state change notes will be ordered according to time.
3057 This option can also be set with on a per-file-basis with
3059 #+STARTUP: logstatesreversed
3060 #+STARTUP: nologstatesreversed"
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-todo-repeat-to-state nil
3066 "The TODO state to which a repeater should return the repeating task.
3067 By default this is the first task in a TODO sequence, or the previous state
3068 in a TODO_TYP set. But you can specify another task here.
3069 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3070 :group 'org-todo
3071 :version "24.1"
3072 :type '(choice (const :tag "Head of sequence" nil)
3073 (string :tag "Specific state")))
3075 (defcustom org-log-repeat 'time
3076 "Non-nil means record moving through the DONE state when triggering repeat.
3077 An auto-repeating task is immediately switched back to TODO when
3078 marked DONE. If you are not logging state changes (by adding \"@\"
3079 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3080 record a closing note, there will be no record of the task moving
3081 through DONE. This variable forces taking a note anyway.
3083 nil Don't force a record
3084 time Record a time stamp
3085 note Prompt for a note and add it with template `org-log-note-headings'
3087 This option can also be set with on a per-file-basis with
3089 #+STARTUP: nologrepeat
3090 #+STARTUP: logrepeat
3091 #+STARTUP: lognoterepeat
3093 You can have local logging settings for a subtree by setting the LOGGING
3094 property to one or more of these keywords."
3095 :group 'org-todo
3096 :group 'org-progress
3097 :type '(choice
3098 (const :tag "Don't force a record" nil)
3099 (const :tag "Force recording the DONE state" time)
3100 (const :tag "Force recording a note with the DONE state" note)))
3103 (defgroup org-priorities nil
3104 "Priorities in Org mode."
3105 :tag "Org Priorities"
3106 :group 'org-todo)
3108 (defcustom org-enable-priority-commands t
3109 "Non-nil means priority commands are active.
3110 When nil, these commands will be disabled, so that you never accidentally
3111 set a priority."
3112 :group 'org-priorities
3113 :type 'boolean)
3115 (defcustom org-highest-priority ?A
3116 "The highest priority of TODO items. A character like ?A, ?B etc.
3117 Must have a smaller ASCII number than `org-lowest-priority'."
3118 :group 'org-priorities
3119 :type 'character)
3121 (defcustom org-lowest-priority ?C
3122 "The lowest priority of TODO items. A character like ?A, ?B etc.
3123 Must have a larger ASCII number than `org-highest-priority'."
3124 :group 'org-priorities
3125 :type 'character)
3127 (defcustom org-default-priority ?B
3128 "The default priority of TODO items.
3129 This is the priority an item gets if no explicit priority is given.
3130 When starting to cycle on an empty priority the first step in the cycle
3131 depends on `org-priority-start-cycle-with-default'. The resulting first
3132 step priority must not exceed the range from `org-highest-priority' to
3133 `org-lowest-priority' which means that `org-default-priority' has to be
3134 in this range exclusive or inclusive the range boundaries. Else the
3135 first step refuses to set the default and the second will fall back
3136 to (depending on the command used) the highest or lowest priority."
3137 :group 'org-priorities
3138 :type 'character)
3140 (defcustom org-priority-start-cycle-with-default t
3141 "Non-nil means start with default priority when starting to cycle.
3142 When this is nil, the first step in the cycle will be (depending on the
3143 command used) one higher or lower than the default priority.
3144 See also `org-default-priority'."
3145 :group 'org-priorities
3146 :type 'boolean)
3148 (defcustom org-get-priority-function nil
3149 "Function to extract the priority from a string.
3150 The string is normally the headline. If this is nil Org computes the
3151 priority from the priority cookie like [#A] in the headline. It returns
3152 an integer, increasing by 1000 for each priority level.
3153 The user can set a different function here, which should take a string
3154 as an argument and return the numeric priority."
3155 :group 'org-priorities
3156 :version "24.1"
3157 :type '(choice
3158 (const nil)
3159 (function)))
3161 (defgroup org-time nil
3162 "Options concerning time stamps and deadlines in Org mode."
3163 :tag "Org Time"
3164 :group 'org)
3166 (defcustom org-time-stamp-rounding-minutes '(0 5)
3167 "Number of minutes to round time stamps to.
3168 \\<org-mode-map>\
3169 These are two values, the first applies when first creating a time stamp.
3170 The second applies when changing it with the commands `S-up' and `S-down'.
3171 When changing the time stamp, this means that it will change in steps
3172 of N minutes, as given by the second value.
3174 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3175 numbers should be factors of 60, so for example 5, 10, 15.
3177 When this is larger than 1, you can still force an exact time stamp by using
3178 a double prefix argument to a time stamp command like \
3179 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3180 and by using a prefix arg to `S-up/down' to specify the exact number
3181 of minutes to shift."
3182 :group 'org-time
3183 :get (lambda (var) ; Make sure both elements are there
3184 (if (integerp (default-value var))
3185 (list (default-value var) 5)
3186 (default-value var)))
3187 :type '(list
3188 (integer :tag "when inserting times")
3189 (integer :tag "when modifying times")))
3191 ;; Normalize old customizations of this variable.
3192 (when (integerp org-time-stamp-rounding-minutes)
3193 (setq org-time-stamp-rounding-minutes
3194 (list org-time-stamp-rounding-minutes
3195 org-time-stamp-rounding-minutes)))
3197 (defcustom org-display-custom-times nil
3198 "Non-nil means overlay custom formats over all time stamps.
3199 The formats are defined through the variable `org-time-stamp-custom-formats'.
3200 To turn this on on a per-file basis, insert anywhere in the file:
3201 #+STARTUP: customtime"
3202 :group 'org-time
3203 :set 'set-default
3204 :type 'sexp)
3205 (make-variable-buffer-local 'org-display-custom-times)
3207 (defcustom org-time-stamp-custom-formats
3208 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3209 "Custom formats for time stamps. See `format-time-string' for the syntax.
3210 These are overlaid over the default ISO format if the variable
3211 `org-display-custom-times' is set. Time like %H:%M should be at the
3212 end of the second format. The custom formats are also honored by export
3213 commands, if custom time display is turned on at the time of export."
3214 :group 'org-time
3215 :type 'sexp)
3217 (defun org-time-stamp-format (&optional long inactive)
3218 "Get the right format for a time string."
3219 (let ((f (if long (cdr org-time-stamp-formats)
3220 (car org-time-stamp-formats))))
3221 (if inactive
3222 (concat "[" (substring f 1 -1) "]")
3223 f)))
3225 (defcustom org-time-clocksum-format
3226 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3227 "The format string used when creating CLOCKSUM lines.
3228 This is also used when Org mode generates a time duration.
3230 The value can be a single format string containing two
3231 %-sequences, which will be filled with the number of hours and
3232 minutes in that order.
3234 Alternatively, the value can be a plist associating any of the
3235 keys :years, :months, :weeks, :days, :hours or :minutes with
3236 format strings. The time duration is formatted using only the
3237 time components that are needed and concatenating the results.
3238 If a time unit in absent, it falls back to the next smallest
3239 unit.
3241 The keys :require-years, :require-months, :require-days,
3242 :require-weeks, :require-hours, :require-minutes are also
3243 meaningful. A non-nil value for these keys indicates that the
3244 corresponding time component should always be included, even if
3245 its value is 0.
3248 For example,
3250 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3251 :require-minutes t)
3253 means durations longer than a day will be expressed in days,
3254 hours and minutes, and durations less than a day will always be
3255 expressed in hours and minutes (even for durations less than an
3256 hour).
3258 The value
3260 (:days \"%dd\" :minutes \"%dm\")
3262 means durations longer than a day will be expressed in days and
3263 minutes, and durations less than a day will be expressed entirely
3264 in minutes (even for durations longer than an hour)."
3265 :group 'org-time
3266 :group 'org-clock
3267 :version "24.4"
3268 :package-version '(Org . "8.0")
3269 :type '(choice (string :tag "Format string")
3270 (set :tag "Plist"
3271 (group :inline t (const :tag "Years" :years)
3272 (string :tag "Format string"))
3273 (group :inline t
3274 (const :tag "Always show years" :require-years)
3275 (const t))
3276 (group :inline t (const :tag "Months" :months)
3277 (string :tag "Format string"))
3278 (group :inline t
3279 (const :tag "Always show months" :require-months)
3280 (const t))
3281 (group :inline t (const :tag "Weeks" :weeks)
3282 (string :tag "Format string"))
3283 (group :inline t
3284 (const :tag "Always show weeks" :require-weeks)
3285 (const t))
3286 (group :inline t (const :tag "Days" :days)
3287 (string :tag "Format string"))
3288 (group :inline t
3289 (const :tag "Always show days" :require-days)
3290 (const t))
3291 (group :inline t (const :tag "Hours" :hours)
3292 (string :tag "Format string"))
3293 (group :inline t
3294 (const :tag "Always show hours" :require-hours)
3295 (const t))
3296 (group :inline t (const :tag "Minutes" :minutes)
3297 (string :tag "Format string"))
3298 (group :inline t
3299 (const :tag "Always show minutes" :require-minutes)
3300 (const t)))))
3302 (defcustom org-time-clocksum-use-fractional nil
3303 "When non-nil, \\[org-clock-display] uses fractional times.
3304 See `org-time-clocksum-format' for more on time clock formats."
3305 :group 'org-time
3306 :group 'org-clock
3307 :version "24.3"
3308 :type 'boolean)
3310 (defcustom org-time-clocksum-use-effort-durations nil
3311 "When non-nil, \\[org-clock-display] uses effort durations.
3312 E.g. by default, one day is considered to be a 8 hours effort,
3313 so a task that has been clocked for 16 hours will be displayed
3314 as during 2 days in the clock display or in the clocktable.
3316 See `org-effort-durations' on how to set effort durations
3317 and `org-time-clocksum-format' for more on time clock formats."
3318 :group 'org-time
3319 :group 'org-clock
3320 :version "24.4"
3321 :package-version '(Org . "8.0")
3322 :type 'boolean)
3324 (defcustom org-time-clocksum-fractional-format "%.2f"
3325 "The format string used when creating CLOCKSUM lines,
3326 or when Org mode generates a time duration, if
3327 `org-time-clocksum-use-fractional' is enabled.
3329 The value can be a single format string containing one
3330 %-sequence, which will be filled with the number of hours as
3331 a float.
3333 Alternatively, the value can be a plist associating any of the
3334 keys :years, :months, :weeks, :days, :hours or :minutes with
3335 a format string. The time duration is formatted using the
3336 largest time unit which gives a non-zero integer part. If all
3337 specified formats have zero integer part, the smallest time unit
3338 is used."
3339 :group 'org-time
3340 :type '(choice (string :tag "Format string")
3341 (set (group :inline t (const :tag "Years" :years)
3342 (string :tag "Format string"))
3343 (group :inline t (const :tag "Months" :months)
3344 (string :tag "Format string"))
3345 (group :inline t (const :tag "Weeks" :weeks)
3346 (string :tag "Format string"))
3347 (group :inline t (const :tag "Days" :days)
3348 (string :tag "Format string"))
3349 (group :inline t (const :tag "Hours" :hours)
3350 (string :tag "Format string"))
3351 (group :inline t (const :tag "Minutes" :minutes)
3352 (string :tag "Format string")))))
3354 (defcustom org-deadline-warning-days 14
3355 "Number of days before expiration during which a deadline becomes active.
3356 This variable governs the display in sparse trees and in the agenda.
3357 When 0 or negative, it means use this number (the absolute value of it)
3358 even if a deadline has a different individual lead time specified.
3360 Custom commands can set this variable in the options section."
3361 :group 'org-time
3362 :group 'org-agenda-daily/weekly
3363 :type 'integer)
3365 (defcustom org-scheduled-delay-days 0
3366 "Number of days before a scheduled item becomes active.
3367 This variable governs the display in sparse trees and in the agenda.
3368 The default value (i.e. 0) means: don't delay scheduled item.
3369 When negative, it means use this number (the absolute value of it)
3370 even if a scheduled item has a different individual delay time
3371 specified.
3373 Custom commands can set this variable in the options section."
3374 :group 'org-time
3375 :group 'org-agenda-daily/weekly
3376 :version "24.4"
3377 :package-version '(Org . "8.0")
3378 :type 'integer)
3380 (defcustom org-read-date-prefer-future t
3381 "Non-nil means assume future for incomplete date input from user.
3382 This affects the following situations:
3383 1. The user gives a month but not a year.
3384 For example, if it is April and you enter \"feb 2\", this will be read
3385 as Feb 2, *next* year. \"May 5\", however, will be this year.
3386 2. The user gives a day, but no month.
3387 For example, if today is the 15th, and you enter \"3\", Org will read
3388 this as the third of *next* month. However, if you enter \"17\",
3389 it will be considered as *this* month.
3391 If you set this variable to the symbol `time', then also the following
3392 will work:
3394 3. If the user gives a time.
3395 If the time is before now, it will be interpreted as tomorrow.
3397 Currently none of this works for ISO week specifications.
3399 When this option is nil, the current day, month and year will always be
3400 used as defaults.
3402 See also `org-agenda-jump-prefer-future'."
3403 :group 'org-time
3404 :type '(choice
3405 (const :tag "Never" nil)
3406 (const :tag "Check month and day" t)
3407 (const :tag "Check month, day, and time" time)))
3409 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3410 "Should the agenda jump command prefer the future for incomplete dates?
3411 The default is to do the same as configured in `org-read-date-prefer-future'.
3412 But you can also set a deviating value here.
3413 This may t or nil, or the symbol `org-read-date-prefer-future'."
3414 :group 'org-agenda
3415 :group 'org-time
3416 :version "24.1"
3417 :type '(choice
3418 (const :tag "Use org-read-date-prefer-future"
3419 org-read-date-prefer-future)
3420 (const :tag "Never" nil)
3421 (const :tag "Always" t)))
3423 (defcustom org-read-date-force-compatible-dates t
3424 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3426 Depending on the system Emacs is running on, certain dates cannot
3427 be represented with the type used internally to represent time.
3428 Dates between 1970-1-1 and 2038-1-1 can always be represented
3429 correctly. Some systems allow for earlier dates, some for later,
3430 some for both. One way to find out it to insert any date into an
3431 Org buffer, putting the cursor on the year and hitting S-up and
3432 S-down to test the range.
3434 When this variable is set to t, the date/time prompt will not let
3435 you specify dates outside the 1970-2037 range, so it is certain that
3436 these dates will work in whatever version of Emacs you are
3437 running, and also that you can move a file from one Emacs implementation
3438 to another. WHenever Org is forcing the year for you, it will display
3439 a message and beep.
3441 When this variable is nil, Org will check if the date is
3442 representable in the specific Emacs implementation you are using.
3443 If not, it will force a year, usually the current year, and beep
3444 to remind you. Currently this setting is not recommended because
3445 the likelihood that you will open your Org files in an Emacs that
3446 has limited date range is not negligible.
3448 A workaround for this problem is to use diary sexp dates for time
3449 stamps outside of this range."
3450 :group 'org-time
3451 :version "24.1"
3452 :type 'boolean)
3454 (defcustom org-read-date-display-live t
3455 "Non-nil means display current interpretation of date prompt live.
3456 This display will be in an overlay, in the minibuffer."
3457 :group 'org-time
3458 :type 'boolean)
3460 (defcustom org-read-date-popup-calendar t
3461 "Non-nil means pop up a calendar when prompting for a date.
3462 In the calendar, the date can be selected with mouse-1. However, the
3463 minibuffer will also be active, and you can simply enter the date as well.
3464 When nil, only the minibuffer will be available."
3465 :group 'org-time
3466 :type 'boolean)
3467 (defvaralias 'org-popup-calendar-for-date-prompt
3468 'org-read-date-popup-calendar)
3470 (defcustom org-extend-today-until 0
3471 "The hour when your day really ends. Must be an integer.
3472 This has influence for the following applications:
3473 - When switching the agenda to \"today\". It it is still earlier than
3474 the time given here, the day recognized as TODAY is actually yesterday.
3475 - When a date is read from the user and it is still before the time given
3476 here, the current date and time will be assumed to be yesterday, 23:59.
3477 Also, timestamps inserted in capture templates follow this rule.
3479 IMPORTANT: This is a feature whose implementation is and likely will
3480 remain incomplete. Really, it is only here because past midnight seems to
3481 be the favorite working time of John Wiegley :-)"
3482 :group 'org-time
3483 :type 'integer)
3485 (defcustom org-use-effective-time nil
3486 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3487 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3488 \"effective time\" of any timestamps between midnight and 8am will be
3489 23:59 of the previous day."
3490 :group 'org-time
3491 :version "24.1"
3492 :type 'boolean)
3494 (defcustom org-use-last-clock-out-time-as-effective-time nil
3495 "When non-nil, use the last clock out time for `org-todo'.
3496 Note that this option has precedence over the combined use of
3497 `org-use-effective-time' and `org-extend-today-until'."
3498 :group 'org-time
3499 :version "24.4"
3500 :package-version '(Org . "8.0")
3501 :type 'boolean)
3503 (defcustom org-edit-timestamp-down-means-later nil
3504 "Non-nil means S-down will increase the time in a time stamp.
3505 When nil, S-up will increase."
3506 :group 'org-time
3507 :type 'boolean)
3509 (defcustom org-calendar-follow-timestamp-change t
3510 "Non-nil means make the calendar window follow timestamp changes.
3511 When a timestamp is modified and the calendar window is visible, it will be
3512 moved to the new date."
3513 :group 'org-time
3514 :type 'boolean)
3516 (defgroup org-tags nil
3517 "Options concerning tags in Org mode."
3518 :tag "Org Tags"
3519 :group 'org)
3521 (defcustom org-tag-alist nil
3522 "Default tags available in Org files.
3524 The value of this variable is an alist. Associations either:
3526 (TAG)
3527 (TAG . SELECT)
3528 (SPECIAL)
3530 where TAG is a tag as a string, SELECT is a character, used to
3531 select that tag through the fast tag selection interface, and
3532 SPECIAL is one of the following keywords: `:startgroup',
3533 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3534 `:newline'. These keywords are used to define a hierarchy of
3535 tags. See manual for details.
3537 When this variable is nil, Org mode bases tag input on what is
3538 already in the buffer. The value can be overridden locally by
3539 using a TAGS keyword, e.g.,
3541 #+TAGS: tag1 tag2
3543 See also `org-tag-persistent-alist' to sidestep this behavior."
3544 :group 'org-tags
3545 :type '(repeat
3546 (choice
3547 (cons (string :tag "Tag name")
3548 (character :tag "Access char"))
3549 (const :tag "Start radio group" (:startgroup))
3550 (const :tag "Start tag group, non distinct" (:startgrouptag))
3551 (const :tag "Group tags delimiter" (:grouptags))
3552 (const :tag "End radio group" (:endgroup))
3553 (const :tag "End tag group, non distinct" (:endgrouptag))
3554 (const :tag "New line" (:newline)))))
3556 (defcustom org-tag-persistent-alist nil
3557 "Tags always available in Org files.
3559 The value of this variable is an alist. Associations either:
3561 (TAG)
3562 (TAG . SELECT)
3563 (SPECIAL)
3565 where TAG is a tag as a string, SELECT is a character, used to
3566 select that tag through the fast tag selection interface, and
3567 SPECIAL is one of the following keywords: `:startgroup',
3568 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3569 `:newline'. These keywords are used to define a hierarchy of
3570 tags. See manual for details.
3572 Unlike to `org-tag-alist', tags defined in this variable do not
3573 depend on a local TAGS keyword. Instead, to disable these tags
3574 on a per-file basis, insert anywhere in the file:
3576 #+STARTUP: noptag"
3577 :group 'org-tags
3578 :type '(repeat
3579 (choice
3580 (cons (string :tag "Tag name")
3581 (character :tag "Access char"))
3582 (const :tag "Start radio group" (:startgroup))
3583 (const :tag "Start tag group, non distinct" (:startgrouptag))
3584 (const :tag "Group tags delimiter" (:grouptags))
3585 (const :tag "End radio group" (:endgroup))
3586 (const :tag "End tag group, non distinct" (:endgrouptag))
3587 (const :tag "New line" (:newline)))))
3589 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3590 "If non-nil, always offer completion for all tags of all agenda files.
3591 Instead of customizing this variable directly, you might want to
3592 set it locally for capture buffers, because there no list of
3593 tags in that file can be created dynamically (there are none).
3595 (add-hook \\='org-capture-mode-hook
3596 (lambda ()
3597 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3598 :group 'org-tags
3599 :version "24.1"
3600 :type 'boolean)
3602 (defvar org-file-tags nil
3603 "List of tags that can be inherited by all entries in the file.
3604 The tags will be inherited if the variable `org-use-tag-inheritance'
3605 says they should be.
3606 This variable is populated from #+FILETAGS lines.")
3608 (defcustom org-use-fast-tag-selection 'auto
3609 "Non-nil means use fast tag selection scheme.
3610 This is a special interface to select and deselect tags with single keys.
3611 When nil, fast selection is never used.
3612 When the symbol `auto', fast selection is used if and only if selection
3613 characters for tags have been configured, either through the variable
3614 `org-tag-alist' or through a #+TAGS line in the buffer.
3615 When t, fast selection is always used and selection keys are assigned
3616 automatically if necessary."
3617 :group 'org-tags
3618 :type '(choice
3619 (const :tag "Always" t)
3620 (const :tag "Never" nil)
3621 (const :tag "When selection characters are configured" auto)))
3623 (defcustom org-fast-tag-selection-single-key nil
3624 "Non-nil means fast tag selection exits after first change.
3625 When nil, you have to press RET to exit it.
3626 During fast tag selection, you can toggle this flag with `C-c'.
3627 This variable can also have the value `expert'. In this case, the window
3628 displaying the tags menu is not even shown, until you press C-c again."
3629 :group 'org-tags
3630 :type '(choice
3631 (const :tag "No" nil)
3632 (const :tag "Yes" t)
3633 (const :tag "Expert" expert)))
3635 (defvar org-fast-tag-selection-include-todo nil
3636 "Non-nil means fast tags selection interface will also offer TODO states.
3637 This is an undocumented feature, you should not rely on it.")
3639 (defcustom org-tags-column -77
3640 "The column to which tags should be indented in a headline.
3641 If this number is positive, it specifies the column. If it is negative,
3642 it means that the tags should be flushright to that column. For example,
3643 -80 works well for a normal 80 character screen.
3644 When 0, place tags directly after headline text, with only one space in
3645 between."
3646 :group 'org-tags
3647 :type 'integer)
3649 (defcustom org-auto-align-tags t
3650 "Non-nil keeps tags aligned when modifying headlines.
3651 Some operations (i.e. demoting) change the length of a headline and
3652 therefore shift the tags around. With this option turned on, after
3653 each such operation the tags are again aligned to `org-tags-column'."
3654 :group 'org-tags
3655 :type 'boolean)
3657 (defcustom org-use-tag-inheritance t
3658 "Non-nil means tags in levels apply also for sublevels.
3659 When nil, only the tags directly given in a specific line apply there.
3660 This may also be a list of tags that should be inherited, or a regexp that
3661 matches tags that should be inherited. Additional control is possible
3662 with the variable `org-tags-exclude-from-inheritance' which gives an
3663 explicit list of tags to be excluded from inheritance, even if the value of
3664 `org-use-tag-inheritance' would select it for inheritance.
3666 If this option is t, a match early-on in a tree can lead to a large
3667 number of matches in the subtree when constructing the agenda or creating
3668 a sparse tree. If you only want to see the first match in a tree during
3669 a search, check out the variable `org-tags-match-list-sublevels'."
3670 :group 'org-tags
3671 :type '(choice
3672 (const :tag "Not" nil)
3673 (const :tag "Always" t)
3674 (repeat :tag "Specific tags" (string :tag "Tag"))
3675 (regexp :tag "Tags matched by regexp")))
3677 (defcustom org-tags-exclude-from-inheritance nil
3678 "List of tags that should never be inherited.
3679 This is a way to exclude a few tags from inheritance. For way to do
3680 the opposite, to actively allow inheritance for selected tags,
3681 see the variable `org-use-tag-inheritance'."
3682 :group 'org-tags
3683 :type '(repeat (string :tag "Tag")))
3685 (defun org-tag-inherit-p (tag)
3686 "Check if TAG is one that should be inherited."
3687 (cond
3688 ((member tag org-tags-exclude-from-inheritance) nil)
3689 ((eq org-use-tag-inheritance t) t)
3690 ((not org-use-tag-inheritance) nil)
3691 ((stringp org-use-tag-inheritance)
3692 (string-match org-use-tag-inheritance tag))
3693 ((listp org-use-tag-inheritance)
3694 (member tag org-use-tag-inheritance))
3695 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3697 (defcustom org-tags-match-list-sublevels t
3698 "Non-nil means list also sublevels of headlines matching a search.
3699 This variable applies to tags/property searches, and also to stuck
3700 projects because this search is based on a tags match as well.
3702 When set to the symbol `indented', sublevels are indented with
3703 leading dots.
3705 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3706 the sublevels of a headline matching a tag search often also match
3707 the same search. Listing all of them can create very long lists.
3708 Setting this variable to nil causes subtrees of a match to be skipped.
3710 This variable is semi-obsolete and probably should always be true. It
3711 is better to limit inheritance to certain tags using the variables
3712 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3713 :group 'org-tags
3714 :type '(choice
3715 (const :tag "No, don't list them" nil)
3716 (const :tag "Yes, do list them" t)
3717 (const :tag "List them, indented with leading dots" indented)))
3719 (defcustom org-tags-sort-function nil
3720 "When set, tags are sorted using this function as a comparator."
3721 :group 'org-tags
3722 :type '(choice
3723 (const :tag "No sorting" nil)
3724 (const :tag "Alphabetical" string<)
3725 (const :tag "Reverse alphabetical" string>)
3726 (function :tag "Custom function" nil)))
3728 (defvar org-tags-history nil
3729 "History of minibuffer reads for tags.")
3730 (defvar org-last-tags-completion-table nil
3731 "The last used completion table for tags.")
3732 (defvar org-after-tags-change-hook nil
3733 "Hook that is run after the tags in a line have changed.")
3735 (defgroup org-properties nil
3736 "Options concerning properties in Org mode."
3737 :tag "Org Properties"
3738 :group 'org)
3740 (defcustom org-property-format "%-10s %s"
3741 "How property key/value pairs should be formatted by `indent-line'.
3742 When `indent-line' hits a property definition, it will format the line
3743 according to this format, mainly to make sure that the values are
3744 lined-up with respect to each other."
3745 :group 'org-properties
3746 :type 'string)
3748 (defcustom org-properties-postprocess-alist nil
3749 "Alist of properties and functions to adjust inserted values.
3750 Elements of this alist must be of the form
3752 ([string] [function])
3754 where [string] must be a property name and [function] must be a
3755 lambda expression: this lambda expression must take one argument,
3756 the value to adjust, and return the new value as a string.
3758 For example, this element will allow the property \"Remaining\"
3759 to be updated wrt the relation between the \"Effort\" property
3760 and the clock summary:
3762 ((\"Remaining\" (lambda(value)
3763 (let ((clocksum (org-clock-sum-current-item))
3764 (effort (org-duration-string-to-minutes
3765 (org-entry-get (point) \"Effort\"))))
3766 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3767 :group 'org-properties
3768 :version "24.1"
3769 :type '(alist :key-type (string :tag "Property")
3770 :value-type (function :tag "Function")))
3772 (defcustom org-use-property-inheritance nil
3773 "Non-nil means properties apply also for sublevels.
3775 This setting is chiefly used during property searches. Turning it on can
3776 cause significant overhead when doing a search, which is why it is not
3777 on by default.
3779 When nil, only the properties directly given in the current entry count.
3780 When t, every property is inherited. The value may also be a list of
3781 properties that should have inheritance, or a regular expression matching
3782 properties that should be inherited.
3784 However, note that some special properties use inheritance under special
3785 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3786 and the properties ending in \"_ALL\" when they are used as descriptor
3787 for valid values of a property.
3789 Note for programmers:
3790 When querying an entry with `org-entry-get', you can control if inheritance
3791 should be used. By default, `org-entry-get' looks only at the local
3792 properties. You can request inheritance by setting the inherit argument
3793 to t (to force inheritance) or to `selective' (to respect the setting
3794 in this variable)."
3795 :group 'org-properties
3796 :type '(choice
3797 (const :tag "Not" nil)
3798 (const :tag "Always" t)
3799 (repeat :tag "Specific properties" (string :tag "Property"))
3800 (regexp :tag "Properties matched by regexp")))
3802 (defun org-property-inherit-p (property)
3803 "Check if PROPERTY is one that should be inherited."
3804 (cond
3805 ((eq org-use-property-inheritance t) t)
3806 ((not org-use-property-inheritance) nil)
3807 ((stringp org-use-property-inheritance)
3808 (string-match org-use-property-inheritance property))
3809 ((listp org-use-property-inheritance)
3810 (member property org-use-property-inheritance))
3811 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3813 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3814 "The default column format, if no other format has been defined.
3815 This variable can be set on the per-file basis by inserting a line
3817 #+COLUMNS: %25ITEM ....."
3818 :group 'org-properties
3819 :type 'string)
3821 (defcustom org-columns-ellipses ".."
3822 "The ellipses to be used when a field in column view is truncated.
3823 When this is the empty string, as many characters as possible are shown,
3824 but then there will be no visual indication that the field has been truncated.
3825 When this is a string of length N, the last N characters of a truncated
3826 field are replaced by this string. If the column is narrower than the
3827 ellipses string, only part of the ellipses string will be shown."
3828 :group 'org-properties
3829 :type 'string)
3831 (defconst org-global-properties-fixed
3832 '(("VISIBILITY_ALL" . "folded children content all")
3833 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3834 "List of property/value pairs that can be inherited by any entry.
3836 These are fixed values, for the preset properties. The user variable
3837 that can be used to add to this list is `org-global-properties'.
3839 The entries in this list are cons cells where the car is a property
3840 name and cdr is a string with the value. If the value represents
3841 multiple items like an \"_ALL\" property, separate the items by
3842 spaces.")
3844 (defcustom org-global-properties nil
3845 "List of property/value pairs that can be inherited by any entry.
3847 This list will be combined with the constant `org-global-properties-fixed'.
3849 The entries in this list are cons cells where the car is a property
3850 name and cdr is a string with the value.
3852 You can set buffer-local values for the same purpose in the variable
3853 `org-file-properties' this by adding lines like
3855 #+PROPERTY: NAME VALUE"
3856 :group 'org-properties
3857 :type '(repeat
3858 (cons (string :tag "Property")
3859 (string :tag "Value"))))
3861 (defvar-local org-file-properties nil
3862 "List of property/value pairs that can be inherited by any entry.
3863 Valid for the current buffer.
3864 This variable is populated from #+PROPERTY lines.")
3866 (defgroup org-agenda nil
3867 "Options concerning agenda views in Org mode."
3868 :tag "Org Agenda"
3869 :group 'org)
3871 (defvar-local org-category nil
3872 "Variable used by org files to set a category for agenda display.
3873 Such files should use a file variable to set it, for example
3875 # -*- mode: org; org-category: \"ELisp\"
3877 or contain a special line
3879 #+CATEGORY: ELisp
3881 If the file does not specify a category, then file's base name
3882 is used instead.")
3883 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3885 (defcustom org-agenda-files nil
3886 "The files to be used for agenda display.
3887 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3888 \\[org-remove-file]. You can also use customize to edit the list.
3890 If an entry is a directory, all files in that directory that are matched by
3891 `org-agenda-file-regexp' will be part of the file list.
3893 If the value of the variable is not a list but a single file name, then
3894 the list of agenda files is actually stored and maintained in that file, one
3895 agenda file per line. In this file paths can be given relative to
3896 `org-directory'. Tilde expansion and environment variable substitution
3897 are also made."
3898 :group 'org-agenda
3899 :type '(choice
3900 (repeat :tag "List of files and directories" file)
3901 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3903 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3904 "Regular expression to match files for `org-agenda-files'.
3905 If any element in the list in that variable contains a directory instead
3906 of a normal file, all files in that directory that are matched by this
3907 regular expression will be included."
3908 :group 'org-agenda
3909 :type 'regexp)
3911 (defcustom org-agenda-text-search-extra-files nil
3912 "List of extra files to be searched by text search commands.
3913 These files will be searched in addition to the agenda files by the
3914 commands `org-search-view' (`\\[org-agenda] s') \
3915 and `org-occur-in-agenda-files'.
3916 Note that these files will only be searched for text search commands,
3917 not for the other agenda views like todo lists, tag searches or the weekly
3918 agenda. This variable is intended to list notes and possibly archive files
3919 that should also be searched by these two commands.
3920 In fact, if the first element in the list is the symbol `agenda-archives',
3921 then all archive files of all agenda files will be added to the search
3922 scope."
3923 :group 'org-agenda
3924 :type '(set :greedy t
3925 (const :tag "Agenda Archives" agenda-archives)
3926 (repeat :inline t (file))))
3928 (defvaralias 'org-agenda-multi-occur-extra-files
3929 'org-agenda-text-search-extra-files)
3931 (defcustom org-agenda-skip-unavailable-files nil
3932 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3933 A nil value means to remove them, after a query, from the list."
3934 :group 'org-agenda
3935 :type 'boolean)
3937 (defcustom org-calendar-to-agenda-key [?c]
3938 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3939 The command `org-calendar-goto-agenda' will be bound to this key. The
3940 default is the character `c' because then `c' can be used to switch back and
3941 forth between agenda and calendar."
3942 :group 'org-agenda
3943 :type 'sexp)
3945 (defcustom org-calendar-insert-diary-entry-key [?i]
3946 "The key to be installed in `calendar-mode-map' for adding diary entries.
3947 This option is irrelevant until `org-agenda-diary-file' has been configured
3948 to point to an Org file. When that is the case, the command
3949 `org-agenda-diary-entry' will be bound to the key given here, by default
3950 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3951 if you want to continue doing this, you need to change this to a different
3952 key."
3953 :group 'org-agenda
3954 :type 'sexp)
3956 (defcustom org-agenda-diary-file 'diary-file
3957 "File to which to add new entries with the `i' key in agenda and calendar.
3958 When this is the symbol `diary-file', the functionality in the Emacs
3959 calendar will be used to add entries to the `diary-file'. But when this
3960 points to a file, `org-agenda-diary-entry' will be used instead."
3961 :group 'org-agenda
3962 :type '(choice
3963 (const :tag "The standard Emacs diary file" diary-file)
3964 (file :tag "Special Org file diary entries")))
3966 (eval-after-load "calendar"
3967 '(progn
3968 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3969 'org-calendar-goto-agenda)
3970 (add-hook 'calendar-mode-hook
3971 (lambda ()
3972 (unless (eq org-agenda-diary-file 'diary-file)
3973 (define-key calendar-mode-map
3974 org-calendar-insert-diary-entry-key
3975 'org-agenda-diary-entry))))))
3977 (defgroup org-latex nil
3978 "Options for embedding LaTeX code into Org mode."
3979 :tag "Org LaTeX"
3980 :group 'org)
3982 (defcustom org-format-latex-options
3983 '(:foreground default :background default :scale 1.0
3984 :html-foreground "Black" :html-background "Transparent"
3985 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3986 "Options for creating images from LaTeX fragments.
3987 This is a property list with the following properties:
3988 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3989 `default' means use the foreground of the default face.
3990 `auto' means use the foreground from the text face.
3991 :background the background color, or \"Transparent\".
3992 `default' means use the background of the default face.
3993 `auto' means use the background from the text face.
3994 :scale a scaling factor for the size of the images, to get more pixels
3995 :html-foreground, :html-background, :html-scale
3996 the same numbers for HTML export.
3997 :matchers a list indicating which matchers should be used to
3998 find LaTeX fragments. Valid members of this list are:
3999 \"begin\" find environments
4000 \"$1\" find single characters surrounded by $.$
4001 \"$\" find math expressions surrounded by $...$
4002 \"$$\" find math expressions surrounded by $$....$$
4003 \"\\(\" find math expressions surrounded by \\(...\\)
4004 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4005 :group 'org-latex
4006 :type 'plist)
4008 (defcustom org-format-latex-signal-error t
4009 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4010 When nil, just push out a message."
4011 :group 'org-latex
4012 :version "24.1"
4013 :type 'boolean)
4015 (defcustom org-latex-to-mathml-jar-file nil
4016 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4017 Use this to specify additional executable file say a jar file.
4019 When using MathToWeb as the converter, specify the full-path to
4020 your mathtoweb.jar file."
4021 :group 'org-latex
4022 :version "24.1"
4023 :type '(choice
4024 (const :tag "None" nil)
4025 (file :tag "JAR file" :must-match t)))
4027 (defcustom org-latex-to-mathml-convert-command nil
4028 "Command to convert LaTeX fragments to MathML.
4029 Replace format-specifiers in the command as noted below and use
4030 `shell-command' to convert LaTeX to MathML.
4031 %j: Executable file in fully expanded form as specified by
4032 `org-latex-to-mathml-jar-file'.
4033 %I: Input LaTeX file in fully expanded form.
4034 %i: The latex fragment to be converted.
4035 %o: Output MathML file.
4037 This command is used by `org-create-math-formula'.
4039 When using MathToWeb as the converter, set this option to
4040 \"java -jar %j -unicode -force -df %o %I\".
4042 When using LaTeXML set this option to
4043 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4044 :group 'org-latex
4045 :version "24.1"
4046 :type '(choice
4047 (const :tag "None" nil)
4048 (string :tag "\nShell command")))
4050 (defcustom org-preview-latex-default-process 'dvipng
4051 "The default process to convert LaTeX fragments to image files.
4052 All available processes and theirs documents can be found in
4053 `org-preview-latex-process-alist', which see."
4054 :group 'org-latex
4055 :version "25.2"
4056 :package-version '(Org . "9.0")
4057 :type 'symbol)
4059 (defcustom org-preview-latex-process-alist
4060 '((dvipng
4061 :programs ("latex" "dvipng" "gs")
4062 :description "dvi > png"
4063 :message "you need to install the programs: latex, dvipng and ghostscript."
4064 :image-input-type "dvi"
4065 :image-output-type "png"
4066 :image-size-adjust (1.0 . 1.0)
4067 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4068 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4069 (dvisvgm
4070 :programs ("latex" "dvisvgm" "gs")
4071 :description "dvi > svg"
4072 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4073 :use-xcolor t
4074 :image-input-type "dvi"
4075 :image-output-type "svg"
4076 :image-size-adjust (1.7 . 1.5)
4077 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4078 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4079 (imagemagick
4080 :programs ("latex" "convert" "gs")
4081 :description "pdf > png"
4082 :message
4083 "you need to install the programs: latex, imagemagick and ghostscript."
4084 :use-xcolor t
4085 :image-input-type "pdf"
4086 :image-output-type "png"
4087 :image-size-adjust (1.0 . 1.0)
4088 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4089 :image-converter
4090 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4091 "Definitions of external processes for LaTeX previewing.
4092 Org mode can use some external commands to generate TeX snippet's images for
4093 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4094 `org-create-formula-image' how to call them.
4096 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4097 PROPERTIES accepts the following attributes:
4099 :programs list of strings, required programs.
4100 :description string, describe the process.
4101 :message string, message it when required programs cannot be found.
4102 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4103 :image-output-type string, output file type of image converter (e.g., \"png\").
4104 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4105 deal with background and foreground color of image.
4106 Otherwise, dvipng style background and foregroud color
4107 format are generated. You may then refer to them in
4108 command options with \"%F\" and \"%B\".
4109 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4110 image size showed in buffer and the cdr element is for
4111 HTML file. This option is only useful for process
4112 developers, users should use variable
4113 `org-format-latex-options' instead.
4114 :post-clean list of strings, files matched are to be cleaned up once
4115 the image is generated. When nil, the files with \".dvi\",
4116 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4117 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4118 be cleaned up.
4119 :latex-header list of strings, the LaTeX header of the snippet file.
4120 When nil, the fallback value is used instead, which is
4121 controlled by `org-format-latex-header',
4122 `org-latex-default-packages-alist' and
4123 `org-latex-packages-alist', which see.
4124 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4125 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4126 replaced with values defined below.
4127 :image-converter list of image converter commands strings. Each of them is
4128 given to the shell and supports any of the following
4129 place-holders defined below.
4131 Place-holders used by `:image-converter' and `:latex-compiler':
4133 %f input file name.
4134 %b base name of input file.
4135 %o base directory of input file.
4137 Place-holders only used by `:image-converter':
4139 %F foreground of image
4140 %B background of image
4141 %D dpi, which is used to adjust image size by some processing commands.
4142 %S the image size scale ratio, which is used to adjust image size by some
4143 processing commands."
4144 :group 'org-latex
4145 :version "25.2"
4146 :package-version '(Org . "9.0")
4147 :type '(alist :tag "LaTeX to image backends"
4148 :value-type (plist)))
4150 (defcustom org-preview-latex-image-directory "ltximg/"
4151 "Path to store latex preview images.
4152 A relative path here creates many directories relative to the
4153 processed org files paths. An absolute path puts all preview
4154 images at the same place."
4155 :group 'org-latex
4156 :version "25.2"
4157 :package-version '(Org . "9.0")
4158 :type 'string)
4160 (defun org-format-latex-mathml-available-p ()
4161 "Return t if `org-latex-to-mathml-convert-command' is usable."
4162 (save-match-data
4163 (when (and (boundp 'org-latex-to-mathml-convert-command)
4164 org-latex-to-mathml-convert-command)
4165 (let ((executable (car (split-string
4166 org-latex-to-mathml-convert-command))))
4167 (when (executable-find executable)
4168 (if (string-match
4169 "%j" org-latex-to-mathml-convert-command)
4170 (file-readable-p org-latex-to-mathml-jar-file)
4171 t))))))
4173 (defcustom org-format-latex-header "\\documentclass{article}
4174 \\usepackage[usenames]{color}
4175 \[PACKAGES]
4176 \[DEFAULT-PACKAGES]
4177 \\pagestyle{empty} % do not remove
4178 % The settings below are copied from fullpage.sty
4179 \\setlength{\\textwidth}{\\paperwidth}
4180 \\addtolength{\\textwidth}{-3cm}
4181 \\setlength{\\oddsidemargin}{1.5cm}
4182 \\addtolength{\\oddsidemargin}{-2.54cm}
4183 \\setlength{\\evensidemargin}{\\oddsidemargin}
4184 \\setlength{\\textheight}{\\paperheight}
4185 \\addtolength{\\textheight}{-\\headheight}
4186 \\addtolength{\\textheight}{-\\headsep}
4187 \\addtolength{\\textheight}{-\\footskip}
4188 \\addtolength{\\textheight}{-3cm}
4189 \\setlength{\\topmargin}{1.5cm}
4190 \\addtolength{\\topmargin}{-2.54cm}"
4191 "The document header used for processing LaTeX fragments.
4192 It is imperative that this header make sure that no page number
4193 appears on the page. The package defined in the variables
4194 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4195 will either replace the placeholder \"[PACKAGES]\" in this
4196 header, or they will be appended."
4197 :group 'org-latex
4198 :type 'string)
4200 (defun org-set-packages-alist (var val)
4201 "Set the packages alist and make sure it has 3 elements per entry."
4202 (set var (mapcar (lambda (x)
4203 (if (and (consp x) (= (length x) 2))
4204 (list (car x) (nth 1 x) t)
4206 val)))
4208 (defun org-get-packages-alist (var)
4209 "Get the packages alist and make sure it has 3 elements per entry."
4210 (mapcar (lambda (x)
4211 (if (and (consp x) (= (length x) 2))
4212 (list (car x) (nth 1 x) t)
4214 (default-value var)))
4216 (defcustom org-latex-default-packages-alist
4217 '(("AUTO" "inputenc" t ("pdflatex"))
4218 ("T1" "fontenc" t ("pdflatex"))
4219 ("" "graphicx" t)
4220 ("" "grffile" t)
4221 ("" "longtable" nil)
4222 ("" "wrapfig" nil)
4223 ("" "rotating" nil)
4224 ("normalem" "ulem" t)
4225 ("" "amsmath" t)
4226 ("" "textcomp" t)
4227 ("" "amssymb" t)
4228 ("" "capt-of" nil)
4229 ("" "hyperref" nil))
4230 "Alist of default packages to be inserted in the header.
4232 Change this only if one of the packages here causes an
4233 incompatibility with another package you are using.
4235 The packages in this list are needed by one part or another of
4236 Org mode to function properly:
4238 - inputenc, fontenc: for basic font and character selection
4239 - graphicx: for including images
4240 - grffile: allow periods and spaces in graphics file names
4241 - longtable: For multipage tables
4242 - wrapfig: for figure placement
4243 - rotating: for sideways figures and tables
4244 - ulem: for underline and strike-through
4245 - amsmath: for subscript and superscript and math environments
4246 - textcomp, amssymb: for various symbols used
4247 for interpreting the entities in `org-entities'. You can skip
4248 some of these packages if you don't use any of their symbols.
4249 - capt-of: for captions outside of floats
4250 - hyperref: for cross references
4252 Therefore you should not modify this variable unless you know
4253 what you are doing. The one reason to change it anyway is that
4254 you might be loading some other package that conflicts with one
4255 of the default packages. Each element is either a cell or
4256 a string.
4258 A cell is of the format
4260 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4262 If SNIPPET-FLAG is non-nil, the package also needs to be included
4263 when compiling LaTeX snippets into images for inclusion into
4264 non-LaTeX output. COMPILERS is a list of compilers that should
4265 include the package, see `org-latex-compiler'. If the document
4266 compiler is not in the list, and the list is non-nil, the package
4267 will not be inserted in the final document.
4269 A string will be inserted as-is in the header of the document."
4270 :group 'org-latex
4271 :group 'org-export-latex
4272 :set 'org-set-packages-alist
4273 :get 'org-get-packages-alist
4274 :version "25.2"
4275 :package-version '(Org . "8.3")
4276 :type '(repeat
4277 (choice
4278 (list :tag "options/package pair"
4279 (string :tag "options")
4280 (string :tag "package")
4281 (boolean :tag "Snippet"))
4282 (string :tag "A line of LaTeX"))))
4284 (defcustom org-latex-packages-alist nil
4285 "Alist of packages to be inserted in every LaTeX header.
4287 These will be inserted after `org-latex-default-packages-alist'.
4288 Each element is either a cell or a string.
4290 A cell is of the format:
4292 (\"options\" \"package\" SNIPPET-FLAG)
4294 SNIPPET-FLAG, when non-nil, indicates that this package is also
4295 needed when turning LaTeX snippets into images for inclusion into
4296 non-LaTeX output.
4298 A string will be inserted as-is in the header of the document.
4300 Make sure that you only list packages here which:
4302 - you want in every file;
4303 - do not conflict with the setup in `org-format-latex-header';
4304 - do not conflict with the default packages in
4305 `org-latex-default-packages-alist'."
4306 :group 'org-latex
4307 :group 'org-export-latex
4308 :set 'org-set-packages-alist
4309 :get 'org-get-packages-alist
4310 :type '(repeat
4311 (choice
4312 (list :tag "options/package pair"
4313 (string :tag "options")
4314 (string :tag "package")
4315 (boolean :tag "Snippet"))
4316 (string :tag "A line of LaTeX"))))
4318 (defgroup org-appearance nil
4319 "Settings for Org mode appearance."
4320 :tag "Org Appearance"
4321 :group 'org)
4323 (defcustom org-level-color-stars-only nil
4324 "Non-nil means fontify only the stars in each headline.
4325 When nil, the entire headline is fontified.
4326 Changing it requires restart of `font-lock-mode' to become effective
4327 also in regions already fontified."
4328 :group 'org-appearance
4329 :type 'boolean)
4331 (defcustom org-hide-leading-stars nil
4332 "Non-nil means hide the first N-1 stars in a headline.
4333 This works by using the face `org-hide' for these stars. This
4334 face is white for a light background, and black for a dark
4335 background. You may have to customize the face `org-hide' to
4336 make this work.
4337 Changing it requires restart of `font-lock-mode' to become effective
4338 also in regions already fontified.
4339 You may also set this on a per-file basis by adding one of the following
4340 lines to the buffer:
4342 #+STARTUP: hidestars
4343 #+STARTUP: showstars"
4344 :group 'org-appearance
4345 :type 'boolean)
4347 (defcustom org-hidden-keywords nil
4348 "List of symbols corresponding to keywords to be hidden the org buffer.
4349 For example, a value \\='(title) for this list will make the document's title
4350 appear in the buffer without the initial #+TITLE: keyword."
4351 :group 'org-appearance
4352 :version "24.1"
4353 :type '(set (const :tag "#+AUTHOR" author)
4354 (const :tag "#+DATE" date)
4355 (const :tag "#+EMAIL" email)
4356 (const :tag "#+TITLE" title)))
4358 (defcustom org-custom-properties nil
4359 "List of properties (as strings) with a special meaning.
4360 The default use of these custom properties is to let the user
4361 hide them with `org-toggle-custom-properties-visibility'."
4362 :group 'org-properties
4363 :group 'org-appearance
4364 :version "24.3"
4365 :type '(repeat (string :tag "Property Name")))
4367 (defcustom org-fontify-done-headline nil
4368 "Non-nil means change the face of a headline if it is marked DONE.
4369 Normally, only the TODO/DONE keyword indicates the state of a headline.
4370 When this is non-nil, the headline after the keyword is set to the
4371 `org-headline-done' as an additional indication."
4372 :group 'org-appearance
4373 :type 'boolean)
4375 (defcustom org-fontify-emphasized-text t
4376 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4377 Changing this variable requires a restart of Emacs to take effect."
4378 :group 'org-appearance
4379 :type 'boolean)
4381 (defcustom org-fontify-whole-heading-line nil
4382 "Non-nil means fontify the whole line for headings.
4383 This is useful when setting a background color for the
4384 org-level-* faces."
4385 :group 'org-appearance
4386 :type 'boolean)
4388 (defcustom org-highlight-latex-and-related nil
4389 "Non-nil means highlight LaTeX related syntax in the buffer.
4390 When non nil, the value should be a list containing any of the
4391 following symbols:
4392 `latex' Highlight LaTeX snippets and environments.
4393 `script' Highlight subscript and superscript.
4394 `entities' Highlight entities."
4395 :group 'org-appearance
4396 :version "24.4"
4397 :package-version '(Org . "8.0")
4398 :type '(choice
4399 (const :tag "No highlighting" nil)
4400 (set :greedy t :tag "Highlight"
4401 (const :tag "LaTeX snippets and environments" latex)
4402 (const :tag "Subscript and superscript" script)
4403 (const :tag "Entities" entities))))
4405 (defcustom org-hide-emphasis-markers nil
4406 "Non-nil mean font-lock should hide the emphasis marker characters."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-hide-macro-markers nil
4411 "Non-nil mean font-lock should hide the brackets marking macro calls."
4412 :group 'org-appearance
4413 :type 'boolean)
4415 (defcustom org-pretty-entities nil
4416 "Non-nil means show entities as UTF8 characters.
4417 When nil, the \\name form remains in the buffer."
4418 :group 'org-appearance
4419 :version "24.1"
4420 :type 'boolean)
4422 (defcustom org-pretty-entities-include-sub-superscripts t
4423 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4424 :group 'org-appearance
4425 :version "24.1"
4426 :type 'boolean)
4428 (defvar org-emph-re nil
4429 "Regular expression for matching emphasis.
4430 After a match, the match groups contain these elements:
4431 0 The match of the full regular expression, including the characters
4432 before and after the proper match
4433 1 The character before the proper match, or empty at beginning of line
4434 2 The proper match, including the leading and trailing markers
4435 3 The leading marker like * or /, indicating the type of highlighting
4436 4 The text between the emphasis markers, not including the markers
4437 5 The character after the match, empty at the end of a line")
4438 (defvar org-verbatim-re nil
4439 "Regular expression for matching verbatim text.")
4440 (defvar org-emphasis-regexp-components) ; defined just below
4441 (defvar org-emphasis-alist) ; defined just below
4442 (defun org-set-emph-re (var val)
4443 "Set variable and compute the emphasis regular expression."
4444 (set var val)
4445 (when (and (boundp 'org-emphasis-alist)
4446 (boundp 'org-emphasis-regexp-components)
4447 org-emphasis-alist org-emphasis-regexp-components)
4448 (let* ((e org-emphasis-regexp-components)
4449 (pre (car e))
4450 (post (nth 1 e))
4451 (border (nth 2 e))
4452 (body (nth 3 e))
4453 (nl (nth 4 e))
4454 (body1 (concat body "*?"))
4455 (markers (mapconcat 'car org-emphasis-alist ""))
4456 (vmarkers (mapconcat
4457 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4458 org-emphasis-alist "")))
4459 ;; make sure special characters appear at the right position in the class
4460 (if (string-match "\\^" markers)
4461 (setq markers (concat (replace-match "" t t markers) "^")))
4462 (if (string-match "-" markers)
4463 (setq markers (concat (replace-match "" t t markers) "-")))
4464 (if (string-match "\\^" vmarkers)
4465 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4466 (if (string-match "-" vmarkers)
4467 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4468 (if (> nl 0)
4469 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4470 (int-to-string nl) "\\}")))
4471 ;; Make the regexp
4472 (setq org-emph-re
4473 (concat "\\([" pre "]\\|^\\)"
4474 "\\("
4475 "\\([" markers "]\\)"
4476 "\\("
4477 "[^" border "]\\|"
4478 "[^" border "]"
4479 body1
4480 "[^" border "]"
4481 "\\)"
4482 "\\3\\)"
4483 "\\([" post "]\\|$\\)"))
4484 (setq org-verbatim-re
4485 (concat "\\([" pre "]\\|^\\)"
4486 "\\("
4487 "\\([" vmarkers "]\\)"
4488 "\\("
4489 "[^" border "]\\|"
4490 "[^" border "]"
4491 body1
4492 "[^" border "]"
4493 "\\)"
4494 "\\3\\)"
4495 "\\([" post "]\\|$\\)")))))
4497 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4498 ;; set this option proved cumbersome. See this message/thread:
4499 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4500 (defvar org-emphasis-regexp-components
4501 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4502 "Components used to build the regular expression for emphasis.
4503 This is a list with five entries. Terminology: In an emphasis string
4504 like \" *strong word* \", we call the initial space PREMATCH, the final
4505 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4506 and \"trong wor\" is the body. The different components in this variable
4507 specify what is allowed/forbidden in each part:
4509 pre Chars allowed as prematch. Beginning of line will be allowed too.
4510 post Chars allowed as postmatch. End of line will be allowed too.
4511 border The chars *forbidden* as border characters.
4512 body-regexp A regexp like \".\" to match a body character. Don't use
4513 non-shy groups here, and don't allow newline here.
4514 newline The maximum number of newlines allowed in an emphasis exp.
4516 You need to reload Org or to restart Emacs after customizing this.")
4518 (defcustom org-emphasis-alist
4519 '(("*" bold)
4520 ("/" italic)
4521 ("_" underline)
4522 ("=" org-verbatim verbatim)
4523 ("~" org-code verbatim)
4524 ("+" (:strike-through t)))
4525 "Alist of characters and faces to emphasize text.
4526 Text starting and ending with a special character will be emphasized,
4527 for example *bold*, _underlined_ and /italic/. This variable sets the
4528 marker characters and the face to be used by font-lock for highlighting
4529 in Org buffers.
4531 You need to reload Org or to restart Emacs after customizing this."
4532 :group 'org-appearance
4533 :set 'org-set-emph-re
4534 :version "24.4"
4535 :package-version '(Org . "8.0")
4536 :type '(repeat
4537 (list
4538 (string :tag "Marker character")
4539 (choice
4540 (face :tag "Font-lock-face")
4541 (plist :tag "Face property list"))
4542 (option (const verbatim)))))
4544 (defvar org-protecting-blocks '("src" "example" "export")
4545 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4546 This is needed for font-lock setup.")
4548 ;;; Functions and variables from their packages
4549 ;; Declared here to avoid compiler warnings
4550 (defvar mark-active)
4552 ;; Various packages
4553 (declare-function calc-eval "calc" (str &optional separator &rest args))
4554 (declare-function calendar-forward-day "cal-move" (arg))
4555 (declare-function calendar-goto-date "cal-move" (date))
4556 (declare-function calendar-goto-today "cal-move" ())
4557 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4558 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4559 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4560 (declare-function cdlatex-tab "ext:cdlatex" ())
4561 (declare-function dired-get-filename
4562 "dired"
4563 (&optional localp no-error-if-not-filep))
4564 (declare-function iswitchb-read-buffer
4565 "iswitchb"
4566 (prompt &optional
4567 default require-match _predicate start matches-set))
4568 (declare-function org-agenda-change-all-lines
4569 "org-agenda"
4570 (newhead hdmarker &optional fixface just-this))
4571 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4572 "org-agenda"
4573 (&optional end))
4574 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4575 (declare-function org-agenda-format-item
4576 "org-agenda"
4577 (extra txt &optional level category tags dotime
4578 remove-re habitp))
4579 (declare-function org-agenda-maybe-redo "org-agenda" ())
4580 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4581 (declare-function org-agenda-save-markers-for-cut-and-paste
4582 "org-agenda"
4583 (beg end))
4584 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4585 (declare-function org-agenda-skip "org-agenda" ())
4586 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4587 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4588 (declare-function org-indent-mode "org-indent" (&optional arg))
4589 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4590 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4591 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4592 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4593 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4594 (declare-function parse-time-string "parse-time" (string))
4595 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4597 (defvar align-mode-rules-list)
4598 (defvar calc-embedded-close-formula)
4599 (defvar calc-embedded-open-formula)
4600 (defvar calc-embedded-open-mode)
4601 (defvar font-lock-unfontify-region-function)
4602 (defvar iswitchb-temp-buflist)
4603 (defvar org-agenda-tags-todo-honor-ignore-options)
4604 (defvar remember-data-file)
4605 (defvar texmathp-why)
4607 ;;;###autoload
4608 (defun turn-on-orgtbl ()
4609 "Unconditionally turn on `orgtbl-mode'."
4610 (require 'org-table)
4611 (orgtbl-mode 1))
4613 (defun org-at-table-p (&optional table-type)
4614 "Non-nil if the cursor is inside an Org table.
4615 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4616 If `org-enable-table-editor' is nil, return nil unconditionally."
4617 (and
4618 org-enable-table-editor
4619 (save-excursion
4620 (beginning-of-line)
4621 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4622 (or (not (derived-mode-p 'org-mode))
4623 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4624 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4626 (defun org-at-table.el-p ()
4627 "Non-nil when point is at a table.el table."
4628 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4629 (let ((element (org-element-at-point)))
4630 (and (eq (org-element-type element) 'table)
4631 (eq (org-element-property :type element) 'table.el)))))
4633 (defun org-at-table-hline-p ()
4634 "Non-nil when point is inside a hline in a table.
4635 Assume point is already in a table. If `org-enable-table-editor'
4636 is nil, return nil unconditionally."
4637 (and org-enable-table-editor
4638 (save-excursion
4639 (beginning-of-line)
4640 (looking-at org-table-hline-regexp))))
4642 (defun org-table-map-tables (function &optional quietly)
4643 "Apply FUNCTION to the start of all tables in the buffer."
4644 (org-with-wide-buffer
4645 (goto-char (point-min))
4646 (while (re-search-forward org-table-any-line-regexp nil t)
4647 (unless quietly
4648 (message "Mapping tables: %d%%"
4649 (floor (* 100.0 (point)) (buffer-size))))
4650 (beginning-of-line 1)
4651 (when (and (looking-at org-table-line-regexp)
4652 ;; Exclude tables in src/example/verbatim/clocktable blocks
4653 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4654 (save-excursion (funcall function))
4655 (or (looking-at org-table-line-regexp)
4656 (forward-char 1)))
4657 (re-search-forward org-table-any-border-regexp nil 1)))
4658 (unless quietly (message "Mapping tables: done")))
4660 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4661 (declare-function org-clock-update-mode-line "org-clock" ())
4662 (declare-function org-resolve-clocks "org-clock"
4663 (&optional also-non-dangling-p prompt last-valid))
4665 (defun org-at-TBLFM-p (&optional pos)
4666 "Non-nil when point (or POS) is in #+TBLFM line."
4667 (save-excursion
4668 (goto-char (or pos (point)))
4669 (beginning-of-line)
4670 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4671 (eq (org-element-type (org-element-at-point)) 'table))))
4673 (defvar org-clock-start-time)
4674 (defvar org-clock-marker (make-marker)
4675 "Marker recording the last clock-in.")
4676 (defvar org-clock-hd-marker (make-marker)
4677 "Marker recording the last clock-in, but the headline position.")
4678 (defvar org-clock-heading ""
4679 "The heading of the current clock entry.")
4680 (defun org-clock-is-active ()
4681 "Return the buffer where the clock is currently running.
4682 Return nil if no clock is running."
4683 (marker-buffer org-clock-marker))
4685 (defun org-check-running-clock ()
4686 "Check if the current buffer contains the running clock.
4687 If yes, offer to stop it and to save the buffer with the changes."
4688 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4689 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4690 (buffer-name))))
4691 (org-clock-out)
4692 (when (y-or-n-p "Save changed buffer?")
4693 (save-buffer))))
4695 (defun org-clocktable-try-shift (dir n)
4696 "Check if this line starts a clock table, if yes, shift the time block."
4697 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4698 (org-clocktable-shift dir n)))
4700 ;;;###autoload
4701 (defun org-clock-persistence-insinuate ()
4702 "Set up hooks for clock persistence."
4703 (require 'org-clock)
4704 (add-hook 'org-mode-hook 'org-clock-load)
4705 (add-hook 'kill-emacs-hook 'org-clock-save))
4707 (defgroup org-archive nil
4708 "Options concerning archiving in Org mode."
4709 :tag "Org Archive"
4710 :group 'org-structure)
4712 (defcustom org-archive-location "%s_archive::"
4713 "The location where subtrees should be archived.
4715 The value of this variable is a string, consisting of two parts,
4716 separated by a double-colon. The first part is a filename and
4717 the second part is a headline.
4719 When the filename is omitted, archiving happens in the same file.
4720 %s in the filename will be replaced by the current file
4721 name (without the directory part). Archiving to a different file
4722 is useful to keep archived entries from contributing to the
4723 Org Agenda.
4725 The archived entries will be filed as subtrees of the specified
4726 headline. When the headline is omitted, the subtrees are simply
4727 filed away at the end of the file, as top-level entries. Also in
4728 the heading you can use %s to represent the file name, this can be
4729 useful when using the same archive for a number of different files.
4731 Here are a few examples:
4732 \"%s_archive::\"
4733 If the current file is Projects.org, archive in file
4734 Projects.org_archive, as top-level trees. This is the default.
4736 \"::* Archived Tasks\"
4737 Archive in the current file, under the top-level headline
4738 \"* Archived Tasks\".
4740 \"~/org/archive.org::\"
4741 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4743 \"~/org/archive.org::* From %s\"
4744 Archive in file ~/org/archive.org (absolute path), under headlines
4745 \"From FILENAME\" where file name is the current file name.
4747 \"~/org/datetree.org::datetree/* Finished Tasks\"
4748 The \"datetree/\" string is special, signifying to archive
4749 items to the datetree. Items are placed in either the CLOSED
4750 date of the item, or the current date if there is no CLOSED date.
4751 The heading will be a subentry to the current date. There doesn't
4752 need to be a heading, but there always needs to be a slash after
4753 datetree. For example, to store archived items directly in the
4754 datetree, use \"~/org/datetree.org::datetree/\".
4756 \"basement::** Finished Tasks\"
4757 Archive in file ./basement (relative path), as level 3 trees
4758 below the level 2 heading \"** Finished Tasks\".
4760 You may set this option on a per-file basis by adding to the buffer a
4761 line like
4763 #+ARCHIVE: basement::** Finished Tasks
4765 You may also define it locally for a subtree by setting an ARCHIVE property
4766 in the entry. If such a property is found in an entry, or anywhere up
4767 the hierarchy, it will be used."
4768 :group 'org-archive
4769 :type 'string)
4771 (defcustom org-agenda-skip-archived-trees t
4772 "Non-nil means the agenda will skip any items located in archived trees.
4773 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4774 variable is no longer recommended, you should leave it at the value t.
4775 Instead, use the key `v' to cycle the archives-mode in the agenda."
4776 :group 'org-archive
4777 :group 'org-agenda-skip
4778 :type 'boolean)
4780 (defcustom org-columns-skip-archived-trees t
4781 "Non-nil means ignore archived trees when creating column view."
4782 :group 'org-archive
4783 :group 'org-properties
4784 :type 'boolean)
4786 (defcustom org-cycle-open-archived-trees nil
4787 "Non-nil means `org-cycle' will open archived trees.
4788 An archived tree is a tree marked with the tag ARCHIVE.
4789 When nil, archived trees will stay folded. You can still open them with
4790 normal outline commands like `show-all', but not with the cycling commands."
4791 :group 'org-archive
4792 :group 'org-cycle
4793 :type 'boolean)
4795 (defcustom org-sparse-tree-open-archived-trees nil
4796 "Non-nil means sparse tree construction shows matches in archived trees.
4797 When nil, matches in these trees are highlighted, but the trees are kept in
4798 collapsed state."
4799 :group 'org-archive
4800 :group 'org-sparse-trees
4801 :type 'boolean)
4803 (defcustom org-sparse-tree-default-date-type nil
4804 "The default date type when building a sparse tree.
4805 When this is nil, a date is a scheduled or a deadline timestamp.
4806 Otherwise, these types are allowed:
4808 all: all timestamps
4809 active: only active timestamps (<...>)
4810 inactive: only inactive timestamps ([...])
4811 scheduled: only scheduled timestamps
4812 deadline: only deadline timestamps"
4813 :type '(choice (const :tag "Scheduled or deadline" nil)
4814 (const :tag "All timestamps" all)
4815 (const :tag "Only active timestamps" active)
4816 (const :tag "Only inactive timestamps" inactive)
4817 (const :tag "Only scheduled timestamps" scheduled)
4818 (const :tag "Only deadline timestamps" deadline)
4819 (const :tag "Only closed timestamps" closed))
4820 :version "25.2"
4821 :package-version '(Org . "8.3")
4822 :group 'org-sparse-trees)
4824 (defun org-cycle-hide-archived-subtrees (state)
4825 "Re-hide all archived subtrees after a visibility state change."
4826 (when (and (not org-cycle-open-archived-trees)
4827 (not (memq state '(overview folded))))
4828 (save-excursion
4829 (let* ((globalp (memq state '(contents all)))
4830 (beg (if globalp (point-min) (point)))
4831 (end (if globalp (point-max) (org-end-of-subtree t))))
4832 (org-hide-archived-subtrees beg end)
4833 (goto-char beg)
4834 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4835 (message "%s" (substitute-command-keys
4836 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4838 (defun org-force-cycle-archived ()
4839 "Cycle subtree even if it is archived."
4840 (interactive)
4841 (setq this-command 'org-cycle)
4842 (let ((org-cycle-open-archived-trees t))
4843 (call-interactively 'org-cycle)))
4845 (defun org-hide-archived-subtrees (beg end)
4846 "Re-hide all archived subtrees after a visibility state change."
4847 (org-with-wide-buffer
4848 (let ((case-fold-search nil)
4849 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4850 (goto-char beg)
4851 ;; Include headline point is currently on.
4852 (beginning-of-line)
4853 (while (and (< (point) end) (re-search-forward re end t))
4854 (when (member org-archive-tag (org-get-tags))
4855 (org-flag-subtree t)
4856 (org-end-of-subtree t))))))
4858 (declare-function outline-end-of-heading "outline" ())
4859 (declare-function outline-flag-region "outline" (from to flag))
4860 (defun org-flag-subtree (flag)
4861 (save-excursion
4862 (org-back-to-heading t)
4863 (outline-end-of-heading)
4864 (outline-flag-region (point)
4865 (progn (org-end-of-subtree t) (point))
4866 flag)))
4868 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4870 ;; Declare Column View Code
4872 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4873 (declare-function org-columns-compute "org-colview" (property))
4875 ;; Declare ID code
4877 (declare-function org-id-store-link "org-id")
4878 (declare-function org-id-locations-load "org-id")
4879 (declare-function org-id-locations-save "org-id")
4880 (defvar org-id-track-globally)
4882 ;;; Variables for pre-computed regular expressions, all buffer local
4884 (defvar-local org-todo-regexp nil
4885 "Matches any of the TODO state keywords.")
4886 (defvar-local org-not-done-regexp nil
4887 "Matches any of the TODO state keywords except the last one.")
4888 (defvar-local org-not-done-heading-regexp nil
4889 "Matches a TODO headline that is not done.")
4890 (defvar-local org-todo-line-regexp nil
4891 "Matches a headline and puts TODO state into group 2 if present.")
4892 (defvar-local org-complex-heading-regexp nil
4893 "Matches a headline and puts everything into groups:
4894 group 1: the stars
4895 group 2: The todo keyword, maybe
4896 group 3: Priority cookie
4897 group 4: True headline
4898 group 5: Tags")
4899 (defvar-local org-complex-heading-regexp-format nil
4900 "Printf format to make regexp to match an exact headline.
4901 This regexp will match the headline of any node which has the
4902 exact headline text that is put into the format, but may have any
4903 TODO state, priority and tags.")
4904 (defvar-local org-todo-line-tags-regexp nil
4905 "Matches a headline and puts TODO state into group 2 if present.
4906 Also put tags into group 4 if tags are present.")
4908 (defconst org-plain-time-of-day-regexp
4909 (concat
4910 "\\(\\<[012]?[0-9]"
4911 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4912 "\\(--?"
4913 "\\(\\<[012]?[0-9]"
4914 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4915 "\\)?")
4916 "Regular expression to match a plain time or time range.
4917 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4918 groups carry important information:
4919 0 the full match
4920 1 the first time, range or not
4921 8 the second time, if it is a range.")
4923 (defconst org-plain-time-extension-regexp
4924 (concat
4925 "\\(\\<[012]?[0-9]"
4926 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4927 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4928 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4929 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4930 groups carry important information:
4931 0 the full match
4932 7 hours of duration
4933 9 minutes of duration")
4935 (defconst org-stamp-time-of-day-regexp
4936 (concat
4937 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4938 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4939 "\\(--?"
4940 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4941 "Regular expression to match a timestamp time or time range.
4942 After a match, the following groups carry important information:
4943 0 the full match
4944 1 date plus weekday, for back referencing to make sure both times are on the same day
4945 2 the first time, range or not
4946 4 the second time, if it is a range.")
4948 (defconst org-startup-options
4949 '(("fold" org-startup-folded t)
4950 ("overview" org-startup-folded t)
4951 ("nofold" org-startup-folded nil)
4952 ("showall" org-startup-folded nil)
4953 ("showeverything" org-startup-folded showeverything)
4954 ("content" org-startup-folded content)
4955 ("indent" org-startup-indented t)
4956 ("noindent" org-startup-indented nil)
4957 ("hidestars" org-hide-leading-stars t)
4958 ("showstars" org-hide-leading-stars nil)
4959 ("odd" org-odd-levels-only t)
4960 ("oddeven" org-odd-levels-only nil)
4961 ("align" org-startup-align-all-tables t)
4962 ("noalign" org-startup-align-all-tables nil)
4963 ("inlineimages" org-startup-with-inline-images t)
4964 ("noinlineimages" org-startup-with-inline-images nil)
4965 ("latexpreview" org-startup-with-latex-preview t)
4966 ("nolatexpreview" org-startup-with-latex-preview nil)
4967 ("customtime" org-display-custom-times t)
4968 ("logdone" org-log-done time)
4969 ("lognotedone" org-log-done note)
4970 ("nologdone" org-log-done nil)
4971 ("lognoteclock-out" org-log-note-clock-out t)
4972 ("nolognoteclock-out" org-log-note-clock-out nil)
4973 ("logrepeat" org-log-repeat state)
4974 ("lognoterepeat" org-log-repeat note)
4975 ("logdrawer" org-log-into-drawer t)
4976 ("nologdrawer" org-log-into-drawer nil)
4977 ("logstatesreversed" org-log-states-order-reversed t)
4978 ("nologstatesreversed" org-log-states-order-reversed nil)
4979 ("nologrepeat" org-log-repeat nil)
4980 ("logreschedule" org-log-reschedule time)
4981 ("lognotereschedule" org-log-reschedule note)
4982 ("nologreschedule" org-log-reschedule nil)
4983 ("logredeadline" org-log-redeadline time)
4984 ("lognoteredeadline" org-log-redeadline note)
4985 ("nologredeadline" org-log-redeadline nil)
4986 ("logrefile" org-log-refile time)
4987 ("lognoterefile" org-log-refile note)
4988 ("nologrefile" org-log-refile nil)
4989 ("fninline" org-footnote-define-inline t)
4990 ("nofninline" org-footnote-define-inline nil)
4991 ("fnlocal" org-footnote-section nil)
4992 ("fnauto" org-footnote-auto-label t)
4993 ("fnprompt" org-footnote-auto-label nil)
4994 ("fnconfirm" org-footnote-auto-label confirm)
4995 ("fnplain" org-footnote-auto-label plain)
4996 ("fnadjust" org-footnote-auto-adjust t)
4997 ("nofnadjust" org-footnote-auto-adjust nil)
4998 ("constcgs" constants-unit-system cgs)
4999 ("constSI" constants-unit-system SI)
5000 ("noptag" org-tag-persistent-alist nil)
5001 ("hideblocks" org-hide-block-startup t)
5002 ("nohideblocks" org-hide-block-startup nil)
5003 ("beamer" org-startup-with-beamer-mode t)
5004 ("entitiespretty" org-pretty-entities t)
5005 ("entitiesplain" org-pretty-entities nil))
5006 "Variable associated with STARTUP options for org-mode.
5007 Each element is a list of three items: the startup options (as written
5008 in the #+STARTUP line), the corresponding variable, and the value to set
5009 this variable to if the option is found. An optional forth element PUSH
5010 means to push this value onto the list in the variable.")
5012 (defcustom org-group-tags t
5013 "When non-nil (the default), use group tags.
5014 This can be turned on/off through `org-toggle-tags-groups'."
5015 :group 'org-tags
5016 :group 'org-startup
5017 :type 'boolean)
5019 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5021 (defun org-toggle-tags-groups ()
5022 "Toggle support for group tags.
5023 Support for group tags is controlled by the option
5024 `org-group-tags', which is non-nil by default."
5025 (interactive)
5026 (setq org-group-tags (not org-group-tags))
5027 (cond ((and (derived-mode-p 'org-agenda-mode)
5028 org-group-tags)
5029 (org-agenda-redo))
5030 ((derived-mode-p 'org-mode)
5031 (let ((org-inhibit-startup t)) (org-mode))))
5032 (message "Groups tags support has been turned %s"
5033 (if org-group-tags "on" "off")))
5035 (defun org-set-regexps-and-options (&optional tags-only)
5036 "Precompute regular expressions used in the current buffer.
5037 When optional argument TAGS-ONLY is non-nil, only compute tags
5038 related expressions."
5039 (when (derived-mode-p 'org-mode)
5040 (let ((alist (org--setup-collect-keywords
5041 (org-make-options-regexp
5042 (append '("FILETAGS" "TAGS" "SETUPFILE")
5043 (and (not tags-only)
5044 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5045 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5046 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5047 ;; Startup options. Get this early since it does change
5048 ;; behavior for other options (e.g., tags).
5049 (let ((startup (cdr (assq 'startup alist))))
5050 (dolist (option startup)
5051 (let ((entry (assoc-string option org-startup-options t)))
5052 (when entry
5053 (let ((var (nth 1 entry))
5054 (val (nth 2 entry)))
5055 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5056 (unless (listp (symbol-value var))
5057 (set (make-local-variable var) nil))
5058 (add-to-list var val)))))))
5059 (setq-local org-file-tags
5060 (mapcar #'org-add-prop-inherited
5061 (cdr (assq 'filetags alist))))
5062 (setq org-current-tag-alist
5063 (append org-tag-persistent-alist
5064 (let ((tags (cdr (assq 'tags alist))))
5065 (if tags (org-tag-string-to-alist tags)
5066 org-tag-alist))))
5067 (setq org-tag-groups-alist
5068 (org-tag-alist-to-groups org-current-tag-alist))
5069 (unless tags-only
5070 ;; File properties.
5071 (setq-local org-file-properties (cdr (assq 'property alist)))
5072 ;; Archive location.
5073 (let ((archive (cdr (assq 'archive alist))))
5074 (when archive (setq-local org-archive-location archive)))
5075 ;; Category.
5076 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5077 (when cat
5078 (setq-local org-category (intern cat))
5079 (setq-local org-file-properties
5080 (org--update-property-plist
5081 "CATEGORY" cat org-file-properties))))
5082 ;; Columns.
5083 (let ((column (cdr (assq 'columns alist))))
5084 (when column (setq-local org-columns-default-format column)))
5085 ;; Constants.
5086 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5087 ;; Link abbreviations.
5088 (let ((links (cdr (assq 'link alist))))
5089 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5090 ;; Priorities.
5091 (let ((priorities (cdr (assq 'priorities alist))))
5092 (when priorities
5093 (setq-local org-highest-priority (nth 0 priorities))
5094 (setq-local org-lowest-priority (nth 1 priorities))
5095 (setq-local org-default-priority (nth 2 priorities))))
5096 ;; Scripts.
5097 (let ((scripts (assq 'scripts alist)))
5098 (when scripts
5099 (setq-local org-use-sub-superscripts (cdr scripts))))
5100 ;; TODO keywords.
5101 (setq-local org-todo-kwd-alist nil)
5102 (setq-local org-todo-key-alist nil)
5103 (setq-local org-todo-key-trigger nil)
5104 (setq-local org-todo-keywords-1 nil)
5105 (setq-local org-done-keywords nil)
5106 (setq-local org-todo-heads nil)
5107 (setq-local org-todo-sets nil)
5108 (setq-local org-todo-log-states nil)
5109 (let ((todo-sequences
5110 (or (nreverse (cdr (assq 'todo alist)))
5111 (let ((d (default-value 'org-todo-keywords)))
5112 (if (not (stringp (car d))) d
5113 ;; XXX: Backward compatibility code.
5114 (list (cons org-todo-interpretation d)))))))
5115 (dolist (sequence todo-sequences)
5116 (let* ((sequence (or (run-hook-with-args-until-success
5117 'org-todo-setup-filter-hook sequence)
5118 sequence))
5119 (sequence-type (car sequence))
5120 (keywords (cdr sequence))
5121 (sep (member "|" keywords))
5122 names alist)
5123 (dolist (k (remove "|" keywords))
5124 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5126 (error "Invalid TODO keyword %s" k))
5127 (let ((name (match-string 1 k))
5128 (key (match-string 2 k))
5129 (log (org-extract-log-state-settings k)))
5130 (push name names)
5131 (push (cons name (and key (string-to-char key))) alist)
5132 (when log (push log org-todo-log-states))))
5133 (let* ((names (nreverse names))
5134 (done (if sep (org-remove-keyword-keys (cdr sep))
5135 (last names)))
5136 (head (car names))
5137 (tail (list sequence-type head (car done) (org-last done))))
5138 (add-to-list 'org-todo-heads head 'append)
5139 (push names org-todo-sets)
5140 (setq org-done-keywords (append org-done-keywords done nil))
5141 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5142 (setq org-todo-key-alist
5143 (append org-todo-key-alist
5144 (and alist
5145 (append '((:startgroup))
5146 (nreverse alist)
5147 '((:endgroup))))))
5148 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5149 (setq org-todo-sets (nreverse org-todo-sets)
5150 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5151 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5152 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5153 ;; Compute the regular expressions and other local variables.
5154 ;; Using `org-outline-regexp-bol' would complicate them much,
5155 ;; because of the fixed white space at the end of that string.
5156 (unless org-done-keywords
5157 (setq org-done-keywords
5158 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5159 (setq org-not-done-keywords
5160 (org-delete-all org-done-keywords
5161 (copy-sequence org-todo-keywords-1))
5162 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5163 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5164 org-not-done-heading-regexp
5165 (format org-heading-keyword-regexp-format org-not-done-regexp)
5166 org-todo-line-regexp
5167 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5168 org-complex-heading-regexp
5169 (concat "^\\(\\*+\\)"
5170 "\\(?: +" org-todo-regexp "\\)?"
5171 "\\(?: +\\(\\[#.\\]\\)\\)?"
5172 "\\(?: +\\(.*?\\)\\)??"
5173 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5174 "[ \t]*$")
5175 org-complex-heading-regexp-format
5176 (concat "^\\(\\*+\\)"
5177 "\\(?: +" org-todo-regexp "\\)?"
5178 "\\(?: +\\(\\[#.\\]\\)\\)?"
5179 "\\(?: +"
5180 ;; Stats cookies can be stuck to body.
5181 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5182 "\\(%s\\)"
5183 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5184 "\\)"
5185 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5186 "[ \t]*$")
5187 org-todo-line-tags-regexp
5188 (concat "^\\(\\*+\\)"
5189 "\\(?: +" org-todo-regexp "\\)?"
5190 "\\(?: +\\(.*?\\)\\)??"
5191 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5192 "[ \t]*$"))
5193 (org-compute-latex-and-related-regexp)))))
5195 (defun org--setup-collect-keywords (regexp &optional files alist)
5196 "Return setup keywords values as an alist.
5198 REGEXP matches a subset of setup keywords. FILES is a list of
5199 file names already visited. It is used to avoid circular setup
5200 files. ALIST, when non-nil, is the alist computed so far.
5202 Return value contains the following keys: `archive', `category',
5203 `columns', `constants', `filetags', `link', `priorities',
5204 `property', `scripts', `startup', `tags' and `todo'."
5205 (org-with-wide-buffer
5206 (goto-char (point-min))
5207 (let ((case-fold-search t))
5208 (while (re-search-forward regexp nil t)
5209 (let ((element (org-element-at-point)))
5210 (when (eq (org-element-type element) 'keyword)
5211 (let ((key (org-element-property :key element))
5212 (value (org-element-property :value element)))
5213 (cond
5214 ((equal key "ARCHIVE")
5215 (when (org-string-nw-p value)
5216 (push (cons 'archive value) alist)))
5217 ((equal key "CATEGORY") (push (cons 'category value) alist))
5218 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5219 ((equal key "CONSTANTS")
5220 (let* ((constants (assq 'constants alist))
5221 (store (cdr constants)))
5222 (dolist (pair (org-split-string value))
5223 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5224 pair)
5225 (let* ((name (match-string 1 pair))
5226 (value (match-string 2 pair))
5227 (old (assoc name store)))
5228 (if old (setcdr old value)
5229 (push (cons name value) store)))))
5230 (if constants (setcdr constants store)
5231 (push (cons 'constants store) alist))))
5232 ((equal key "FILETAGS")
5233 (when (org-string-nw-p value)
5234 (let ((old (assq 'filetags alist))
5235 (new (apply #'nconc
5236 (mapcar (lambda (x) (org-split-string x ":"))
5237 (org-split-string value)))))
5238 (if old (setcdr old (append new (cdr old)))
5239 (push (cons 'filetags new) alist)))))
5240 ((equal key "LINK")
5241 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5242 (let ((links (assq 'link alist))
5243 (pair (cons (match-string-no-properties 1 value)
5244 (match-string-no-properties 2 value))))
5245 (if links (push pair (cdr links))
5246 (push (list 'link pair) alist)))))
5247 ((equal key "OPTIONS")
5248 (when (and (org-string-nw-p value)
5249 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5250 (push (cons 'scripts (read (match-string 1 value))) alist)))
5251 ((equal key "PRIORITIES")
5252 (push (cons 'priorities
5253 (let ((prio (org-split-string value)))
5254 (if (< (length prio) 3) '(?A ?C ?B)
5255 (mapcar #'string-to-char prio))))
5256 alist))
5257 ((equal key "PROPERTY")
5258 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5259 (let* ((property (assq 'property alist))
5260 (value (org--update-property-plist
5261 (match-string-no-properties 1 value)
5262 (match-string-no-properties 2 value)
5263 (cdr property))))
5264 (if property (setcdr property value)
5265 (push (cons 'property value) alist)))))
5266 ((equal key "STARTUP")
5267 (let ((startup (assq 'startup alist)))
5268 (if startup
5269 (setcdr startup
5270 (append (cdr startup) (org-split-string value)))
5271 (push (cons 'startup (org-split-string value)) alist))))
5272 ((equal key "TAGS")
5273 (let ((tag-cell (assq 'tags alist)))
5274 (if tag-cell
5275 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5276 (push (cons 'tags value) alist))))
5277 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5278 (let ((todo (assq 'todo alist))
5279 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5280 (org-split-string value))))
5281 (if todo (push value (cdr todo))
5282 (push (list 'todo value) alist))))
5283 ((equal key "SETUPFILE")
5284 (unless buffer-read-only ; Do not check in Gnus messages.
5285 (let ((f (and (org-string-nw-p value)
5286 (expand-file-name
5287 (org-unbracket-string "\"" "\"" value)))))
5288 (when (and f (file-readable-p f) (not (member f files)))
5289 (with-temp-buffer
5290 (setq default-directory (file-name-directory f))
5291 (insert-file-contents f)
5292 (setq alist
5293 ;; Fake Org mode to benefit from cache
5294 ;; without recurring needlessly.
5295 (let ((major-mode 'org-mode))
5296 (org--setup-collect-keywords
5297 regexp (cons f files) alist)))))))))))))))
5298 alist)
5300 (defun org-tag-string-to-alist (s)
5301 "Return tag alist associated to string S.
5302 S is a value for TAGS keyword or produced with
5303 `org-tag-alist-to-string'. Return value is an alist suitable for
5304 `org-tag-alist' or `org-tag-persistent-alist'."
5305 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5306 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5307 "\\|{.+?}\\)" ; regular expression
5308 "\\(?:(\\(.\\))\\)?\\'"))
5309 alist group-flag)
5310 (dolist (tokens lines (cdr (nreverse alist)))
5311 (push '(:newline) alist)
5312 (while tokens
5313 (let ((token (pop tokens)))
5314 (pcase token
5315 ("{"
5316 (push '(:startgroup) alist)
5317 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5318 ("}"
5319 (push '(:endgroup) alist)
5320 (setq group-flag nil))
5321 ("["
5322 (push '(:startgrouptag) alist)
5323 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5324 ("]"
5325 (push '(:endgrouptag) alist)
5326 (setq group-flag nil))
5327 (":"
5328 (push '(:grouptags) alist))
5329 ((guard (string-match tag-re token))
5330 (let ((tag (match-string 1 token))
5331 (key (and (match-beginning 2)
5332 (string-to-char (match-string 2 token)))))
5333 ;; Push all tags in groups, no matter if they already
5334 ;; appear somewhere else in the list.
5335 (when (or group-flag (not (assoc tag alist)))
5336 (push (cons tag key) alist))))))))))
5338 (defun org-tag-alist-to-string (alist &optional skip-key)
5339 "Return tag string associated to ALIST.
5341 ALIST is an alist, as defined in `org-tag-alist' or
5342 `org-tag-persistent-alist', or produced with
5343 `org-tag-string-to-alist'.
5345 Return value is a string suitable as a value for \"TAGS\"
5346 keyword.
5348 When optional argument SKIP-KEY is non-nil, skip selection keys
5349 next to tags."
5350 (mapconcat (lambda (token)
5351 (pcase token
5352 (`(:startgroup) "{")
5353 (`(:endgroup) "}")
5354 (`(:startgrouptag) "[")
5355 (`(:endgrouptag) "]")
5356 (`(:grouptags) ":")
5357 (`(:newline) "\\n")
5358 ((and
5359 (guard (not skip-key))
5360 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5361 (format "%s(%c)" tag key))
5362 (`(,(and tag (pred stringp)) . ,_) tag)
5363 (_ (user-error "Invalid tag token: %S" token))))
5364 alist
5365 " "))
5367 (defun org-tag-alist-to-groups (alist)
5368 "Return group alist from tag ALIST.
5369 ALIST is an alist, as defined in `org-tag-alist' or
5370 `org-tag-persistent-alist', or produced with
5371 `org-tag-string-to-alist'. Return value is an alist following
5372 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5373 a string, summarizing TAGS, as a list of strings."
5374 (let (groups group-status current-group)
5375 (dolist (token alist (nreverse groups))
5376 (pcase token
5377 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5378 (`(,(or :endgroup :endgrouptag))
5379 (when (eq group-status 'append)
5380 (push (nreverse current-group) groups))
5381 (setq group-status nil))
5382 (`(:grouptags) (setq group-status 'append))
5383 ((and `(,tag . ,_) (guard group-status))
5384 (if (eq group-status 'append) (push tag current-group)
5385 (setq current-group (list tag))))
5386 (_ nil)))))
5388 (defun org-file-contents (file &optional noerror)
5389 "Return the contents of FILE, as a string."
5390 (if (and file (file-readable-p file))
5391 (with-temp-buffer
5392 (insert-file-contents file)
5393 (buffer-string))
5394 (funcall (if noerror 'message 'error)
5395 "Cannot read file \"%s\"%s"
5396 file
5397 (let ((from (buffer-file-name (buffer-base-buffer))))
5398 (if from (concat " (referenced in file \"" from "\")") "")))))
5400 (defun org-extract-log-state-settings (x)
5401 "Extract the log state setting from a TODO keyword string.
5402 This will extract info from a string like \"WAIT(w@/!)\"."
5403 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5404 (let ((kw (match-string 1 x))
5405 (log1 (and (match-end 3) (match-string 3 x)))
5406 (log2 (and (match-end 4) (match-string 4 x))))
5407 (and (or log1 log2)
5408 (list kw
5409 (and log1 (if (equal log1 "!") 'time 'note))
5410 (and log2 (if (equal log2 "!") 'time 'note)))))))
5412 (defun org-remove-keyword-keys (list)
5413 "Remove a pair of parenthesis at the end of each string in LIST."
5414 (mapcar (lambda (x)
5415 (if (string-match "(.*)$" x)
5416 (substring x 0 (match-beginning 0))
5418 list))
5420 (defun org-assign-fast-keys (alist)
5421 "Assign fast keys to a keyword-key alist.
5422 Respect keys that are already there."
5423 (let (new e (alt ?0))
5424 (while (setq e (pop alist))
5425 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5426 (cdr e)) ;; Key already assigned.
5427 (push e new)
5428 (let ((clist (string-to-list (downcase (car e))))
5429 (used (append new alist)))
5430 (when (= (car clist) ?@)
5431 (pop clist))
5432 (while (and clist (rassoc (car clist) used))
5433 (pop clist))
5434 (unless clist
5435 (while (rassoc alt used)
5436 (cl-incf alt)))
5437 (push (cons (car e) (or (car clist) alt)) new))))
5438 (nreverse new)))
5440 ;;; Some variables used in various places
5442 (defvar org-window-configuration nil
5443 "Used in various places to store a window configuration.")
5444 (defvar org-selected-window nil
5445 "Used in various places to store a window configuration.")
5446 (defvar org-finish-function nil
5447 "Function to be called when `C-c C-c' is used.
5448 This is for getting out of special buffers like capture.")
5449 (defvar org-last-state)
5451 ;; Defined somewhere in this file, but used before definition.
5452 (defvar org-entities) ;; defined in org-entities.el
5453 (defvar org-struct-menu)
5454 (defvar org-org-menu)
5455 (defvar org-tbl-menu)
5457 ;;;; Define the Org mode
5459 ;; We use a before-change function to check if a table might need
5460 ;; an update.
5461 (defvar org-table-may-need-update t
5462 "Indicates that a table might need an update.
5463 This variable is set by `org-before-change-function'.
5464 `org-table-align' sets it back to nil.")
5465 (defun org-before-change-function (_beg _end)
5466 "Every change indicates that a table might need an update."
5467 (setq org-table-may-need-update t))
5468 (defvar org-mode-map)
5469 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5470 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5471 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5472 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5473 (defvar org-table-buffer-is-an nil)
5475 (defvar bidi-paragraph-direction)
5476 (defvar buffer-face-mode-face)
5478 (require 'outline)
5480 ;; Other stuff we need.
5481 (require 'time-date)
5482 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5483 (require 'easymenu)
5484 (autoload 'easy-menu-add "easymenu")
5485 (require 'overlay)
5487 ;; (require 'org-macs) moved higher up in the file before it is first used
5488 (require 'org-entities)
5489 ;; (require 'org-compat) moved higher up in the file before it is first used
5490 (require 'org-faces)
5491 (require 'org-list)
5492 (require 'org-pcomplete)
5493 (require 'org-src)
5494 (require 'org-footnote)
5495 (require 'org-macro)
5497 ;; babel
5498 (require 'ob)
5500 ;;;###autoload
5501 (define-derived-mode org-mode outline-mode "Org"
5502 "Outline-based notes management and organizer, alias
5503 \"Carsten's outline-mode for keeping track of everything.\"
5505 Org mode develops organizational tasks around a NOTES file which
5506 contains information about projects as plain text. Org mode is
5507 implemented on top of Outline mode, which is ideal to keep the content
5508 of large files well structured. It supports ToDo items, deadlines and
5509 time stamps, which magically appear in the diary listing of the Emacs
5510 calendar. Tables are easily created with a built-in table editor.
5511 Plain text URL-like links connect to websites, emails (VM), Usenet
5512 messages (Gnus), BBDB entries, and any files related to the project.
5513 For printing and sharing of notes, an Org file (or a part of it)
5514 can be exported as a structured ASCII or HTML file.
5516 The following commands are available:
5518 \\{org-mode-map}"
5520 ;; Get rid of Outline menus, they are not needed
5521 ;; Need to do this here because define-derived-mode sets up
5522 ;; the keymap so late. Still, it is a waste to call this each time
5523 ;; we switch another buffer into Org mode.
5524 (define-key org-mode-map [menu-bar headings] 'undefined)
5525 (define-key org-mode-map [menu-bar hide] 'undefined)
5526 (define-key org-mode-map [menu-bar show] 'undefined)
5528 (org-load-modules-maybe)
5529 (org-install-agenda-files-menu)
5530 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5531 (add-to-invisibility-spec '(org-cwidth))
5532 (add-to-invisibility-spec '(org-hide-block . t))
5533 (setq-local outline-regexp org-outline-regexp)
5534 (setq-local outline-level 'org-outline-level)
5535 (setq bidi-paragraph-direction 'left-to-right)
5536 (when (and org-ellipsis
5537 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5538 (fboundp 'make-glyph-code))
5539 (unless org-display-table
5540 (setq org-display-table (make-display-table)))
5541 (set-display-table-slot
5542 org-display-table 4
5543 (vconcat (mapcar
5544 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5545 org-ellipsis)))
5546 (if (stringp org-ellipsis) org-ellipsis "..."))))
5547 (setq buffer-display-table org-display-table))
5548 (org-set-regexps-and-options)
5549 (org-set-font-lock-defaults)
5550 (when (and org-tag-faces (not org-tags-special-faces-re))
5551 ;; tag faces set outside customize.... force initialization.
5552 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5553 ;; Calc embedded
5554 (setq-local calc-embedded-open-mode "# ")
5555 ;; Modify a few syntax entries
5556 (modify-syntax-entry ?@ "w")
5557 (modify-syntax-entry ?\" "\"")
5558 (modify-syntax-entry ?\\ "_")
5559 (modify-syntax-entry ?~ "_")
5560 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5561 ;; Activate before-change-function
5562 (setq-local org-table-may-need-update t)
5563 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5564 ;; Check for running clock before killing a buffer
5565 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5566 ;; Initialize macros templates.
5567 (org-macro-initialize-templates)
5568 ;; Initialize radio targets.
5569 (org-update-radio-target-regexp)
5570 ;; Indentation.
5571 (setq-local indent-line-function 'org-indent-line)
5572 (setq-local indent-region-function 'org-indent-region)
5573 ;; Filling and auto-filling.
5574 (org-setup-filling)
5575 ;; Comments.
5576 (org-setup-comments-handling)
5577 ;; Initialize cache.
5578 (org-element-cache-reset)
5579 ;; Beginning/end of defun
5580 (setq-local beginning-of-defun-function 'org-backward-element)
5581 (setq-local end-of-defun-function
5582 (lambda ()
5583 (if (not (org-at-heading-p))
5584 (org-forward-element)
5585 (org-forward-element)
5586 (forward-char -1))))
5587 ;; Next error for sparse trees
5588 (setq-local next-error-function 'org-occur-next-match)
5589 ;; Make sure dependence stuff works reliably, even for users who set it
5590 ;; too late :-(
5591 (if org-enforce-todo-dependencies
5592 (add-hook 'org-blocker-hook
5593 'org-block-todo-from-children-or-siblings-or-parent)
5594 (remove-hook 'org-blocker-hook
5595 'org-block-todo-from-children-or-siblings-or-parent))
5596 (if org-enforce-todo-checkbox-dependencies
5597 (add-hook 'org-blocker-hook
5598 'org-block-todo-from-checkboxes)
5599 (remove-hook 'org-blocker-hook
5600 'org-block-todo-from-checkboxes))
5602 ;; Align options lines
5603 (setq-local
5604 align-mode-rules-list
5605 '((org-in-buffer-settings
5606 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5607 (modes . '(org-mode)))))
5609 ;; Imenu
5610 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5612 ;; Make isearch reveal context
5613 (setq-local outline-isearch-open-invisible-function
5614 (lambda (&rest _) (org-show-context 'isearch)))
5616 ;; Setup the pcomplete hooks
5617 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5618 (setq-local pcomplete-command-name-function 'org-command-at-point)
5619 (setq-local pcomplete-default-completion-function 'ignore)
5620 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5621 (setq-local pcomplete-termination-string "")
5622 (setq-local buffer-face-mode-face 'org-default)
5624 ;; If empty file that did not turn on Org mode automatically, make
5625 ;; it to.
5626 (when (and org-insert-mode-line-in-empty-file
5627 (called-interactively-p 'any)
5628 (= (point-min) (point-max)))
5629 (insert "# -*- mode: org -*-\n\n"))
5630 (unless org-inhibit-startup
5631 (org-unmodified
5632 (when org-startup-with-beamer-mode (org-beamer-mode))
5633 (when org-startup-align-all-tables
5634 (org-table-map-tables #'org-table-align t))
5635 (when org-startup-with-inline-images (org-display-inline-images))
5636 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5637 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5638 (when org-startup-truncated (setq truncate-lines t))
5639 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5640 (org-refresh-effort-properties)))
5641 ;; Try to set `org-hide' face correctly.
5642 (let ((foreground (org-find-invisible-foreground)))
5643 (when foreground
5644 (set-face-foreground 'org-hide foreground))))
5646 ;; Update `customize-package-emacs-version-alist'
5647 (add-to-list 'customize-package-emacs-version-alist
5648 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5649 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5650 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5651 ("9.0" . "25.2")))
5653 (defvar org-mode-transpose-word-syntax-table
5654 (let ((st (make-syntax-table text-mode-syntax-table)))
5655 (dolist (c org-emphasis-alist st)
5656 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5658 (when (fboundp 'abbrev-table-put)
5659 (abbrev-table-put org-mode-abbrev-table
5660 :parents (list text-mode-abbrev-table)))
5662 (defun org-find-invisible-foreground ()
5663 (let ((candidates (remove
5664 "unspecified-bg"
5665 (nconc
5666 (list (face-background 'default)
5667 (face-background 'org-default))
5668 (mapcar
5669 (lambda (alist)
5670 (when (boundp alist)
5671 (cdr (assq 'background-color (symbol-value alist)))))
5672 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5673 (list (face-foreground 'org-hide))))))
5674 (car (remove nil candidates))))
5676 (defun org-current-time (&optional rounding-minutes past)
5677 "Current time, possibly rounded to ROUNDING-MINUTES.
5678 When ROUNDING-MINUTES is not an integer, fall back on the car of
5679 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5680 the rounding returns a past time."
5681 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5682 (car org-time-stamp-rounding-minutes)))
5683 (time (decode-time)) res)
5684 (if (< r 1)
5685 (current-time)
5686 (setq res
5687 (apply 'encode-time
5688 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5689 (nthcdr 2 time))))
5690 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5691 (seconds-to-time (- (float-time res) (* r 60)))
5692 res))))
5694 (defun org-today ()
5695 "Return today date, considering `org-extend-today-until'."
5696 (time-to-days
5697 (time-subtract (current-time)
5698 (list 0 (* 3600 org-extend-today-until) 0))))
5700 ;;;; Font-Lock stuff, including the activators
5702 (defvar org-mouse-map (make-sparse-keymap))
5703 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5704 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5705 (when org-mouse-1-follows-link
5706 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5707 (when org-tab-follows-link
5708 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5709 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5711 (require 'font-lock)
5713 (defconst org-non-link-chars "]\t\n\r<>")
5714 (defvar org-link-types-re nil
5715 "Matches a link that has a url-like prefix like \"http:\"")
5716 (defvar org-link-re-with-space nil
5717 "Matches a link with spaces, optional angular brackets around it.")
5718 (defvar org-link-re-with-space2 nil
5719 "Matches a link with spaces, optional angular brackets around it.")
5720 (defvar org-link-re-with-space3 nil
5721 "Matches a link with spaces, only for internal part in bracket links.")
5722 (defvar org-angle-link-re nil
5723 "Matches link with angular brackets, spaces are allowed.")
5724 (defvar org-plain-link-re nil
5725 "Matches plain link, without spaces.")
5726 (defvar org-bracket-link-regexp nil
5727 "Matches a link in double brackets.")
5728 (defvar org-bracket-link-analytic-regexp nil
5729 "Regular expression used to analyze links.
5730 Here is what the match groups contain after a match:
5731 1: http:
5732 2: http
5733 3: path
5734 4: [desc]
5735 5: desc")
5736 (defvar org-bracket-link-analytic-regexp++ nil
5737 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5738 (defvar org-any-link-re nil
5739 "Regular expression matching any link.")
5741 (defconst org-match-sexp-depth 3
5742 "Number of stacked braces for sub/superscript matching.")
5744 (defun org-create-multibrace-regexp (left right n)
5745 "Create a regular expression which will match a balanced sexp.
5746 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5747 as single character strings.
5748 The regexp returned will match the entire expression including the
5749 delimiters. It will also define a single group which contains the
5750 match except for the outermost delimiters. The maximum depth of
5751 stacked delimiters is N. Escaping delimiters is not possible."
5752 (let* ((nothing (concat "[^" left right "]*?"))
5753 (or "\\|")
5754 (re nothing)
5755 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5756 (while (> n 1)
5757 (setq n (1- n)
5758 re (concat re or next)
5759 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5760 (concat left "\\(" re "\\)" right)))
5762 (defconst org-match-substring-regexp
5763 (concat
5764 "\\(\\S-\\)\\([_^]\\)\\("
5765 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5766 "\\|"
5767 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5768 "\\|"
5769 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5770 "The regular expression matching a sub- or superscript.")
5772 (defconst org-match-substring-with-braces-regexp
5773 (concat
5774 "\\(\\S-\\)\\([_^]\\)"
5775 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5776 "The regular expression matching a sub- or superscript, forcing braces.")
5778 (defun org-make-link-regexps ()
5779 "Update the link regular expressions.
5780 This should be called after the variable `org-link-parameters' has changed."
5781 (let ((types-re (regexp-opt (org-link-types) t)))
5782 (setq org-link-types-re
5783 (concat "\\`" types-re ":")
5784 org-link-re-with-space
5785 (concat "<?" types-re ":"
5786 "\\([^" org-non-link-chars " ]"
5787 "[^" org-non-link-chars "]*"
5788 "[^" org-non-link-chars " ]\\)>?")
5789 org-link-re-with-space2
5790 (concat "<?" types-re ":"
5791 "\\([^" org-non-link-chars " ]"
5792 "[^\t\n\r]*"
5793 "[^" org-non-link-chars " ]\\)>?")
5794 org-link-re-with-space3
5795 (concat "<?" types-re ":"
5796 "\\([^" org-non-link-chars " ]"
5797 "[^\t\n\r]*\\)")
5798 org-angle-link-re
5799 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5800 types-re)
5801 org-plain-link-re
5802 (concat
5803 "\\<" types-re ":"
5804 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5805 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5806 org-bracket-link-regexp
5807 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5808 org-bracket-link-analytic-regexp
5809 (concat
5810 "\\[\\["
5811 "\\(" types-re ":\\)?"
5812 "\\([^]]+\\)"
5813 "\\]"
5814 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5815 "\\]")
5816 org-bracket-link-analytic-regexp++
5817 (concat
5818 "\\[\\["
5819 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5820 "\\([^]]+\\)"
5821 "\\]"
5822 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5823 "\\]")
5824 org-any-link-re
5825 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5826 org-angle-link-re "\\)\\|\\("
5827 org-plain-link-re "\\)"))))
5829 (org-make-link-regexps)
5831 (defvar org-emph-face nil)
5833 (defun org-do-emphasis-faces (limit)
5834 "Run through the buffer and emphasize strings."
5835 (let (rtn a)
5836 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5837 (let* ((border (char-after (match-beginning 3)))
5838 (bre (regexp-quote (char-to-string border))))
5839 (when (and (not (= border (char-after (match-beginning 4))))
5840 (not (string-match-p (concat bre ".*" bre)
5841 (replace-regexp-in-string
5842 "\n" " "
5843 (substring (match-string 2) 1 -1)))))
5844 (setq rtn t)
5845 (setq a (assoc (match-string 3) org-emphasis-alist))
5846 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5847 'face
5848 (nth 1 a))
5849 (and (nth 2 a)
5850 (org-remove-flyspell-overlays-in
5851 (match-beginning 0) (match-end 0)))
5852 (add-text-properties (match-beginning 2) (match-end 2)
5853 '(font-lock-multiline t org-emphasis t))
5854 (when org-hide-emphasis-markers
5855 (add-text-properties (match-end 4) (match-beginning 5)
5856 '(invisible org-link))
5857 (add-text-properties (match-beginning 3) (match-end 3)
5858 '(invisible org-link)))))
5859 (goto-char (1+ (match-beginning 0))))
5860 rtn))
5862 (defun org-emphasize (&optional char)
5863 "Insert or change an emphasis, i.e. a font like bold or italic.
5864 If there is an active region, change that region to a new emphasis.
5865 If there is no region, just insert the marker characters and position
5866 the cursor between them.
5867 CHAR should be the marker character. If it is a space, it means to
5868 remove the emphasis of the selected region.
5869 If CHAR is not given (for example in an interactive call) it will be
5870 prompted for."
5871 (interactive)
5872 (let ((erc org-emphasis-regexp-components)
5873 (string "") beg end move s)
5874 (if (org-region-active-p)
5875 (setq beg (region-beginning)
5876 end (region-end)
5877 string (buffer-substring beg end))
5878 (setq move t))
5880 (unless char
5881 (message "Emphasis marker or tag: [%s]"
5882 (mapconcat #'car org-emphasis-alist ""))
5883 (setq char (read-char-exclusive)))
5884 (if (equal char ?\s)
5885 (setq s ""
5886 move nil)
5887 (unless (assoc (char-to-string char) org-emphasis-alist)
5888 (user-error "No such emphasis marker: \"%c\"" char))
5889 (setq s (char-to-string char)))
5890 (while (and (> (length string) 1)
5891 (equal (substring string 0 1) (substring string -1))
5892 (assoc (substring string 0 1) org-emphasis-alist))
5893 (setq string (substring string 1 -1)))
5894 (setq string (concat s string s))
5895 (when beg (delete-region beg end))
5896 (unless (or (bolp)
5897 (string-match (concat "[" (nth 0 erc) "\n]")
5898 (char-to-string (char-before (point)))))
5899 (insert " "))
5900 (unless (or (eobp)
5901 (string-match (concat "[" (nth 1 erc) "\n]")
5902 (char-to-string (char-after (point)))))
5903 (insert " ") (backward-char 1))
5904 (insert string)
5905 (and move (backward-char 1))))
5907 (defconst org-nonsticky-props
5908 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5910 (defsubst org-rear-nonsticky-at (pos)
5911 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5913 (defun org-activate-plain-links (limit)
5914 "Add link properties for plain links."
5915 (when (and (re-search-forward org-plain-link-re limit t)
5916 (not (org-in-src-block-p)))
5918 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5919 'face))
5920 (link (match-string-no-properties 0))
5921 (type (match-string-no-properties 1))
5922 (path (match-string-no-properties 2))
5923 (link-start (match-beginning 0))
5924 (link-end (match-end 0))
5925 (link-face (org-link-get-parameter type :face))
5926 (help-echo (org-link-get-parameter type :help-echo))
5927 (htmlize-link (org-link-get-parameter type :htmlize-link))
5928 (activate-func (org-link-get-parameter type :activate-func)))
5929 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5930 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5931 (add-text-properties (match-beginning 0) (match-end 0)
5932 (list
5933 'mouse-face (or (org-link-get-parameter type :mouse-face)
5934 'highlight)
5935 'face (cond
5936 ;; A function that returns a face
5937 ((functionp link-face)
5938 (funcall link-face path))
5939 ;; a face
5940 ((facep link-face)
5941 link-face)
5942 ;; An anonymous face
5943 ((consp link-face)
5944 link-face)
5945 ;; default
5947 'org-link))
5948 'help-echo (cond
5949 ((stringp help-echo)
5950 help-echo)
5951 ((functionp help-echo)
5952 help-echo)
5954 (concat "LINK: "
5955 (save-match-data
5956 (org-link-unescape link)))))
5957 'htmlize-link (cond
5958 ((functionp htmlize-link)
5959 (funcall htmlize-link path))
5961 `(:uri ,link)))
5962 'keymap (or (org-link-get-parameter type :keymap)
5963 org-mouse-map)
5964 'org-link-start (match-beginning 0)))
5965 (org-rear-nonsticky-at (match-end 0))
5966 (when activate-func
5967 (funcall activate-func link-start link-end path nil))
5968 t))))
5970 (defun org-activate-code (limit)
5971 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5972 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5973 (remove-text-properties (match-beginning 0) (match-end 0)
5974 '(display t invisible t intangible t))
5977 (defcustom org-src-fontify-natively t
5978 "When non-nil, fontify code in code blocks.
5979 See also the `org-block' face."
5980 :type 'boolean
5981 :version "24.4"
5982 :package-version '(Org . "8.3")
5983 :group 'org-appearance
5984 :group 'org-babel)
5986 (defcustom org-allow-promoting-top-level-subtree nil
5987 "When non-nil, allow promoting a top level subtree.
5988 The leading star of the top level headline will be replaced
5989 by a #."
5990 :type 'boolean
5991 :version "24.1"
5992 :group 'org-appearance)
5994 (defun org-fontify-meta-lines-and-blocks (limit)
5995 (condition-case nil
5996 (org-fontify-meta-lines-and-blocks-1 limit)
5997 (error (message "org-mode fontification error in %S at %d"
5998 (current-buffer)
5999 (line-number-at-pos)))))
6001 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6002 "Fontify #+ lines and blocks."
6003 (let ((case-fold-search t))
6004 (when (re-search-forward
6005 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6006 limit t)
6007 (let ((beg (match-beginning 0))
6008 (block-start (match-end 0))
6009 (block-end nil)
6010 (lang (match-string 7))
6011 (beg1 (line-beginning-position 2))
6012 (dc1 (downcase (match-string 2)))
6013 (dc3 (downcase (match-string 3)))
6014 end end1 quoting block-type)
6015 (cond
6016 ((and (match-end 4) (equal dc3 "+begin"))
6017 ;; Truly a block
6018 (setq block-type (downcase (match-string 5))
6019 quoting (member block-type org-protecting-blocks))
6020 (when (re-search-forward
6021 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6022 nil t) ;; on purpose, we look further than LIMIT
6023 (setq end (min (point-max) (match-end 0))
6024 end1 (min (point-max) (1- (match-beginning 0))))
6025 (setq block-end (match-beginning 0))
6026 (when quoting
6027 (org-remove-flyspell-overlays-in beg1 end1)
6028 (remove-text-properties beg end
6029 '(display t invisible t intangible t)))
6030 (add-text-properties
6031 beg end '(font-lock-fontified t font-lock-multiline t))
6032 (add-text-properties beg beg1 '(face org-meta-line))
6033 (org-remove-flyspell-overlays-in beg beg1)
6034 (add-text-properties ; For end_src
6035 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6036 (org-remove-flyspell-overlays-in end1 end)
6037 (cond
6038 ((and lang (not (string= lang "")) org-src-fontify-natively)
6039 (org-src-font-lock-fontify-block lang block-start block-end)
6040 (add-text-properties beg1 block-end '(src-block t)))
6041 (quoting
6042 (add-text-properties beg1 (min (point-max) (1+ end1))
6043 (list 'face
6044 (list :inherit
6045 (let ((face-name
6046 (intern (format "org-block-%s" lang))))
6047 (append (and (facep face-name) (list face-name))
6048 '(org-block))))))) ; end of source block
6049 ((not org-fontify-quote-and-verse-blocks))
6050 ((string= block-type "quote")
6051 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6052 ((string= block-type "verse")
6053 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6054 (add-text-properties beg beg1 '(face org-block-begin-line))
6055 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6056 '(face org-block-end-line))
6058 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6059 (org-remove-flyspell-overlays-in
6060 (match-beginning 0)
6061 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6062 (add-text-properties
6063 beg (match-end 3)
6064 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6065 '(font-lock-fontified t invisible t)
6066 '(font-lock-fontified t face org-document-info-keyword)))
6067 (add-text-properties
6068 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6069 (if (string-equal dc1 "+title:")
6070 '(font-lock-fontified t face org-document-title)
6071 '(font-lock-fontified t face org-document-info))))
6072 ((equal dc1 "+caption:")
6073 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6074 (remove-text-properties (match-beginning 0) (match-end 0)
6075 '(display t invisible t intangible t))
6076 (add-text-properties (match-beginning 1) (match-end 3)
6077 '(font-lock-fontified t face org-meta-line))
6078 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6079 '(font-lock-fontified t face org-block))
6081 ((member dc3 '(" " ""))
6082 (org-remove-flyspell-overlays-in beg (match-end 0))
6083 (add-text-properties
6084 beg (match-end 0)
6085 '(font-lock-fontified t face font-lock-comment-face)))
6086 (t ;; just any other in-buffer setting, but not indented
6087 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6088 (remove-text-properties (match-beginning 0) (match-end 0)
6089 '(display t invisible t intangible t))
6090 (add-text-properties beg (match-end 0)
6091 '(font-lock-fontified t face org-meta-line))
6092 t))))))
6094 (defun org-fontify-drawers (limit)
6095 "Fontify drawers."
6096 (when (re-search-forward org-drawer-regexp limit t)
6097 (add-text-properties
6098 (match-beginning 0) (match-end 0)
6099 '(font-lock-fontified t face org-special-keyword))
6100 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6103 (defun org-fontify-macros (limit)
6104 "Fontify macros."
6105 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6106 (add-text-properties
6107 (match-beginning 0) (match-end 0)
6108 '(font-lock-fontified t face org-macro))
6109 (when org-hide-macro-markers
6110 (add-text-properties (match-end 2) (match-beginning 2)
6111 '(invisible t))
6112 (add-text-properties (match-beginning 1) (match-end 1)
6113 '(invisible t)))
6114 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6117 (defun org-activate-angle-links (limit)
6118 "Add text properties for angle links."
6119 (when (and (re-search-forward org-angle-link-re limit t)
6120 (not (org-in-src-block-p)))
6121 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6122 (add-text-properties (match-beginning 0) (match-end 0)
6123 (list 'mouse-face 'highlight
6124 'keymap org-mouse-map
6125 'font-lock-multiline t))
6126 (org-rear-nonsticky-at (match-end 0))
6129 (defun org-activate-footnote-links (limit)
6130 "Add text properties for footnotes."
6131 (let ((fn (org-footnote-next-reference-or-definition limit)))
6132 (when fn
6133 (let* ((beg (nth 1 fn))
6134 (end (nth 2 fn))
6135 (label (car fn))
6136 (referencep (/= (line-beginning-position) beg)))
6137 (when (and referencep (nth 3 fn))
6138 (save-excursion
6139 (goto-char beg)
6140 (search-forward (or label "fn:"))
6141 (org-remove-flyspell-overlays-in beg (match-end 0))))
6142 (add-text-properties beg end
6143 (list 'mouse-face 'highlight
6144 'keymap org-mouse-map
6145 'help-echo
6146 (if referencep "Footnote reference"
6147 "Footnote definition")
6148 'font-lock-fontified t
6149 'font-lock-multiline t
6150 'face 'org-footnote))))))
6152 (defun org-activate-bracket-links (limit)
6153 "Add text properties for bracketed links."
6154 (when (and (re-search-forward org-bracket-link-regexp limit t)
6155 (not (org-in-src-block-p)))
6156 (let* ((hl (save-match-data
6157 (org-link-expand-abbrev (match-string-no-properties 1))))
6158 (type (save-match-data
6159 (and (string-match org-plain-link-re hl)
6160 (match-string-no-properties 1 hl))))
6161 (path (save-match-data
6162 (and (string-match org-plain-link-re hl)
6163 (match-string-no-properties 2 hl))))
6164 (link-start (match-beginning 0))
6165 (link-end (match-end 0))
6166 (bracketp t)
6167 (help-echo (org-link-get-parameter type :help-echo))
6168 (help (cond
6169 ((stringp help-echo)
6170 help-echo)
6171 ((functionp help-echo)
6172 help-echo)
6174 (concat "LINK: "
6175 (save-match-data
6176 (org-link-unescape hl))))))
6177 (link-face (org-link-get-parameter type :face))
6178 (face (cond
6179 ;; A function that returns a face
6180 ((functionp link-face)
6181 (funcall link-face path))
6182 ;; a face
6183 ((facep link-face)
6184 link-face)
6185 ;; An anonymous face
6186 ((consp link-face)
6187 link-face)
6188 ;; default
6190 'org-link)))
6191 (keymap (or (org-link-get-parameter type :keymap)
6192 org-mouse-map))
6193 (mouse-face (or (org-link-get-parameter type :mouse-face)
6194 'highlight))
6195 (htmlize (org-link-get-parameter type :htmlize-link))
6196 (htmlize-link (cond
6197 ((functionp htmlize)
6198 (funcall htmlize))
6200 `(:uri ,(format "%s:%s" type path)))))
6201 (activate-func (org-link-get-parameter type :activate-func))
6202 ;; invisible part
6203 (ip (list 'invisible (or
6204 (org-link-get-parameter type :display)
6205 'org-link)
6206 'face face
6207 'keymap keymap
6208 'mouse-face mouse-face
6209 'font-lock-multiline t
6210 'help-echo help
6211 'htmlize-link htmlize-link))
6212 ;; visible part
6213 (vp (list 'keymap keymap
6214 'face face
6215 'mouse-face mouse-face
6216 'font-lock-multiline t
6217 'help-echo help
6218 'htmlize-link htmlize-link)))
6219 ;; We need to remove the invisible property here. Table narrowing
6220 ;; may have made some of this invisible.
6221 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6222 (remove-text-properties (match-beginning 0) (match-end 0)
6223 '(invisible nil))
6224 (if (match-end 3)
6225 (progn
6226 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6227 (org-rear-nonsticky-at (match-beginning 3))
6228 (add-text-properties (match-beginning 3) (match-end 3) vp)
6229 (org-rear-nonsticky-at (match-end 3))
6230 (add-text-properties (match-end 3) (match-end 0) ip)
6231 (org-rear-nonsticky-at (match-end 0)))
6232 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6233 (org-rear-nonsticky-at (match-beginning 1))
6234 (add-text-properties (match-beginning 1) (match-end 1) vp)
6235 (org-rear-nonsticky-at (match-end 1))
6236 (add-text-properties (match-end 1) (match-end 0) ip)
6237 (org-rear-nonsticky-at (match-end 0)))
6238 (when activate-func
6239 (funcall activate-func link-start link-end path bracketp))
6240 t)))
6242 (defun org-activate-dates (limit)
6243 "Add text properties for dates."
6244 (when (and (re-search-forward org-tsr-regexp-both limit t)
6245 (not (equal (char-before (match-beginning 0)) 91)))
6246 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6247 (add-text-properties (match-beginning 0) (match-end 0)
6248 (list 'mouse-face 'highlight
6249 'keymap org-mouse-map))
6250 (org-rear-nonsticky-at (match-end 0))
6251 (when org-display-custom-times
6252 (if (match-end 3)
6253 (org-display-custom-time (match-beginning 3) (match-end 3))
6254 (org-display-custom-time (match-beginning 1) (match-end 1))))
6257 (defvar-local org-target-link-regexp nil
6258 "Regular expression matching radio targets in plain text.")
6260 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6261 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6262 border border border))
6263 "Regular expression matching a link target.")
6265 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6266 "Regular expression matching a radio target.")
6268 (defconst org-any-target-regexp
6269 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6270 "Regular expression matching any target.")
6272 (defun org-activate-target-links (limit)
6273 "Add text properties for target matches."
6274 (when org-target-link-regexp
6275 (let ((case-fold-search t))
6276 (when (re-search-forward org-target-link-regexp limit t)
6277 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6278 (add-text-properties (match-beginning 1) (match-end 1)
6279 (list 'mouse-face 'highlight
6280 'keymap org-mouse-map
6281 'help-echo "Radio target link"
6282 'org-linked-text t))
6283 (org-rear-nonsticky-at (match-end 1))
6284 t))))
6286 (defun org-update-radio-target-regexp ()
6287 "Find all radio targets in this file and update the regular expression.
6288 Also refresh fontification if needed."
6289 (interactive)
6290 (let ((old-regexp org-target-link-regexp)
6291 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6292 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6293 (targets
6294 (org-with-wide-buffer
6295 (goto-char (point-min))
6296 (let (rtn)
6297 (while (re-search-forward org-radio-target-regexp nil t)
6298 ;; Make sure point is really within the object.
6299 (backward-char)
6300 (let ((obj (org-element-context)))
6301 (when (eq (org-element-type obj) 'radio-target)
6302 (cl-pushnew (org-element-property :value obj) rtn
6303 :test #'equal))))
6304 rtn))))
6305 (setq org-target-link-regexp
6306 (and targets
6307 (concat before-re
6308 (mapconcat
6309 (lambda (x)
6310 (replace-regexp-in-string
6311 " +" "\\s-+" (regexp-quote x) t t))
6312 targets
6313 "\\|")
6314 after-re)))
6315 (unless (equal old-regexp org-target-link-regexp)
6316 ;; Clean-up cache.
6317 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6318 ((not org-target-link-regexp) old-regexp)
6320 (concat before-re
6321 (mapconcat
6322 (lambda (re)
6323 (substring re (length before-re)
6324 (- (length after-re))))
6325 (list old-regexp org-target-link-regexp)
6326 "\\|")
6327 after-re)))))
6328 (org-with-wide-buffer
6329 (goto-char (point-min))
6330 (while (re-search-forward regexp nil t)
6331 (org-element-cache-refresh (match-beginning 1)))))
6332 ;; Re fontify buffer.
6333 (when (memq 'radio org-highlight-links)
6334 (org-restart-font-lock)))))
6336 (defun org-hide-wide-columns (limit)
6337 (let (s e)
6338 (setq s (text-property-any (point) (or limit (point-max))
6339 'org-cwidth t))
6340 (when s
6341 (setq e (next-single-property-change s 'org-cwidth))
6342 (add-text-properties s e '(invisible org-cwidth))
6343 (goto-char e)
6344 t)))
6346 (defvar org-latex-and-related-regexp nil
6347 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6349 (defun org-compute-latex-and-related-regexp ()
6350 "Compute regular expression for LaTeX, entities and sub/superscript.
6351 Result depends on variable `org-highlight-latex-and-related'."
6352 (setq-local
6353 org-latex-and-related-regexp
6354 (let* ((re-sub
6355 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6356 ((eq org-use-sub-superscripts '{})
6357 (list org-match-substring-with-braces-regexp))
6358 (org-use-sub-superscripts (list org-match-substring-regexp))))
6359 (re-latex
6360 (when (memq 'latex org-highlight-latex-and-related)
6361 (let ((matchers (plist-get org-format-latex-options :matchers)))
6362 (delq nil
6363 (mapcar (lambda (x)
6364 (and (member (car x) matchers) (nth 1 x)))
6365 org-latex-regexps)))))
6366 (re-entities
6367 (when (memq 'entities org-highlight-latex-and-related)
6368 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6369 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6371 (defun org-do-latex-and-related (limit)
6372 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6373 LIMIT bounds the search for syntax to highlight. Stop at first
6374 highlighted object, if any. Return t if some highlighting was
6375 done, nil otherwise."
6376 (when (org-string-nw-p org-latex-and-related-regexp)
6377 (catch 'found
6378 (while (re-search-forward org-latex-and-related-regexp limit t)
6379 (unless
6380 (cl-some
6381 (lambda (f)
6382 (memq f '(org-code org-verbatim underline org-special-keyword)))
6383 (save-excursion
6384 (goto-char (1+ (match-beginning 0)))
6385 (face-at-point nil t)))
6386 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6387 '(?_ ?^))
6389 0)))
6390 (font-lock-prepend-text-property
6391 (+ offset (match-beginning 0)) (match-end 0)
6392 'face 'org-latex-and-related)
6393 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6394 '(font-lock-multiline t)))
6395 (throw 'found t)))
6396 nil)))
6398 (defun org-restart-font-lock ()
6399 "Restart `font-lock-mode', to force refontification."
6400 (when (and (boundp 'font-lock-mode) font-lock-mode)
6401 (font-lock-mode -1)
6402 (font-lock-mode 1)))
6404 (defun org-activate-tags (limit)
6405 (when (re-search-forward
6406 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6407 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6408 (add-text-properties (match-beginning 1) (match-end 1)
6409 (list 'mouse-face 'highlight
6410 'keymap org-mouse-map))
6411 (org-rear-nonsticky-at (match-end 1))
6414 (defun org-outline-level ()
6415 "Compute the outline level of the heading at point.
6417 If this is called at a normal headline, the level is the number
6418 of stars. Use `org-reduced-level' to remove the effect of
6419 `org-odd-levels'. Unlike to `org-current-level', this function
6420 takes into consideration inlinetasks."
6421 (org-with-wide-buffer
6422 (end-of-line)
6423 (if (re-search-backward org-outline-regexp-bol nil t)
6424 (1- (- (match-end 0) (match-beginning 0)))
6425 0)))
6427 (defvar org-font-lock-keywords nil)
6429 (defsubst org-re-property (property &optional literal allow-null value)
6430 "Return a regexp matching a PROPERTY line.
6432 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6433 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6434 non-nil, match properties even without a value.
6436 Match group 3 is set to the value when it exists. If there is no
6437 value and ALLOW-NULL is non-nil, it is set to the empty string.
6439 With optional argument VALUE, match only property lines with
6440 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6441 unless LITERAL is non-nil."
6442 (concat
6443 "^\\(?4:[ \t]*\\)"
6444 (format "\\(?1::\\(?2:%s\\):\\)"
6445 (if literal property (regexp-quote property)))
6446 (cond (value
6447 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6448 (if literal value (regexp-quote value))))
6449 (allow-null
6450 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6452 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6454 (defconst org-property-re
6455 (org-re-property "\\S-+" 'literal t)
6456 "Regular expression matching a property line.
6457 There are four matching groups:
6458 1: :PROPKEY: including the leading and trailing colon,
6459 2: PROPKEY without the leading and trailing colon,
6460 3: PROPVAL without leading or trailing spaces,
6461 4: the indentation of the current line,
6462 5: trailing whitespace.")
6464 (defvar org-font-lock-hook nil
6465 "Functions to be called for special font lock stuff.")
6467 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6469 (defvar org-font-lock-set-keywords-hook nil
6470 "Functions that can manipulate `org-font-lock-extra-keywords'.
6471 This is called after `org-font-lock-extra-keywords' is defined, but before
6472 it is installed to be used by font lock. This can be useful if something
6473 needs to be inserted at a specific position in the font-lock sequence.")
6475 (defun org-font-lock-hook (limit)
6476 "Run `org-font-lock-hook' within LIMIT."
6477 (run-hook-with-args 'org-font-lock-hook limit))
6479 (defun org-set-font-lock-defaults ()
6480 "Set font lock defaults for the current buffer."
6481 (let* ((em org-fontify-emphasized-text)
6482 (lk org-highlight-links)
6483 (org-font-lock-extra-keywords
6484 (list
6485 ;; Call the hook
6486 '(org-font-lock-hook)
6487 ;; Headlines
6488 `(,(if org-fontify-whole-heading-line
6489 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6490 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6491 (1 (org-get-level-face 1))
6492 (2 (org-get-level-face 2))
6493 (3 (org-get-level-face 3)))
6494 ;; Table lines
6495 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6496 (1 'org-table t))
6497 ;; Table internals
6498 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6499 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6500 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6501 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6502 ;; Drawers
6503 '(org-fontify-drawers)
6504 ;; Properties
6505 (list org-property-re
6506 '(1 'org-special-keyword t)
6507 '(3 'org-property-value t))
6508 ;; Links
6509 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6510 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6511 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6512 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6513 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6514 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6515 (when (memq 'footnote lk) '(org-activate-footnote-links))
6516 ;; Targets.
6517 (list org-any-target-regexp '(0 'org-target t))
6518 ;; Diary sexps.
6519 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6520 ;; Macro
6521 '(org-fontify-macros)
6522 '(org-hide-wide-columns (0 nil append))
6523 ;; TODO keyword
6524 (list (format org-heading-keyword-regexp-format
6525 org-todo-regexp)
6526 '(2 (org-get-todo-face 2) t))
6527 ;; DONE
6528 (if org-fontify-done-headline
6529 (list (format org-heading-keyword-regexp-format
6530 (concat
6531 "\\(?:"
6532 (mapconcat 'regexp-quote org-done-keywords "\\|")
6533 "\\)"))
6534 '(2 'org-headline-done t))
6535 nil)
6536 ;; Priorities
6537 '(org-font-lock-add-priority-faces)
6538 ;; Tags
6539 '(org-font-lock-add-tag-faces)
6540 ;; Tags groups
6541 (when (and org-group-tags org-tag-groups-alist)
6542 (list (concat org-outline-regexp-bol ".+\\(:"
6543 (regexp-opt (mapcar 'car org-tag-groups-alist))
6544 ":\\).*$")
6545 '(1 'org-tag-group prepend)))
6546 ;; Special keywords
6547 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6548 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6549 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6550 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6551 ;; Emphasis
6552 (when em '(org-do-emphasis-faces))
6553 ;; Checkboxes
6554 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6555 1 'org-checkbox prepend)
6556 (when (cdr (assq 'checkbox org-list-automatic-rules))
6557 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6558 (0 (org-get-checkbox-statistics-face) t)))
6559 ;; Description list items
6560 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6561 1 'org-list-dt prepend)
6562 ;; ARCHIVEd headings
6563 (list (concat
6564 org-outline-regexp-bol
6565 "\\(.*:" org-archive-tag ":.*\\)")
6566 '(1 'org-archived prepend))
6567 ;; Specials
6568 '(org-do-latex-and-related)
6569 '(org-fontify-entities)
6570 '(org-raise-scripts)
6571 ;; Code
6572 '(org-activate-code (1 'org-code t))
6573 ;; COMMENT
6574 (list (format
6575 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6576 org-todo-regexp
6577 org-comment-string)
6578 '(9 'org-special-keyword t))
6579 ;; Blocks and meta lines
6580 '(org-fontify-meta-lines-and-blocks))))
6581 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6582 (run-hooks 'org-font-lock-set-keywords-hook)
6583 ;; Now set the full font-lock-keywords
6584 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6585 (setq-local font-lock-defaults
6586 '(org-font-lock-keywords t nil nil backward-paragraph))
6587 (kill-local-variable 'font-lock-keywords)
6588 nil))
6590 (defun org-toggle-pretty-entities ()
6591 "Toggle the composition display of entities as UTF8 characters."
6592 (interactive)
6593 (setq-local org-pretty-entities (not org-pretty-entities))
6594 (org-restart-font-lock)
6595 (if org-pretty-entities
6596 (message "Entities are now displayed as UTF8 characters")
6597 (save-restriction
6598 (widen)
6599 (decompose-region (point-min) (point-max))
6600 (message "Entities are now displayed as plain text"))))
6602 (defvar-local org-custom-properties-overlays nil
6603 "List of overlays used for custom properties.")
6605 (defun org-toggle-custom-properties-visibility ()
6606 "Display or hide properties in `org-custom-properties'."
6607 (interactive)
6608 (if org-custom-properties-overlays
6609 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6610 (setq org-custom-properties-overlays nil))
6611 (when org-custom-properties
6612 (org-with-wide-buffer
6613 (goto-char (point-min))
6614 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6615 (while (re-search-forward regexp nil t)
6616 (let ((end (cdr (save-match-data (org-get-property-block)))))
6617 (when (and end (< (point) end))
6618 ;; Hide first custom property in current drawer.
6619 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6620 (overlay-put o 'invisible t)
6621 (overlay-put o 'org-custom-property t)
6622 (push o org-custom-properties-overlays))
6623 ;; Hide additional custom properties in the same drawer.
6624 (while (re-search-forward regexp end t)
6625 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6626 (overlay-put o 'invisible t)
6627 (overlay-put o 'org-custom-property t)
6628 (push o org-custom-properties-overlays)))))
6629 ;; Each entry is limited to a single property drawer.
6630 (outline-next-heading)))))))
6632 (defun org-fontify-entities (limit)
6633 "Find an entity to fontify."
6634 (let (ee)
6635 (when org-pretty-entities
6636 (catch 'match
6637 ;; "\_ "-family is left out on purpose. Only the first one,
6638 ;; i.e., "\_ ", could be fontified anyway, and it would be
6639 ;; confusing when adding a second white space character.
6640 (while (re-search-forward
6641 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6642 limit t)
6643 (when (and (not (org-at-comment-p))
6644 (setq ee (org-entity-get (match-string 1)))
6645 (= (length (nth 6 ee)) 1))
6646 (let* ((end (if (equal (match-string 2) "{}")
6647 (match-end 2)
6648 (match-end 1))))
6649 (add-text-properties
6650 (match-beginning 0) end
6651 (list 'font-lock-fontified t))
6652 (compose-region (match-beginning 0) end
6653 (nth 6 ee) nil)
6654 (backward-char 1)
6655 (throw 'match t))))
6656 nil))))
6658 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6659 "Fontify string S like in Org mode."
6660 (with-temp-buffer
6661 (insert s)
6662 (let ((org-odd-levels-only odd-levels))
6663 (org-mode)
6664 (org-font-lock-ensure)
6665 (buffer-string))))
6667 (defvar org-m nil)
6668 (defvar org-l nil)
6669 (defvar org-f nil)
6670 (defun org-get-level-face (n)
6671 "Get the right face for match N in font-lock matching of headlines."
6672 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6673 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6674 (if org-cycle-level-faces
6675 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6676 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6677 (cond
6678 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6679 ((eq n 2) org-f)
6680 (t (unless org-level-color-stars-only org-f))))
6682 (defun org-face-from-face-or-color (context inherit face-or-color)
6683 "Create a face list that inherits INHERIT, but sets the foreground color.
6684 When FACE-OR-COLOR is not a string, just return it."
6685 (if (stringp face-or-color)
6686 (list :inherit inherit
6687 (cdr (assoc context org-faces-easy-properties))
6688 face-or-color)
6689 face-or-color))
6691 (defun org-get-todo-face (kwd)
6692 "Get the right face for a TODO keyword KWD.
6693 If KWD is a number, get the corresponding match group."
6694 (when (numberp kwd) (setq kwd (match-string kwd)))
6695 (or (org-face-from-face-or-color
6696 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6697 (and (member kwd org-done-keywords) 'org-done)
6698 'org-todo))
6700 (defun org-get-priority-face (priority)
6701 "Get the right face for PRIORITY.
6702 PRIORITY is a character."
6703 (or (org-face-from-face-or-color
6704 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6705 'org-priority))
6707 (defun org-get-tag-face (tag)
6708 "Get the right face for TAG.
6709 If TAG is a number, get the corresponding match group."
6710 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6711 (or (org-face-from-face-or-color
6712 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6713 'org-tag)))
6715 (defun org-font-lock-add-priority-faces (limit)
6716 "Add the special priority faces."
6717 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6718 (add-text-properties
6719 (match-beginning 1) (match-end 1)
6720 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6721 'font-lock-fontified t))))
6723 (defun org-font-lock-add-tag-faces (limit)
6724 "Add the special tag faces."
6725 (when (and org-tag-faces org-tags-special-faces-re)
6726 (while (re-search-forward org-tags-special-faces-re limit t)
6727 (add-text-properties (match-beginning 1) (match-end 1)
6728 (list 'face (org-get-tag-face 1)
6729 'font-lock-fontified t))
6730 (backward-char 1))))
6732 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6733 "Remove fontification and activation overlays from links."
6734 (font-lock-default-unfontify-region beg end)
6735 (let* ((buffer-undo-list t)
6736 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6737 (inhibit-modification-hooks t)
6738 deactivate-mark buffer-file-name buffer-file-truename)
6739 (decompose-region beg end)
6740 (remove-text-properties beg end
6741 '(mouse-face t keymap t org-linked-text t
6742 invisible t intangible t
6743 org-emphasis t))
6744 (org-remove-font-lock-display-properties beg end)))
6746 (defconst org-script-display '(((raise -0.3) (height 0.7))
6747 ((raise 0.3) (height 0.7))
6748 ((raise -0.5))
6749 ((raise 0.5)))
6750 "Display properties for showing superscripts and subscripts.")
6752 (defun org-remove-font-lock-display-properties (beg end)
6753 "Remove specific display properties that have been added by font lock.
6754 The will remove the raise properties that are used to show superscripts
6755 and subscripts."
6756 (let (next prop)
6757 (while (< beg end)
6758 (setq next (next-single-property-change beg 'display nil end)
6759 prop (get-text-property beg 'display))
6760 (when (member prop org-script-display)
6761 (put-text-property beg next 'display nil))
6762 (setq beg next))))
6764 (defun org-raise-scripts (limit)
6765 "Add raise properties to sub/superscripts."
6766 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6767 (re-search-forward
6768 (if (eq org-use-sub-superscripts t)
6769 org-match-substring-regexp
6770 org-match-substring-with-braces-regexp)
6771 limit t))
6772 (let* ((pos (point)) table-p comment-p
6773 (mpos (match-beginning 3))
6774 (emph-p (get-text-property mpos 'org-emphasis))
6775 (link-p (get-text-property mpos 'mouse-face))
6776 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6777 (goto-char (point-at-bol))
6778 (setq table-p (looking-at-p org-table-dataline-regexp)
6779 comment-p (looking-at-p "^[ \t]*#[ +]"))
6780 (goto-char pos)
6781 ;; Handle a_b^c
6782 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6783 (unless (or comment-p emph-p link-p keyw-p)
6784 (put-text-property (match-beginning 3) (match-end 0)
6785 'display
6786 (if (equal (char-after (match-beginning 2)) ?^)
6787 (nth (if table-p 3 1) org-script-display)
6788 (nth (if table-p 2 0) org-script-display)))
6789 (add-text-properties (match-beginning 2) (match-end 2)
6790 (list 'invisible t
6791 'org-dwidth t 'org-dwidth-n 1))
6792 (if (and (eq (char-after (match-beginning 3)) ?{)
6793 (eq (char-before (match-end 3)) ?}))
6794 (progn
6795 (add-text-properties
6796 (match-beginning 3) (1+ (match-beginning 3))
6797 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6798 (add-text-properties
6799 (1- (match-end 3)) (match-end 3)
6800 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6801 t)))
6803 ;;;; Visibility cycling, including org-goto and indirect buffer
6805 ;;; Cycling
6807 (defvar-local org-cycle-global-status nil)
6808 (put 'org-cycle-global-status 'org-state t)
6809 (defvar-local org-cycle-subtree-status nil)
6810 (put 'org-cycle-subtree-status 'org-state t)
6812 (defvar org-inlinetask-min-level)
6814 (defun org-unlogged-message (&rest args)
6815 "Display a message, but avoid logging it in the *Messages* buffer."
6816 (let ((message-log-max nil))
6817 (apply 'message args)))
6819 ;;;###autoload
6820 (defun org-cycle (&optional arg)
6821 "TAB-action and visibility cycling for Org mode.
6823 This is the command invoked in Org mode by the TAB key. Its main purpose
6824 is outline visibility cycling, but it also invokes other actions
6825 in special contexts.
6827 - When this function is called with a prefix argument, rotate the entire
6828 buffer through 3 states (global cycling)
6829 1. OVERVIEW: Show only top-level headlines.
6830 2. CONTENTS: Show all headlines of all levels, but no body text.
6831 3. SHOW ALL: Show everything.
6832 With a double \\[universal-argument] prefix argument, \
6833 switch to the startup visibility,
6834 determined by the variable `org-startup-folded', and by any VISIBILITY
6835 properties in the buffer.
6836 With a triple \\[universal-argument] prefix argument, \
6837 show the entire buffer, including any drawers.
6839 - When inside a table, re-align the table and move to the next field.
6841 - When point is at the beginning of a headline, rotate the subtree started
6842 by this line through 3 different states (local cycling)
6843 1. FOLDED: Only the main headline is shown.
6844 2. CHILDREN: The main headline and the direct children are shown.
6845 From this state, you can move to one of the children
6846 and zoom in further.
6847 3. SUBTREE: Show the entire subtree, including body text.
6848 If there is no subtree, switch directly from CHILDREN to FOLDED.
6850 - When point is at the beginning of an empty headline and the variable
6851 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6852 of the headline by demoting and promoting it to likely levels. This
6853 speeds up creation document structure by pressing TAB once or several
6854 times right after creating a new headline.
6856 - When there is a numeric prefix, go up to a heading with level ARG, do
6857 a `show-subtree' and return to the previous cursor position. If ARG
6858 is negative, go up that many levels.
6860 - When point is not at the beginning of a headline, execute the global
6861 binding for TAB, which is re-indenting the line. See the option
6862 `org-cycle-emulate-tab' for details.
6864 - Special case: if point is at the beginning of the buffer and there is
6865 no headline in line 1, this function will act as if called with prefix arg
6866 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6867 But only if also the variable `org-cycle-global-at-bob' is t."
6868 (interactive "P")
6869 (org-load-modules-maybe)
6870 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6871 (and org-cycle-level-after-item/entry-creation
6872 (or (org-cycle-level)
6873 (org-cycle-item-indentation))))
6874 (let* ((limit-level
6875 (or org-cycle-max-level
6876 (and (boundp 'org-inlinetask-min-level)
6877 org-inlinetask-min-level
6878 (1- org-inlinetask-min-level))))
6879 (nstars (and limit-level
6880 (if org-odd-levels-only
6881 (and limit-level (1- (* limit-level 2)))
6882 limit-level)))
6883 (org-outline-regexp
6884 (if (not (derived-mode-p 'org-mode))
6885 outline-regexp
6886 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6887 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6888 (not (looking-at org-outline-regexp))))
6889 (org-cycle-hook
6890 (if bob-special
6891 (delq 'org-optimize-window-after-visibility-change
6892 (copy-sequence org-cycle-hook))
6893 org-cycle-hook))
6894 (pos (point)))
6896 (when (or bob-special (equal arg '(4)))
6897 ;; special case: use global cycling
6898 (setq arg t))
6900 (cond
6902 ((equal arg '(16))
6903 (setq last-command 'dummy)
6904 (org-set-startup-visibility)
6905 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6907 ((equal arg '(64))
6908 (outline-show-all)
6909 (org-unlogged-message "Entire buffer visible, including drawers"))
6911 ;; Try cdlatex TAB completion
6912 ((org-try-cdlatex-tab))
6914 ;; Table: enter it or move to the next field.
6915 ((org-at-table-p 'any)
6916 (if (org-at-table.el-p)
6917 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6918 Use \\[org-edit-special] to edit table.el tables"))
6919 (if arg (org-table-edit-field t)
6920 (org-table-justify-field-maybe)
6921 (call-interactively 'org-table-next-field))))
6923 ((run-hook-with-args-until-success
6924 'org-tab-after-check-for-table-hook))
6926 ;; Global cycling: delegate to `org-cycle-internal-global'.
6927 ((eq arg t) (org-cycle-internal-global))
6929 ;; Drawers: delegate to `org-flag-drawer'.
6930 ((save-excursion
6931 (beginning-of-line 1)
6932 (looking-at org-drawer-regexp))
6933 (org-flag-drawer ; toggle block visibility
6934 (not (get-char-property (match-end 0) 'invisible))))
6936 ;; Show-subtree, ARG levels up from here.
6937 ((integerp arg)
6938 (save-excursion
6939 (org-back-to-heading)
6940 (outline-up-heading (if (< arg 0) (- arg)
6941 (- (funcall outline-level) arg)))
6942 (org-show-subtree)))
6944 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6945 ((and (featurep 'org-inlinetask)
6946 (org-inlinetask-at-task-p)
6947 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6948 (org-inlinetask-toggle-visibility))
6950 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6951 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6952 (save-excursion (move-beginning-of-line 1)
6953 (looking-at org-outline-regexp)))
6954 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6955 (org-cycle-internal-local))
6957 ;; From there: TAB emulation and template completion.
6958 (buffer-read-only (org-back-to-heading))
6960 ((run-hook-with-args-until-success
6961 'org-tab-after-check-for-cycling-hook))
6963 ((org-try-structure-completion))
6965 ((run-hook-with-args-until-success
6966 'org-tab-before-tab-emulation-hook))
6968 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6969 (or (not (bolp))
6970 (not (looking-at org-outline-regexp))))
6971 (call-interactively (global-key-binding "\t")))
6973 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6974 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6975 (or (and (eq org-cycle-emulate-tab 'white)
6976 (= (match-end 0) (point-at-eol)))
6977 (and (eq org-cycle-emulate-tab 'whitestart)
6978 (>= (match-end 0) pos))))
6980 (eq org-cycle-emulate-tab t))
6981 (call-interactively (global-key-binding "\t")))
6983 (t (save-excursion
6984 (org-back-to-heading)
6985 (org-cycle)))))))
6987 (defun org-cycle-internal-global ()
6988 "Do the global cycling action."
6989 ;; Hack to avoid display of messages for .org attachments in Gnus
6990 (let ((ga (string-match "\\*fontification" (buffer-name))))
6991 (cond
6992 ((and (eq last-command this-command)
6993 (eq org-cycle-global-status 'overview))
6994 ;; We just created the overview - now do table of contents
6995 ;; This can be slow in very large buffers, so indicate action
6996 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6997 (unless ga (org-unlogged-message "CONTENTS..."))
6998 (org-content)
6999 (unless ga (org-unlogged-message "CONTENTS...done"))
7000 (setq org-cycle-global-status 'contents)
7001 (run-hook-with-args 'org-cycle-hook 'contents))
7003 ((and (eq last-command this-command)
7004 (eq org-cycle-global-status 'contents))
7005 ;; We just showed the table of contents - now show everything
7006 (run-hook-with-args 'org-pre-cycle-hook 'all)
7007 (outline-show-all)
7008 (unless ga (org-unlogged-message "SHOW ALL"))
7009 (setq org-cycle-global-status 'all)
7010 (run-hook-with-args 'org-cycle-hook 'all))
7013 ;; Default action: go to overview
7014 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7015 (org-overview)
7016 (unless ga (org-unlogged-message "OVERVIEW"))
7017 (setq org-cycle-global-status 'overview)
7018 (run-hook-with-args 'org-cycle-hook 'overview)))))
7020 (defvar org-called-with-limited-levels nil
7021 "Non-nil when `org-with-limited-levels' is currently active.")
7023 (defun org-cycle-internal-local ()
7024 "Do the local cycling action."
7025 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7026 ;; First, determine end of headline (EOH), end of subtree or item
7027 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7028 (save-excursion
7029 (if (org-at-item-p)
7030 (progn
7031 (beginning-of-line)
7032 (setq struct (org-list-struct))
7033 (setq eoh (point-at-eol))
7034 (setq eos (org-list-get-item-end-before-blank (point) struct))
7035 (setq has-children (org-list-has-child-p (point) struct)))
7036 (org-back-to-heading)
7037 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7038 (setq eos (save-excursion (org-end-of-subtree t t)
7039 (when (bolp) (backward-char)) (point)))
7040 (setq has-children
7041 (or (save-excursion
7042 (let ((level (funcall outline-level)))
7043 (outline-next-heading)
7044 (and (org-at-heading-p t)
7045 (> (funcall outline-level) level))))
7046 (save-excursion
7047 (org-list-search-forward (org-item-beginning-re) eos t)))))
7048 ;; Determine end invisible part of buffer (EOL)
7049 (beginning-of-line 2)
7050 (while (and (not (eobp)) ;This is like `next-line'.
7051 (get-char-property (1- (point)) 'invisible))
7052 (goto-char (next-single-char-property-change (point) 'invisible))
7053 (and (eolp) (beginning-of-line 2)))
7054 (setq eol (point)))
7055 ;; Find out what to do next and set `this-command'
7056 (cond
7057 ((= eos eoh)
7058 ;; Nothing is hidden behind this heading
7059 (unless (org-before-first-heading-p)
7060 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7061 (org-unlogged-message "EMPTY ENTRY")
7062 (setq org-cycle-subtree-status nil)
7063 (save-excursion
7064 (goto-char eos)
7065 (outline-next-heading)
7066 (when (outline-invisible-p) (org-flag-heading nil))))
7067 ((and (or (>= eol eos)
7068 (not (string-match "\\S-" (buffer-substring eol eos))))
7069 (or has-children
7070 (not (setq children-skipped
7071 org-cycle-skip-children-state-if-no-children))))
7072 ;; Entire subtree is hidden in one line: children view
7073 (unless (org-before-first-heading-p)
7074 (run-hook-with-args 'org-pre-cycle-hook 'children))
7075 (if (org-at-item-p)
7076 (org-list-set-item-visibility (point-at-bol) struct 'children)
7077 (org-show-entry)
7078 (org-with-limited-levels (org-show-children))
7079 ;; FIXME: This slows down the func way too much.
7080 ;; How keep drawers hidden in subtree anyway?
7081 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7082 ;; (org-cycle-hide-drawers 'subtree))
7084 ;; Fold every list in subtree to top-level items.
7085 (when (eq org-cycle-include-plain-lists 'integrate)
7086 (save-excursion
7087 (org-back-to-heading)
7088 (while (org-list-search-forward (org-item-beginning-re) eos t)
7089 (beginning-of-line 1)
7090 (let* ((struct (org-list-struct))
7091 (prevs (org-list-prevs-alist struct))
7092 (end (org-list-get-bottom-point struct)))
7093 (dolist (e (org-list-get-all-items (point) struct prevs))
7094 (org-list-set-item-visibility e struct 'folded))
7095 (goto-char (if (< end eos) end eos)))))))
7096 (org-unlogged-message "CHILDREN")
7097 (save-excursion
7098 (goto-char eos)
7099 (outline-next-heading)
7100 (when (outline-invisible-p) (org-flag-heading nil)))
7101 (setq org-cycle-subtree-status 'children)
7102 (unless (org-before-first-heading-p)
7103 (run-hook-with-args 'org-cycle-hook 'children)))
7104 ((or children-skipped
7105 (and (eq last-command this-command)
7106 (eq org-cycle-subtree-status 'children)))
7107 ;; We just showed the children, or no children are there,
7108 ;; now show everything.
7109 (unless (org-before-first-heading-p)
7110 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7111 (outline-flag-region eoh eos nil)
7112 (org-unlogged-message
7113 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7114 (setq org-cycle-subtree-status 'subtree)
7115 (unless (org-before-first-heading-p)
7116 (run-hook-with-args 'org-cycle-hook 'subtree)))
7118 ;; Default action: hide the subtree.
7119 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7120 (outline-flag-region eoh eos t)
7121 (org-unlogged-message "FOLDED")
7122 (setq org-cycle-subtree-status 'folded)
7123 (unless (org-before-first-heading-p)
7124 (run-hook-with-args 'org-cycle-hook 'folded))))))
7126 ;;;###autoload
7127 (defun org-global-cycle (&optional arg)
7128 "Cycle the global visibility. For details see `org-cycle'.
7129 With \\[universal-argument] prefix arg, switch to startup visibility.
7130 With a numeric prefix, show all headlines up to that level."
7131 (interactive "P")
7132 (let ((org-cycle-include-plain-lists
7133 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7134 (cond
7135 ((integerp arg)
7136 (outline-show-all)
7137 (outline-hide-sublevels arg)
7138 (setq org-cycle-global-status 'contents))
7139 ((equal arg '(4))
7140 (org-set-startup-visibility)
7141 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7143 (org-cycle '(4))))))
7145 (defun org-set-startup-visibility ()
7146 "Set the visibility required by startup options and properties."
7147 (cond
7148 ((eq org-startup-folded t)
7149 (org-overview))
7150 ((eq org-startup-folded 'content)
7151 (org-content))
7152 ((or (eq org-startup-folded 'showeverything)
7153 (eq org-startup-folded nil))
7154 (outline-show-all)))
7155 (unless (eq org-startup-folded 'showeverything)
7156 (when org-hide-block-startup (org-hide-block-all))
7157 (org-set-visibility-according-to-property 'no-cleanup)
7158 (org-cycle-hide-archived-subtrees 'all)
7159 (org-cycle-hide-drawers 'all)
7160 (org-cycle-show-empty-lines t)))
7162 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7163 "Switch subtree visibilities according to :VISIBILITY: property."
7164 (interactive)
7165 (org-with-wide-buffer
7166 (goto-char (point-min))
7167 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7168 (if (not (org-at-property-p)) (outline-next-heading)
7169 (let ((state (match-string 3)))
7170 (save-excursion
7171 (org-back-to-heading t)
7172 (outline-hide-subtree)
7173 (org-reveal)
7174 (cond
7175 ((equal state "folded")
7176 (outline-hide-subtree))
7177 ((equal state "children")
7178 (org-show-hidden-entry)
7179 (org-show-children))
7180 ((equal state "content")
7181 (save-excursion
7182 (save-restriction
7183 (org-narrow-to-subtree)
7184 (org-content))))
7185 ((member state '("all" "showall"))
7186 (outline-show-subtree)))))))
7187 (unless no-cleanup
7188 (org-cycle-hide-archived-subtrees 'all)
7189 (org-cycle-hide-drawers 'all)
7190 (org-cycle-show-empty-lines 'all))))
7192 ;; This function uses outline-regexp instead of the more fundamental
7193 ;; org-outline-regexp so that org-cycle-global works outside of Org
7194 ;; buffers, where outline-regexp is needed.
7195 (defun org-overview ()
7196 "Switch to overview mode, showing only top-level headlines.
7197 This shows all headlines with a level equal or greater than the level
7198 of the first headline in the buffer. This is important, because if the
7199 first headline is not level one, then (hide-sublevels 1) gives confusing
7200 results."
7201 (interactive)
7202 (save-excursion
7203 (let ((level
7204 (save-excursion
7205 (goto-char (point-min))
7206 (when (re-search-forward (concat "^" outline-regexp) nil t)
7207 (goto-char (match-beginning 0))
7208 (funcall outline-level)))))
7209 (and level (outline-hide-sublevels level)))))
7211 (defun org-content (&optional arg)
7212 "Show all headlines in the buffer, like a table of contents.
7213 With numerical argument N, show content up to level N."
7214 (interactive "P")
7215 (org-overview)
7216 (save-excursion
7217 ;; Visit all headings and show their offspring
7218 (and (integerp arg) (org-overview))
7219 (goto-char (point-max))
7220 (catch 'exit
7221 (while (and (progn (condition-case nil
7222 (outline-previous-visible-heading 1)
7223 (error (goto-char (point-min))))
7225 (looking-at org-outline-regexp))
7226 (if (integerp arg)
7227 (org-show-children (1- arg))
7228 (outline-show-branches))
7229 (when (bobp) (throw 'exit nil))))))
7231 (defun org-optimize-window-after-visibility-change (state)
7232 "Adjust the window after a change in outline visibility.
7233 This function is the default value of the hook `org-cycle-hook'."
7234 (when (get-buffer-window (current-buffer))
7235 (cond
7236 ((eq state 'content) nil)
7237 ((eq state 'all) nil)
7238 ((eq state 'folded) nil)
7239 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7240 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7242 (defun org-remove-empty-overlays-at (pos)
7243 "Remove outline overlays that do not contain non-white stuff."
7244 (dolist (o (overlays-at pos))
7245 (and (eq 'outline (overlay-get o 'invisible))
7246 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7247 (overlay-end o))))
7248 (delete-overlay o))))
7250 (defun org-clean-visibility-after-subtree-move ()
7251 "Fix visibility issues after moving a subtree."
7252 ;; First, find a reasonable region to look at:
7253 ;; Start two siblings above, end three below
7254 (let* ((beg (save-excursion
7255 (and (org-get-last-sibling)
7256 (org-get-last-sibling))
7257 (point)))
7258 (end (save-excursion
7259 (and (org-get-next-sibling)
7260 (org-get-next-sibling)
7261 (org-get-next-sibling))
7262 (if (org-at-heading-p)
7263 (point-at-eol)
7264 (point))))
7265 (level (looking-at "\\*+"))
7266 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7267 (save-excursion
7268 (save-restriction
7269 (narrow-to-region beg end)
7270 (when re
7271 ;; Properly fold already folded siblings
7272 (goto-char (point-min))
7273 (while (re-search-forward re nil t)
7274 (when (and (not (outline-invisible-p))
7275 (save-excursion
7276 (goto-char (point-at-eol)) (outline-invisible-p)))
7277 (outline-hide-entry))))
7278 (org-cycle-show-empty-lines 'overview)
7279 (org-cycle-hide-drawers 'overview)))))
7281 (defun org-cycle-show-empty-lines (state)
7282 "Show empty lines above all visible headlines.
7283 The region to be covered depends on STATE when called through
7284 `org-cycle-hook'. Lisp program can use t for STATE to get the
7285 entire buffer covered. Note that an empty line is only shown if there
7286 are at least `org-cycle-separator-lines' empty lines before the headline."
7287 (when (/= org-cycle-separator-lines 0)
7288 (save-excursion
7289 (let* ((n (abs org-cycle-separator-lines))
7290 (re (cond
7291 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7292 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7293 (t (let ((ns (number-to-string (- n 2))))
7294 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7295 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7296 beg end)
7297 (cond
7298 ((memq state '(overview contents t))
7299 (setq beg (point-min) end (point-max)))
7300 ((memq state '(children folded))
7301 (setq beg (point)
7302 end (progn (org-end-of-subtree t t)
7303 (line-beginning-position 2)))))
7304 (when beg
7305 (goto-char beg)
7306 (while (re-search-forward re end t)
7307 (unless (get-char-property (match-end 1) 'invisible)
7308 (let ((e (match-end 1))
7309 (b (if (>= org-cycle-separator-lines 0)
7310 (match-beginning 1)
7311 (save-excursion
7312 (goto-char (match-beginning 0))
7313 (skip-chars-backward " \t\n")
7314 (line-end-position)))))
7315 (outline-flag-region b e nil))))))))
7316 ;; Never hide empty lines at the end of the file.
7317 (save-excursion
7318 (goto-char (point-max))
7319 (outline-previous-heading)
7320 (outline-end-of-heading)
7321 (when (and (looking-at "[ \t\n]+")
7322 (= (match-end 0) (point-max)))
7323 (outline-flag-region (point) (match-end 0) nil))))
7325 (defun org-show-empty-lines-in-parent ()
7326 "Move to the parent and re-show empty lines before visible headlines."
7327 (save-excursion
7328 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7329 (org-cycle-show-empty-lines context))))
7331 (defun org-files-list ()
7332 "Return `org-agenda-files' list, plus all open Org files.
7333 This is useful for operations that need to scan all of a user's
7334 open and agenda-wise Org files."
7335 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7336 (dolist (buf (buffer-list))
7337 (with-current-buffer buf
7338 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7339 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7340 files))
7342 (defsubst org-entry-beginning-position ()
7343 "Return the beginning position of the current entry."
7344 (save-excursion (org-back-to-heading t) (point)))
7346 (defsubst org-entry-end-position ()
7347 "Return the end position of the current entry."
7348 (save-excursion (outline-next-heading) (point)))
7350 (defun org-cycle-hide-drawers (state &optional exceptions)
7351 "Re-hide all drawers after a visibility state change.
7352 When non-nil, optional argument EXCEPTIONS is a list of strings
7353 specifying which drawers should not be hidden."
7354 (when (and (derived-mode-p 'org-mode)
7355 (not (memq state '(overview folded contents))))
7356 (save-excursion
7357 (let* ((globalp (memq state '(contents all)))
7358 (beg (if globalp (point-min) (point)))
7359 (end (if globalp (point-max)
7360 (if (eq state 'children)
7361 (save-excursion (outline-next-heading) (point))
7362 (org-end-of-subtree t)))))
7363 (goto-char beg)
7364 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7365 (unless (member-ignore-case (match-string 1) exceptions)
7366 (let ((drawer (org-element-at-point)))
7367 (when (memq (org-element-type drawer) '(drawer property-drawer))
7368 (org-flag-drawer t drawer)
7369 ;; Make sure to skip drawer entirely or we might flag
7370 ;; it another time when matching its ending line with
7371 ;; `org-drawer-regexp'.
7372 (goto-char (org-element-property :end drawer))))))))))
7374 (defun org-flag-drawer (flag &optional element)
7375 "When FLAG is non-nil, hide the drawer we are at.
7376 Otherwise make it visible. When optional argument ELEMENT is
7377 a parsed drawer, as returned by `org-element-at-point', hide or
7378 show that drawer instead."
7379 (let ((drawer (or element
7380 (and (save-excursion
7381 (beginning-of-line)
7382 (looking-at-p org-drawer-regexp))
7383 (org-element-at-point)))))
7384 (when (memq (org-element-type drawer) '(drawer property-drawer))
7385 (let ((post (org-element-property :post-affiliated drawer)))
7386 (save-excursion
7387 (outline-flag-region
7388 (progn (goto-char post) (line-end-position))
7389 (progn (goto-char (org-element-property :end drawer))
7390 (skip-chars-backward " \r\t\n")
7391 (line-end-position))
7392 flag))
7393 ;; When the drawer is hidden away, make sure point lies in
7394 ;; a visible part of the buffer.
7395 (when (and flag (> (line-beginning-position) post))
7396 (goto-char post))))))
7398 (defun org-subtree-end-visible-p ()
7399 "Is the end of the current subtree visible?"
7400 (pos-visible-in-window-p
7401 (save-excursion (org-end-of-subtree t) (point))))
7403 (defun org-first-headline-recenter ()
7404 "Move cursor to the first headline and recenter the headline."
7405 (let ((window (get-buffer-window)))
7406 (when window
7407 (goto-char (point-min))
7408 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7409 (set-window-start window (line-beginning-position))))))
7411 ;;; Saving and restoring visibility
7413 (defun org-outline-overlay-data (&optional use-markers)
7414 "Return a list of the locations of all outline overlays.
7415 These are overlays with the `invisible' property value `outline'.
7416 The return value is a list of cons cells, with start and stop
7417 positions for each overlay.
7418 If USE-MARKERS is set, return the positions as markers."
7419 (let (beg end)
7420 (org-with-wide-buffer
7421 (delq nil
7422 (mapcar (lambda (o)
7423 (when (eq (overlay-get o 'invisible) 'outline)
7424 (setq beg (overlay-start o)
7425 end (overlay-end o))
7426 (and beg end (> end beg)
7427 (if use-markers
7428 (cons (copy-marker beg)
7429 (copy-marker end t))
7430 (cons beg end)))))
7431 (overlays-in (point-min) (point-max)))))))
7433 (defun org-set-outline-overlay-data (data)
7434 "Create visibility overlays for all positions in DATA.
7435 DATA should have been made by `org-outline-overlay-data'."
7436 (org-with-wide-buffer
7437 (outline-show-all)
7438 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7440 ;;; Folding of blocks
7442 (defvar-local org-hide-block-overlays nil
7443 "Overlays hiding blocks.")
7445 (defun org-block-map (function &optional start end)
7446 "Call FUNCTION at the head of all source blocks in the current buffer.
7447 Optional arguments START and END can be used to limit the range."
7448 (let ((start (or start (point-min)))
7449 (end (or end (point-max))))
7450 (save-excursion
7451 (goto-char start)
7452 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7453 (save-excursion
7454 (save-match-data
7455 (goto-char (match-beginning 0))
7456 (funcall function)))))))
7458 (defun org-hide-block-toggle-all ()
7459 "Toggle the visibility of all blocks in the current buffer."
7460 (org-block-map 'org-hide-block-toggle))
7462 (defun org-hide-block-all ()
7463 "Fold all blocks in the current buffer."
7464 (interactive)
7465 (org-show-block-all)
7466 (org-block-map 'org-hide-block-toggle-maybe))
7468 (defun org-show-block-all ()
7469 "Unfold all blocks in the current buffer."
7470 (interactive)
7471 (mapc #'delete-overlay org-hide-block-overlays)
7472 (setq org-hide-block-overlays nil))
7474 (defun org-hide-block-toggle-maybe ()
7475 "Toggle visibility of block at point.
7476 Unlike to `org-hide-block-toggle', this function does not throw
7477 an error. Return a non-nil value when toggling is successful."
7478 (interactive)
7479 (ignore-errors (org-hide-block-toggle)))
7481 (defun org-hide-block-toggle (&optional force)
7482 "Toggle the visibility of the current block.
7483 When optional argument FORCE is `off', make block visible. If it
7484 is non-nil, hide it unconditionally. Throw an error when not at
7485 a block. Return a non-nil value when toggling is successful."
7486 (interactive)
7487 (let ((element (org-element-at-point)))
7488 (unless (memq (org-element-type element)
7489 '(center-block comment-block dynamic-block example-block
7490 export-block quote-block special-block
7491 src-block verse-block))
7492 (user-error "Not at a block"))
7493 (let* ((start (save-excursion
7494 (goto-char (org-element-property :post-affiliated element))
7495 (line-end-position)))
7496 (end (save-excursion
7497 (goto-char (org-element-property :end element))
7498 (skip-chars-backward " \r\t\n")
7499 (line-end-position)))
7500 (overlays (overlays-at start)))
7501 (cond
7502 ;; Do nothing when not before or at the block opening line or
7503 ;; at the block closing line.
7504 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7505 ((and (not (eq force 'off))
7506 (not (memq t (mapcar
7507 (lambda (o)
7508 (eq (overlay-get o 'invisible) 'org-hide-block))
7509 overlays))))
7510 (let ((ov (make-overlay start end)))
7511 (overlay-put ov 'invisible 'org-hide-block)
7512 ;; Make the block accessible to `isearch'.
7513 (overlay-put
7514 ov 'isearch-open-invisible
7515 (lambda (ov)
7516 (when (memq ov org-hide-block-overlays)
7517 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7518 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7519 (delete-overlay ov))))
7520 (push ov org-hide-block-overlays)
7521 ;; When the block is hidden away, make sure point is left in
7522 ;; a visible part of the buffer.
7523 (when (> (line-beginning-position) start)
7524 (goto-char start)
7525 (beginning-of-line))
7526 ;; Signal successful toggling.
7528 ((or (not force) (eq force 'off))
7529 (dolist (ov overlays t)
7530 (when (memq ov org-hide-block-overlays)
7531 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7532 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7533 (delete-overlay ov))))))))
7535 ;; org-tab-after-check-for-cycling-hook
7536 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7537 ;; Remove overlays when changing major mode
7538 (add-hook 'org-mode-hook
7539 (lambda () (add-hook 'change-major-mode-hook
7540 'org-show-block-all 'append 'local)))
7542 ;;; Org-goto
7544 (defvar org-goto-window-configuration nil)
7545 (defvar org-goto-marker nil)
7546 (defvar org-goto-map)
7547 (defun org-goto-map ()
7548 "Set the keymap `org-goto'."
7549 (setq org-goto-map
7550 (let ((map (make-sparse-keymap)))
7551 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7552 mouse-drag-region universal-argument org-occur)))
7553 (dolist (cmd cmds)
7554 (substitute-key-definition cmd cmd map global-map)))
7555 (suppress-keymap map)
7556 (org-defkey map "\C-m" 'org-goto-ret)
7557 (org-defkey map [(return)] 'org-goto-ret)
7558 (org-defkey map [(left)] 'org-goto-left)
7559 (org-defkey map [(right)] 'org-goto-right)
7560 (org-defkey map [(control ?g)] 'org-goto-quit)
7561 (org-defkey map "\C-i" 'org-cycle)
7562 (org-defkey map [(tab)] 'org-cycle)
7563 (org-defkey map [(down)] 'outline-next-visible-heading)
7564 (org-defkey map [(up)] 'outline-previous-visible-heading)
7565 (if org-goto-auto-isearch
7566 (if (fboundp 'define-key-after)
7567 (define-key-after map [t] 'org-goto-local-auto-isearch)
7568 nil)
7569 (org-defkey map "q" 'org-goto-quit)
7570 (org-defkey map "n" 'outline-next-visible-heading)
7571 (org-defkey map "p" 'outline-previous-visible-heading)
7572 (org-defkey map "f" 'outline-forward-same-level)
7573 (org-defkey map "b" 'outline-backward-same-level)
7574 (org-defkey map "u" 'outline-up-heading))
7575 (org-defkey map "/" 'org-occur)
7576 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7577 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7578 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7579 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7580 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7581 map)))
7583 (defconst org-goto-help
7584 "Browse buffer copy, to find location or copy text.%s
7585 RET=jump to location C-g=quit and return to previous location
7586 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7588 (defvar org-goto-start-pos) ; dynamically scoped parameter
7590 (defun org-goto (&optional alternative-interface)
7591 "Look up a different location in the current file, keeping current visibility.
7593 When you want look-up or go to a different location in a
7594 document, the fastest way is often to fold the entire buffer and
7595 then dive into the tree. This method has the disadvantage, that
7596 the previous location will be folded, which may not be what you
7597 want.
7599 This command works around this by showing a copy of the current
7600 buffer in an indirect buffer, in overview mode. You can dive
7601 into the tree in that copy, use org-occur and incremental search
7602 to find a location. When pressing RET or `Q', the command
7603 returns to the original buffer in which the visibility is still
7604 unchanged. After RET it will also jump to the location selected
7605 in the indirect buffer and expose the headline hierarchy above.
7607 With a prefix argument, use the alternative interface: e.g., if
7608 `org-goto-interface' is `outline' use `outline-path-completion'."
7609 (interactive "P")
7610 (org-goto-map)
7611 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7612 (org-refile-use-outline-path t)
7613 (org-refile-target-verify-function nil)
7614 (interface
7615 (if (not alternative-interface)
7616 org-goto-interface
7617 (if (eq org-goto-interface 'outline)
7618 'outline-path-completion
7619 'outline)))
7620 (org-goto-start-pos (point))
7621 (selected-point
7622 (if (eq interface 'outline)
7623 (car (org-get-location (current-buffer) org-goto-help))
7624 (let ((pa (org-refile-get-location "Goto")))
7625 (org-refile-check-position pa)
7626 (nth 3 pa)))))
7627 (if selected-point
7628 (progn
7629 (org-mark-ring-push org-goto-start-pos)
7630 (goto-char selected-point)
7631 (when (or (outline-invisible-p) (org-invisible-p2))
7632 (org-show-context 'org-goto)))
7633 (message "Quit"))))
7635 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7636 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7637 (defvar org-goto-local-auto-isearch-map) ; defined below
7639 (defun org-get-location (_buf help)
7640 "Let the user select a location in current buffer.
7641 This function uses a recursive edit. It returns the selected position
7642 or nil."
7643 (org-no-popups
7644 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7645 (isearch-hide-immediately nil)
7646 (isearch-search-fun-function
7647 (lambda () 'org-goto-local-search-headings))
7648 (org-goto-selected-point org-goto-exit-command))
7649 (save-excursion
7650 (save-window-excursion
7651 (delete-other-windows)
7652 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7653 (pop-to-buffer-same-window
7654 (condition-case nil
7655 (make-indirect-buffer (current-buffer) "*org-goto*")
7656 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7657 (with-output-to-temp-buffer "*Org Help*"
7658 (princ (format help (if org-goto-auto-isearch
7659 " Just type for auto-isearch."
7660 " n/p/f/b/u to navigate, q to quit."))))
7661 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7662 (setq buffer-read-only nil)
7663 (let ((org-startup-truncated t)
7664 (org-startup-folded nil)
7665 (org-startup-align-all-tables nil))
7666 (org-mode)
7667 (org-overview))
7668 (setq buffer-read-only t)
7669 (if (and (boundp 'org-goto-start-pos)
7670 (integer-or-marker-p org-goto-start-pos))
7671 (progn (goto-char org-goto-start-pos)
7672 (when (outline-invisible-p)
7673 (org-show-set-visibility 'lineage)))
7674 (goto-char (point-min)))
7675 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7676 (message "Select location and press RET")
7677 (use-local-map org-goto-map)
7678 (recursive-edit)))
7679 (kill-buffer "*org-goto*")
7680 (cons org-goto-selected-point org-goto-exit-command))))
7682 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7683 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7684 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7685 (if (fboundp 'isearch-other-control-char)
7686 (progn
7687 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7688 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7689 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7690 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7691 (define-key org-goto-local-auto-isearch-map [return] nil))
7693 (defun org-goto-local-search-headings (string bound noerror)
7694 "Search and make sure that any matches are in headlines."
7695 (catch 'return
7696 (while (if isearch-forward
7697 (search-forward string bound noerror)
7698 (search-backward string bound noerror))
7699 (when (save-match-data
7700 (and (save-excursion
7701 (beginning-of-line)
7702 (looking-at org-complex-heading-regexp))
7703 (or (not (match-beginning 5))
7704 (< (point) (match-beginning 5)))))
7705 (throw 'return (point))))))
7707 (defun org-goto-local-auto-isearch ()
7708 "Start isearch."
7709 (interactive)
7710 (goto-char (point-min))
7711 (let ((keys (this-command-keys)))
7712 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7713 (isearch-mode t)
7714 (isearch-process-search-char (string-to-char keys)))))
7716 (defun org-goto-ret (&optional _arg)
7717 "Finish `org-goto' by going to the new location."
7718 (interactive "P")
7719 (setq org-goto-selected-point (point))
7720 (setq org-goto-exit-command 'return)
7721 (throw 'exit nil))
7723 (defun org-goto-left ()
7724 "Finish `org-goto' by going to the new location."
7725 (interactive)
7726 (if (org-at-heading-p)
7727 (progn
7728 (beginning-of-line 1)
7729 (setq org-goto-selected-point (point)
7730 org-goto-exit-command 'left)
7731 (throw 'exit nil))
7732 (user-error "Not on a heading")))
7734 (defun org-goto-right ()
7735 "Finish `org-goto' by going to the new location."
7736 (interactive)
7737 (if (org-at-heading-p)
7738 (progn
7739 (setq org-goto-selected-point (point)
7740 org-goto-exit-command 'right)
7741 (throw 'exit nil))
7742 (user-error "Not on a heading")))
7744 (defun org-goto-quit ()
7745 "Finish `org-goto' without cursor motion."
7746 (interactive)
7747 (setq org-goto-selected-point nil)
7748 (setq org-goto-exit-command 'quit)
7749 (throw 'exit nil))
7751 ;;; Indirect buffer display of subtrees
7753 (defvar org-indirect-dedicated-frame nil
7754 "This is the frame being used for indirect tree display.")
7755 (defvar org-last-indirect-buffer nil)
7757 (defun org-tree-to-indirect-buffer (&optional arg)
7758 "Create indirect buffer and narrow it to current subtree.
7759 With a numerical prefix ARG, go up to this level and then take that tree.
7760 If ARG is negative, go up that many levels.
7762 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7763 indirect buffer previously made with this command, to avoid proliferation of
7764 indirect buffers. However, when you call the command with a \
7765 \\[universal-argument] prefix, or
7766 when `org-indirect-buffer-display' is `new-frame', the last buffer
7767 is kept so that you can work with several indirect buffers at the same time.
7768 If `org-indirect-buffer-display' is `dedicated-frame', the \
7769 \\[universal-argument] prefix also
7770 requests that a new frame be made for the new buffer, so that the dedicated
7771 frame is not changed."
7772 (interactive "P")
7773 (let ((cbuf (current-buffer))
7774 (cwin (selected-window))
7775 (pos (point))
7776 beg end level heading ibuf)
7777 (save-excursion
7778 (org-back-to-heading t)
7779 (when (numberp arg)
7780 (setq level (org-outline-level))
7781 (when (< arg 0) (setq arg (+ level arg)))
7782 (while (> (setq level (org-outline-level)) arg)
7783 (org-up-heading-safe)))
7784 (setq beg (point)
7785 heading (org-get-heading 'no-tags))
7786 (org-end-of-subtree t t)
7787 (when (org-at-heading-p) (backward-char 1))
7788 (setq end (point)))
7789 (when (and (buffer-live-p org-last-indirect-buffer)
7790 (not (eq org-indirect-buffer-display 'new-frame))
7791 (not arg))
7792 (kill-buffer org-last-indirect-buffer))
7793 (setq ibuf (org-get-indirect-buffer cbuf heading)
7794 org-last-indirect-buffer ibuf)
7795 (cond
7796 ((or (eq org-indirect-buffer-display 'new-frame)
7797 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7798 (select-frame (make-frame))
7799 (delete-other-windows)
7800 (pop-to-buffer-same-window ibuf)
7801 (org-set-frame-title heading))
7802 ((eq org-indirect-buffer-display 'dedicated-frame)
7803 (raise-frame
7804 (select-frame (or (and org-indirect-dedicated-frame
7805 (frame-live-p org-indirect-dedicated-frame)
7806 org-indirect-dedicated-frame)
7807 (setq org-indirect-dedicated-frame (make-frame)))))
7808 (delete-other-windows)
7809 (pop-to-buffer-same-window ibuf)
7810 (org-set-frame-title (concat "Indirect: " heading)))
7811 ((eq org-indirect-buffer-display 'current-window)
7812 (pop-to-buffer-same-window ibuf))
7813 ((eq org-indirect-buffer-display 'other-window)
7814 (pop-to-buffer ibuf))
7815 (t (error "Invalid value")))
7816 (narrow-to-region beg end)
7817 (outline-show-all)
7818 (goto-char pos)
7819 (run-hook-with-args 'org-cycle-hook 'all)
7820 (and (window-live-p cwin) (select-window cwin))))
7822 (defun org-get-indirect-buffer (&optional buffer heading)
7823 (setq buffer (or buffer (current-buffer)))
7824 (let ((n 1) (base (buffer-name buffer)) bname)
7825 (while (buffer-live-p
7826 (get-buffer
7827 (setq bname
7828 (concat base "-"
7829 (if heading (concat heading "-" (number-to-string n))
7830 (number-to-string n))))))
7831 (setq n (1+ n)))
7832 (condition-case nil
7833 (make-indirect-buffer buffer bname 'clone)
7834 (error (make-indirect-buffer buffer bname)))))
7836 (defun org-set-frame-title (title)
7837 "Set the title of the current frame to the string TITLE."
7838 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7840 ;;;; Structure editing
7842 ;;; Inserting headlines
7844 (defun org--line-empty-p (n)
7845 "Is the Nth next line empty?
7847 Counts the current line as N = 1 and the previous line as N = 0;
7848 see `beginning-of-line'."
7849 (save-excursion
7850 (and (not (bobp))
7851 (or (beginning-of-line n) t)
7852 (save-match-data
7853 (looking-at "[ \t]*$")))))
7855 (defun org-previous-line-empty-p ()
7856 "Is the previous line a blank line?
7857 When NEXT is non-nil, check the next line instead."
7858 (org--line-empty-p 0))
7860 (defun org-next-line-empty-p ()
7861 "Is the previous line a blank line?
7862 When NEXT is non-nil, check the next line instead."
7863 (org--line-empty-p 2))
7865 (defun org-insert-heading (&optional arg invisible-ok top)
7866 "Insert a new heading or an item with the same depth at point.
7868 If point is at the beginning of a heading or a list item, insert
7869 a new heading or a new item above the current one. When at the
7870 beginning of a regular line of text, turn it into a heading.
7872 If point is in the middle of a line, split it and create a new
7873 headline/item with the text in the current line after point (see
7874 `org-M-RET-may-split-line' on how to modify this behavior). As
7875 a special case, on a headline, splitting can only happen on the
7876 title itself. E.g., this excludes breaking stars or tags.
7878 With a \\[universal-argument] prefix, set \
7879 `org-insert-heading-respect-content' to
7880 a non-nil value for the duration of the command. This forces the
7881 insertion of a heading after the current subtree, independently
7882 on the location of point.
7884 With a \\[universal-argument] \\[universal-argument] prefix, \
7885 insert the heading at the end of the tree
7886 above the current heading. For example, if point is within a
7887 2nd-level heading, then it will insert a 2nd-level heading at
7888 the end of the 1st-level parent subtree.
7890 When INVISIBLE-OK is set, stop at invisible headlines when going
7891 back. This is important for non-interactive uses of the
7892 command.
7894 When optional argument TOP is non-nil, insert a level 1 heading,
7895 unconditionally."
7896 (interactive "P")
7897 (let ((itemp (and (not top) (org-in-item-p)))
7898 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7899 (respect-content (or org-insert-heading-respect-content
7900 (equal arg '(4))))
7901 (initial-content ""))
7903 (cond
7905 ((or (= (buffer-size) 0)
7906 (and (not (save-excursion
7907 (and (ignore-errors (org-back-to-heading invisible-ok))
7908 (org-at-heading-p))))
7909 (or arg (not itemp))))
7910 ;; At beginning of buffer or so high up that only a heading
7911 ;; makes sense.
7912 (cond ((and (bolp) (not respect-content)) (insert "* "))
7913 ((not respect-content)
7914 (unless may-split (end-of-line))
7915 (insert "\n* "))
7916 ((re-search-forward org-outline-regexp-bol nil t)
7917 (beginning-of-line)
7918 (insert "* \n")
7919 (backward-char))
7920 (t (goto-char (point-max))
7921 (insert "\n* ")))
7922 (run-hooks 'org-insert-heading-hook))
7924 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7927 ;; Maybe move at the end of the subtree
7928 (when (equal arg '(16))
7929 (org-up-heading-safe)
7930 (org-end-of-subtree t))
7931 ;; Insert a heading
7932 (save-restriction
7933 (widen)
7934 (let* ((level nil)
7935 (on-heading (org-at-heading-p))
7936 (empty-line-p (if on-heading
7937 (org-previous-line-empty-p)
7938 ;; We will decide later
7939 nil))
7940 ;; Get a level string to fall back on.
7941 (fix-level
7942 (if (org-before-first-heading-p) "*"
7943 (save-excursion
7944 (org-back-to-heading t)
7945 (when (org-previous-line-empty-p) (setq empty-line-p t))
7946 (looking-at org-outline-regexp)
7947 (make-string (1- (length (match-string 0))) ?*))))
7948 (stars
7949 (save-excursion
7950 (condition-case nil
7951 (if top "* "
7952 (org-back-to-heading invisible-ok)
7953 (when (and (not on-heading)
7954 (featurep 'org-inlinetask)
7955 (integerp org-inlinetask-min-level)
7956 (>= (length (match-string 0))
7957 org-inlinetask-min-level))
7958 ;; Find a heading level before the inline
7959 ;; task.
7960 (while (and (setq level (org-up-heading-safe))
7961 (>= level org-inlinetask-min-level)))
7962 (if (org-at-heading-p)
7963 (org-back-to-heading invisible-ok)
7964 (error "This should not happen")))
7965 (unless (and (save-excursion
7966 (save-match-data
7967 (org-backward-heading-same-level
7968 1 invisible-ok))
7969 (= (point) (match-beginning 0)))
7970 (not (org-next-line-empty-p)))
7971 (setq empty-line-p (or empty-line-p
7972 (org-previous-line-empty-p))))
7973 (match-string 0))
7974 (error (or fix-level "* ")))))
7975 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7976 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7978 ;; If we insert after content, move there and clean up
7979 ;; whitespace.
7980 (when respect-content
7981 (if (not (org-before-first-heading-p))
7982 (org-end-of-subtree nil t)
7983 (re-search-forward org-outline-regexp-bol)
7984 (beginning-of-line 0))
7985 (skip-chars-backward " \r\t\n")
7986 (and (not (looking-back "^\\*+" (line-beginning-position)))
7987 (looking-at "[ \t]+") (replace-match ""))
7988 (unless (eobp) (forward-char 1))
7989 (when (looking-at "^\\*")
7990 (unless (bobp) (backward-char 1))
7991 (insert "\n")))
7993 ;; If we are splitting, grab the text that should be moved
7994 ;; to the new headline.
7995 (when may-split
7996 (if (org-at-heading-p)
7997 ;; This is a heading: split intelligently (keeping
7998 ;; tags).
7999 (let ((pos (point)))
8000 (beginning-of-line)
8001 (unless (looking-at org-complex-heading-regexp)
8002 (error "This should not happen"))
8003 (when (and (match-beginning 4)
8004 (> pos (match-beginning 4))
8005 (< pos (match-end 4)))
8006 (setq initial-content (buffer-substring pos (match-end 4)))
8007 (goto-char pos)
8008 (delete-region (point) (match-end 4))
8009 (if (looking-at "[ \t]*$")
8010 (replace-match "")
8011 (insert (make-string (length initial-content) ?\s)))
8012 (setq initial-content (org-trim initial-content)))
8013 (goto-char pos))
8014 ;; A normal line.
8015 (setq initial-content
8016 (org-trim
8017 (delete-and-extract-region (point) (line-end-position))))))
8019 ;; If we are at the beginning of the line, insert before it.
8020 ;; Otherwise, after it.
8021 (cond
8022 ((and (bolp) (looking-at "[ \t]*$")))
8023 ((bolp) (save-excursion (insert "\n")))
8024 (t (end-of-line)
8025 (insert "\n")))
8027 ;; Insert the new heading
8028 (insert stars)
8029 (just-one-space)
8030 (insert initial-content)
8031 (unless (and blank (org-previous-line-empty-p))
8032 (org-N-empty-lines-before-current (if blank 1 0)))
8033 ;; Adjust visibility, which may be messed up if we removed
8034 ;; blank lines while previous entry was hidden.
8035 (let ((bol (line-beginning-position)))
8036 (dolist (o (overlays-at (1- bol)))
8037 (when (and (eq (overlay-get o 'invisible) 'outline)
8038 (eq (overlay-end o) bol))
8039 (move-overlay o (overlay-start o) (1- bol)))))
8040 (run-hooks 'org-insert-heading-hook)))))))
8042 (defun org-N-empty-lines-before-current (N)
8043 "Make the number of empty lines before current exactly N.
8044 So this will delete or add empty lines."
8045 (save-excursion
8046 (beginning-of-line)
8047 (let ((p (point)))
8048 (skip-chars-backward " \r\t\n")
8049 (unless (bolp) (forward-line))
8050 (delete-region (point) p))
8051 (when (> N 0) (insert (make-string N ?\n)))))
8053 (defun org-get-heading (&optional no-tags no-todo)
8054 "Return the heading of the current entry, without the stars.
8055 When NO-TAGS is non-nil, don't include tags.
8056 When NO-TODO is non-nil, don't include TODO keywords."
8057 (save-excursion
8058 (org-back-to-heading t)
8059 (let ((case-fold-search nil))
8060 (cond
8061 ((and no-tags no-todo)
8062 (looking-at org-complex-heading-regexp)
8063 ;; Return value has to be a string, but match group 4 is
8064 ;; optional.
8065 (or (match-string 4) ""))
8066 (no-tags
8067 (looking-at (concat org-outline-regexp
8068 "\\(.*?\\)"
8069 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8070 (match-string 1))
8071 (no-todo
8072 (looking-at org-todo-line-regexp)
8073 (match-string 3))
8074 (t (looking-at org-heading-regexp)
8075 (match-string 2))))))
8077 (defvar orgstruct-mode) ; defined below
8079 (defun org-heading-components ()
8080 "Return the components of the current heading.
8081 This is a list with the following elements:
8082 - the level as an integer
8083 - the reduced level, different if `org-odd-levels-only' is set.
8084 - the TODO keyword, or nil
8085 - the priority character, like ?A, or nil if no priority is given
8086 - the headline text itself, or the tags string if no headline text
8087 - the tags string, or nil."
8088 (save-excursion
8089 (org-back-to-heading t)
8090 (when (let (case-fold-search)
8091 (looking-at
8092 (if orgstruct-mode
8093 org-heading-regexp
8094 org-complex-heading-regexp)))
8095 (if orgstruct-mode
8096 (list (length (match-string 1))
8097 (org-reduced-level (length (match-string 1)))
8100 (match-string 2)
8101 nil)
8102 (list (length (match-string 1))
8103 (org-reduced-level (length (match-string 1)))
8104 (match-string-no-properties 2)
8105 (and (match-end 3) (aref (match-string 3) 2))
8106 (match-string-no-properties 4)
8107 (match-string-no-properties 5))))))
8109 (defun org-get-entry ()
8110 "Get the entry text, after heading, entire subtree."
8111 (save-excursion
8112 (org-back-to-heading t)
8113 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8115 (defun org-edit-headline (&optional heading)
8116 "Edit the current headline.
8117 Set it to HEADING when provided."
8118 (interactive)
8119 (org-with-wide-buffer
8120 (org-back-to-heading t)
8121 (when (looking-at org-complex-heading-regexp)
8122 (let* ((old (match-string-no-properties 4))
8123 (new (save-match-data
8124 (org-trim (or heading (read-string "Edit: " old))))))
8125 (unless (equal old new)
8126 (if old (replace-match new t t nil 4)
8127 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8128 (insert " " new))
8129 (org-set-tags nil t)
8130 (when (looking-at "[ \t]*$") (replace-match "")))))))
8132 (defun org-insert-heading-after-current ()
8133 "Insert a new heading with same level as current, after current subtree."
8134 (interactive)
8135 (org-back-to-heading)
8136 (org-insert-heading)
8137 (org-move-subtree-down)
8138 (end-of-line 1))
8140 (defun org-insert-heading-respect-content (&optional invisible-ok)
8141 "Insert heading with `org-insert-heading-respect-content' set to t."
8142 (interactive)
8143 (org-insert-heading '(4) invisible-ok))
8145 (defun org-insert-todo-heading-respect-content (&optional force-state)
8146 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8147 (interactive)
8148 (org-insert-todo-heading force-state '(4)))
8150 (defun org-insert-todo-heading (arg &optional force-heading)
8151 "Insert a new heading with the same level and TODO state as current heading.
8153 If the heading has no TODO state, or if the state is DONE, use
8154 the first state (TODO by default). Also with one prefix arg,
8155 force first state. With two prefix args, force inserting at the
8156 end of the parent subtree.
8158 When called at a plain list item, insert a new item with an
8159 unchecked check box."
8160 (interactive "P")
8161 (when (or force-heading (not (org-insert-item 'checkbox)))
8162 (org-insert-heading (or (and (equal arg '(16)) '(16))
8163 force-heading))
8164 (save-excursion
8165 (org-back-to-heading)
8166 (outline-previous-heading)
8167 (looking-at org-todo-line-regexp))
8168 (let* ((new-mark-x
8169 (if (or (equal arg '(4))
8170 (not (match-beginning 2))
8171 (member (match-string 2) org-done-keywords))
8172 (car org-todo-keywords-1)
8173 (match-string 2)))
8174 (new-mark
8176 (run-hook-with-args-until-success
8177 'org-todo-get-default-hook new-mark-x nil)
8178 new-mark-x)))
8179 (beginning-of-line 1)
8180 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8181 (if org-treat-insert-todo-heading-as-state-change
8182 (org-todo new-mark)
8183 (insert new-mark " "))))
8184 (when org-provide-todo-statistics
8185 (org-update-parent-todo-statistics))))
8187 (defun org-insert-subheading (arg)
8188 "Insert a new subheading and demote it.
8189 Works for outline headings and for plain lists alike."
8190 (interactive "P")
8191 (org-insert-heading arg)
8192 (cond
8193 ((org-at-heading-p) (org-do-demote))
8194 ((org-at-item-p) (org-indent-item))))
8196 (defun org-insert-todo-subheading (arg)
8197 "Insert a new subheading with TODO keyword or checkbox and demote it.
8198 Works for outline headings and for plain lists alike."
8199 (interactive "P")
8200 (org-insert-todo-heading arg)
8201 (cond
8202 ((org-at-heading-p) (org-do-demote))
8203 ((org-at-item-p) (org-indent-item))))
8205 ;;; Promotion and Demotion
8207 (defvar org-after-demote-entry-hook nil
8208 "Hook run after an entry has been demoted.
8209 The cursor will be at the beginning of the entry.
8210 When a subtree is being demoted, the hook will be called for each node.")
8212 (defvar org-after-promote-entry-hook nil
8213 "Hook run after an entry has been promoted.
8214 The cursor will be at the beginning of the entry.
8215 When a subtree is being promoted, the hook will be called for each node.")
8217 (defun org-promote-subtree ()
8218 "Promote the entire subtree.
8219 See also `org-promote'."
8220 (interactive)
8221 (save-excursion
8222 (org-with-limited-levels (org-map-tree 'org-promote)))
8223 (org-fix-position-after-promote))
8225 (defun org-demote-subtree ()
8226 "Demote the entire subtree.
8227 See `org-demote' and `org-promote'."
8228 (interactive)
8229 (save-excursion
8230 (org-with-limited-levels (org-map-tree 'org-demote)))
8231 (org-fix-position-after-promote))
8233 (defun org-do-promote ()
8234 "Promote the current heading higher up the tree.
8235 If the region is active in `transient-mark-mode', promote all
8236 headings in the region."
8237 (interactive)
8238 (save-excursion
8239 (if (org-region-active-p)
8240 (org-map-region 'org-promote (region-beginning) (region-end))
8241 (org-promote)))
8242 (org-fix-position-after-promote))
8244 (defun org-do-demote ()
8245 "Demote the current heading lower down the tree.
8246 If the region is active in `transient-mark-mode', demote all
8247 headings in the region."
8248 (interactive)
8249 (save-excursion
8250 (if (org-region-active-p)
8251 (org-map-region 'org-demote (region-beginning) (region-end))
8252 (org-demote)))
8253 (org-fix-position-after-promote))
8255 (defun org-fix-position-after-promote ()
8256 "Fix cursor position and indentation after demoting/promoting."
8257 (let ((pos (point)))
8258 (when (save-excursion
8259 (beginning-of-line 1)
8260 (looking-at org-todo-line-regexp)
8261 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8262 (cond ((eobp) (insert " "))
8263 ((eolp) (insert " "))
8264 ((equal (char-after) ?\ ) (forward-char 1))))))
8266 (defun org-current-level ()
8267 "Return the level of the current entry, or nil if before the first headline.
8268 The level is the number of stars at the beginning of the
8269 headline. Use `org-reduced-level' to remove the effect of
8270 `org-odd-levels'. Unlike to `org-outline-level', this function
8271 ignores inlinetasks."
8272 (let ((level (org-with-limited-levels (org-outline-level))))
8273 (and (> level 0) level)))
8275 (defun org-get-previous-line-level ()
8276 "Return the outline depth of the last headline before the current line.
8277 Returns 0 for the first headline in the buffer, and nil if before the
8278 first headline."
8279 (and (org-current-level)
8280 (or (and (/= (line-beginning-position) (point-min))
8281 (save-excursion (beginning-of-line 0) (org-current-level)))
8282 0)))
8284 (defun org-reduced-level (l)
8285 "Compute the effective level of a heading.
8286 This takes into account the setting of `org-odd-levels-only'."
8287 (cond
8288 ((zerop l) 0)
8289 (org-odd-levels-only (1+ (floor (/ l 2))))
8290 (t l)))
8292 (defun org-level-increment ()
8293 "Return the number of stars that will be added or removed at a
8294 time to headlines when structure editing, based on the value of
8295 `org-odd-levels-only'."
8296 (if org-odd-levels-only 2 1))
8298 (defun org-get-valid-level (level &optional change)
8299 "Rectify a level change under the influence of `org-odd-levels-only'
8300 LEVEL is a current level, CHANGE is by how much the level should be
8301 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8302 even level numbers will become the next higher odd number."
8303 (if org-odd-levels-only
8304 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8305 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8306 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8307 (max 1 (+ level (or change 0)))))
8309 (defun org-promote ()
8310 "Promote the current heading higher up the tree."
8311 (org-with-wide-buffer
8312 (org-back-to-heading t)
8313 (let* ((after-change-functions (remq 'flyspell-after-change-function
8314 after-change-functions))
8315 (level (save-match-data (funcall outline-level)))
8316 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8317 (diff (abs (- level (length up-head) -1))))
8318 (cond
8319 ((and (= level 1) org-allow-promoting-top-level-subtree)
8320 (replace-match "# " nil t))
8321 ((= level 1)
8322 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8323 (t (replace-match up-head nil t)))
8324 (unless (= level 1)
8325 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8326 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8327 (run-hooks 'org-after-promote-entry-hook))))
8329 (defun org-demote ()
8330 "Demote the current heading lower down the tree."
8331 (org-with-wide-buffer
8332 (org-back-to-heading t)
8333 (let* ((after-change-functions (remq 'flyspell-after-change-function
8334 after-change-functions))
8335 (level (save-match-data (funcall outline-level)))
8336 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8337 (diff (abs (- level (length down-head) -1))))
8338 (replace-match down-head nil t)
8339 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8340 (when org-adapt-indentation (org-fixup-indentation diff))
8341 (run-hooks 'org-after-demote-entry-hook))))
8343 (defun org-cycle-level ()
8344 "Cycle the level of an empty headline through possible states.
8345 This goes first to child, then to parent, level, then up the hierarchy.
8346 After top level, it switches back to sibling level."
8347 (interactive)
8348 (let ((org-adapt-indentation nil))
8349 (when (org-point-at-end-of-empty-headline)
8350 (setq this-command 'org-cycle-level) ; Only needed for caching
8351 (let ((cur-level (org-current-level))
8352 (prev-level (org-get-previous-line-level)))
8353 (cond
8354 ;; If first headline in file, promote to top-level.
8355 ((= prev-level 0)
8356 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8357 do (org-do-promote)))
8358 ;; If same level as prev, demote one.
8359 ((= prev-level cur-level)
8360 (org-do-demote))
8361 ;; If parent is top-level, promote to top level if not already.
8362 ((= prev-level 1)
8363 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8364 do (org-do-promote)))
8365 ;; If top-level, return to prev-level.
8366 ((= cur-level 1)
8367 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8368 do (org-do-demote)))
8369 ;; If less than prev-level, promote one.
8370 ((< cur-level prev-level)
8371 (org-do-promote))
8372 ;; If deeper than prev-level, promote until higher than
8373 ;; prev-level.
8374 ((> cur-level prev-level)
8375 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8376 do (org-do-promote))))
8377 t))))
8379 (defun org-map-tree (fun)
8380 "Call FUN for every heading underneath the current one."
8381 (org-back-to-heading t)
8382 (let ((level (funcall outline-level)))
8383 (save-excursion
8384 (funcall fun)
8385 (while (and (progn
8386 (outline-next-heading)
8387 (> (funcall outline-level) level))
8388 (not (eobp)))
8389 (funcall fun)))))
8391 (defun org-map-region (fun beg end)
8392 "Call FUN for every heading between BEG and END."
8393 (let ((org-ignore-region t))
8394 (save-excursion
8395 (setq end (copy-marker end))
8396 (goto-char beg)
8397 (when (and (re-search-forward org-outline-regexp-bol nil t)
8398 (< (point) end))
8399 (funcall fun))
8400 (while (and (progn
8401 (outline-next-heading)
8402 (< (point) end))
8403 (not (eobp)))
8404 (funcall fun)))))
8406 (defun org-fixup-indentation (diff)
8407 "Change the indentation in the current entry by DIFF.
8409 DIFF is an integer. Indentation is done according to the
8410 following rules:
8412 - Planning information and property drawers are always indented
8413 according to the new level of the headline;
8415 - Footnote definitions and their contents are ignored;
8417 - Inlinetasks' boundaries are not shifted;
8419 - Empty lines are ignored;
8421 - Other lines' indentation are shifted by DIFF columns, unless
8422 it would introduce a structural change in the document, in
8423 which case no shifting is done at all.
8425 Assume point is at a heading or an inlinetask beginning."
8426 (org-with-wide-buffer
8427 (narrow-to-region (line-beginning-position)
8428 (save-excursion
8429 (if (org-with-limited-levels (org-at-heading-p))
8430 (org-with-limited-levels (outline-next-heading))
8431 (org-inlinetask-goto-end))
8432 (point)))
8433 (forward-line)
8434 ;; Indent properly planning info and property drawer.
8435 (when (looking-at-p org-planning-line-re)
8436 (org-indent-line)
8437 (forward-line))
8438 (when (looking-at org-property-drawer-re)
8439 (goto-char (match-end 0))
8440 (forward-line)
8441 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8442 (catch 'no-shift
8443 (when (zerop diff) (throw 'no-shift nil))
8444 ;; If DIFF is negative, first check if a shift is possible at all
8445 ;; (e.g., it doesn't break structure). This can only happen if
8446 ;; some contents are not properly indented.
8447 (let ((case-fold-search t))
8448 (when (< diff 0)
8449 (let ((diff (- diff))
8450 (forbidden-re (concat org-outline-regexp
8451 "\\|"
8452 (substring org-footnote-definition-re 1))))
8453 (save-excursion
8454 (while (not (eobp))
8455 (cond
8456 ((looking-at-p "[ \t]*$") (forward-line))
8457 ((and (looking-at-p org-footnote-definition-re)
8458 (let ((e (org-element-at-point)))
8459 (and (eq (org-element-type e) 'footnote-definition)
8460 (goto-char (org-element-property :end e))))))
8461 ((looking-at-p org-outline-regexp) (forward-line))
8462 ;; Give up if shifting would move before column 0 or
8463 ;; if it would introduce a headline or a footnote
8464 ;; definition.
8466 (skip-chars-forward " \t")
8467 (let ((ind (current-column)))
8468 (when (or (< ind diff)
8469 (and (= ind diff) (looking-at-p forbidden-re)))
8470 (throw 'no-shift nil)))
8471 ;; Ignore contents of example blocks and source
8472 ;; blocks if their indentation is meant to be
8473 ;; preserved. Jump to block's closing line.
8474 (beginning-of-line)
8475 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8476 (let ((e (org-element-at-point)))
8477 (and (memq (org-element-type e)
8478 '(example-block src-block))
8479 (or org-src-preserve-indentation
8480 (org-element-property :preserve-indent e))
8481 (goto-char (org-element-property :end e))
8482 (progn (skip-chars-backward " \r\t\n")
8483 (beginning-of-line)
8484 t))))
8485 (forward-line))))))))
8486 ;; Shift lines but footnote definitions, inlinetasks boundaries
8487 ;; by DIFF. Also skip contents of source or example blocks
8488 ;; when indentation is meant to be preserved.
8489 (while (not (eobp))
8490 (cond
8491 ((and (looking-at-p org-footnote-definition-re)
8492 (let ((e (org-element-at-point)))
8493 (and (eq (org-element-type e) 'footnote-definition)
8494 (goto-char (org-element-property :end e))))))
8495 ((looking-at-p org-outline-regexp) (forward-line))
8496 ((looking-at-p "[ \t]*$") (forward-line))
8498 (indent-line-to (+ (org-get-indentation) diff))
8499 (beginning-of-line)
8500 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8501 (let ((e (org-element-at-point)))
8502 (and (memq (org-element-type e)
8503 '(example-block src-block))
8504 (or org-src-preserve-indentation
8505 (org-element-property :preserve-indent e))
8506 (goto-char (org-element-property :end e))
8507 (progn (skip-chars-backward " \r\t\n")
8508 (beginning-of-line)
8509 t))))
8510 (forward-line)))))))))
8512 (defun org-convert-to-odd-levels ()
8513 "Convert an Org file with all levels allowed to one with odd levels.
8514 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8515 level 5 etc."
8516 (interactive)
8517 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8518 (let ((outline-level 'org-outline-level)
8519 (org-odd-levels-only nil) n)
8520 (save-excursion
8521 (goto-char (point-min))
8522 (while (re-search-forward "^\\*\\*+ " nil t)
8523 (setq n (- (length (match-string 0)) 2))
8524 (while (>= (setq n (1- n)) 0)
8525 (org-demote))
8526 (end-of-line 1))))))
8528 (defun org-convert-to-oddeven-levels ()
8529 "Convert an Org file with only odd levels to one with odd/even levels.
8530 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8531 file contains a section with an even level, conversion would
8532 destroy the structure of the file. An error is signaled in this
8533 case."
8534 (interactive)
8535 (goto-char (point-min))
8536 ;; First check if there are no even levels
8537 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8538 (org-show-set-visibility 'canonical)
8539 (error "Not all levels are odd in this file. Conversion not possible"))
8540 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8541 (let ((outline-regexp org-outline-regexp)
8542 (outline-level 'org-outline-level)
8543 (org-odd-levels-only nil) n)
8544 (save-excursion
8545 (goto-char (point-min))
8546 (while (re-search-forward "^\\*\\*+ " nil t)
8547 (setq n (/ (1- (length (match-string 0))) 2))
8548 (while (>= (setq n (1- n)) 0)
8549 (org-promote))
8550 (end-of-line 1))))))
8552 (defun org-tr-level (n)
8553 "Make N odd if required."
8554 (if org-odd-levels-only (1+ (/ n 2)) n))
8556 ;;; Vertical tree motion, cutting and pasting of subtrees
8558 (defun org-move-subtree-up (&optional arg)
8559 "Move the current subtree up past ARG headlines of the same level."
8560 (interactive "p")
8561 (org-move-subtree-down (- (prefix-numeric-value arg))))
8563 (defun org-move-subtree-down (&optional arg)
8564 "Move the current subtree down past ARG headlines of the same level."
8565 (interactive "p")
8566 (setq arg (prefix-numeric-value arg))
8567 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8568 'org-get-last-sibling))
8569 (ins-point (make-marker))
8570 (cnt (abs arg))
8571 (col (current-column))
8572 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8573 ;; Select the tree
8574 (org-back-to-heading)
8575 (setq beg0 (point))
8576 (save-excursion
8577 (setq ne-beg (org-back-over-empty-lines))
8578 (setq beg (point)))
8579 (save-match-data
8580 (save-excursion (outline-end-of-heading)
8581 (setq folded (outline-invisible-p)))
8582 (progn (org-end-of-subtree nil t)
8583 (unless (eobp) (backward-char))))
8584 (outline-next-heading)
8585 (setq ne-end (org-back-over-empty-lines))
8586 (setq end (point))
8587 (goto-char beg0)
8588 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8589 ;; include less whitespace
8590 (save-excursion
8591 (goto-char beg)
8592 (forward-line (- ne-beg ne-end))
8593 (setq beg (point))))
8594 ;; Find insertion point, with error handling
8595 (while (> cnt 0)
8596 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8597 (progn (goto-char beg0)
8598 (user-error "Cannot move past superior level or buffer limit")))
8599 (setq cnt (1- cnt)))
8600 (when (> arg 0)
8601 ;; Moving forward - still need to move over subtree
8602 (org-end-of-subtree t t)
8603 (save-excursion
8604 (org-back-over-empty-lines)
8605 (or (bolp) (newline))))
8606 (setq ne-ins (org-back-over-empty-lines))
8607 (move-marker ins-point (point))
8608 (setq txt (buffer-substring beg end))
8609 (org-save-markers-in-region beg end)
8610 (delete-region beg end)
8611 (org-remove-empty-overlays-at beg)
8612 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8613 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8614 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8615 (let ((bbb (point)))
8616 (insert-before-markers txt)
8617 (org-reinstall-markers-in-region bbb)
8618 (move-marker ins-point bbb))
8619 (or (bolp) (insert "\n"))
8620 (setq ins-end (point))
8621 (goto-char ins-point)
8622 (org-skip-whitespace)
8623 (when (and (< arg 0)
8624 (org-first-sibling-p)
8625 (> ne-ins ne-beg))
8626 ;; Move whitespace back to beginning
8627 (save-excursion
8628 (goto-char ins-end)
8629 (let ((kill-whole-line t))
8630 (kill-line (- ne-ins ne-beg)) (point)))
8631 (insert (make-string (- ne-ins ne-beg) ?\n)))
8632 (move-marker ins-point nil)
8633 (if folded
8634 (outline-hide-subtree)
8635 (org-show-entry)
8636 (org-show-children)
8637 (org-cycle-hide-drawers 'children))
8638 (org-clean-visibility-after-subtree-move)
8639 ;; move back to the initial column we were at
8640 (move-to-column col)))
8642 (defvar org-subtree-clip ""
8643 "Clipboard for cut and paste of subtrees.
8644 This is actually only a copy of the kill, because we use the normal kill
8645 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8647 (defvar org-subtree-clip-folded nil
8648 "Was the last copied subtree folded?
8649 This is used to fold the tree back after pasting.")
8651 (defun org-cut-subtree (&optional n)
8652 "Cut the current subtree into the clipboard.
8653 With prefix arg N, cut this many sequential subtrees.
8654 This is a short-hand for marking the subtree and then cutting it."
8655 (interactive "p")
8656 (org-copy-subtree n 'cut))
8658 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8659 "Copy the current subtree it in the clipboard.
8660 With prefix arg N, copy this many sequential subtrees.
8661 This is a short-hand for marking the subtree and then copying it.
8662 If CUT is non-nil, actually cut the subtree.
8663 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8664 of some markers in the region, even if CUT is non-nil. This is
8665 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8666 (interactive "p")
8667 (let (beg end folded (beg0 (point)))
8668 (if (called-interactively-p 'any)
8669 (org-back-to-heading nil) ; take what looks like a subtree
8670 (org-back-to-heading t)) ; take what is really there
8671 (setq beg (point))
8672 (skip-chars-forward " \t\r\n")
8673 (save-match-data
8674 (if nosubtrees
8675 (outline-next-heading)
8676 (save-excursion (outline-end-of-heading)
8677 (setq folded (outline-invisible-p)))
8678 (ignore-errors (org-forward-heading-same-level (1- n) t))
8679 (org-end-of-subtree t t)))
8680 ;; Include the end of an inlinetask
8681 (when (and (featurep 'org-inlinetask)
8682 (looking-at-p (concat (org-inlinetask-outline-regexp)
8683 "END[ \t]*$")))
8684 (end-of-line))
8685 (setq end (point))
8686 (goto-char beg0)
8687 (when (> end beg)
8688 (setq org-subtree-clip-folded folded)
8689 (when (or cut force-store-markers)
8690 (org-save-markers-in-region beg end))
8691 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8692 (setq org-subtree-clip (current-kill 0))
8693 (message "%s: Subtree(s) with %d characters"
8694 (if cut "Cut" "Copied")
8695 (length org-subtree-clip)))))
8697 (defun org-paste-subtree (&optional level tree for-yank remove)
8698 "Paste the clipboard as a subtree, with modification of headline level.
8699 The entire subtree is promoted or demoted in order to match a new headline
8700 level.
8702 If the cursor is at the beginning of a headline, the same level as
8703 that headline is used to paste the tree.
8705 If not, the new level is derived from the *visible* headings
8706 before and after the insertion point, and taken to be the inferior headline
8707 level of the two. So if the previous visible heading is level 3 and the
8708 next is level 4 (or vice versa), level 4 will be used for insertion.
8709 This makes sure that the subtree remains an independent subtree and does
8710 not swallow low level entries.
8712 You can also force a different level, either by using a numeric prefix
8713 argument, or by inserting the heading marker by hand. For example, if the
8714 cursor is after \"*****\", then the tree will be shifted to level 5.
8716 If optional TREE is given, use this text instead of the kill ring.
8718 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8719 move back over whitespace before inserting, and move point to the end of
8720 the inserted text when done.
8722 When REMOVE is non-nil, remove the subtree from the clipboard."
8723 (interactive "P")
8724 (setq tree (or tree (and kill-ring (current-kill 0))))
8725 (unless (org-kill-is-subtree-p tree)
8726 (user-error "%s"
8727 (substitute-command-keys
8728 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8729 (org-with-limited-levels
8730 (let* ((visp (not (outline-invisible-p)))
8731 (txt tree)
8732 (^re_ "\\(\\*+\\)[ \t]*")
8733 (old-level (if (string-match org-outline-regexp-bol txt)
8734 (- (match-end 0) (match-beginning 0) 1)
8735 -1))
8736 (force-level (cond (level (prefix-numeric-value level))
8737 ((and (looking-at "[ \t]*$")
8738 (string-match
8739 "^\\*+$" (buffer-substring
8740 (point-at-bol) (point))))
8741 (- (match-end 0) (match-beginning 0)))
8742 ((and (bolp)
8743 (looking-at org-outline-regexp))
8744 (- (match-end 0) (point) 1))))
8745 (previous-level (save-excursion
8746 (condition-case nil
8747 (progn
8748 (outline-previous-visible-heading 1)
8749 (if (looking-at ^re_)
8750 (- (match-end 0) (match-beginning 0) 1)
8752 (error 1))))
8753 (next-level (save-excursion
8754 (condition-case nil
8755 (progn
8756 (or (looking-at org-outline-regexp)
8757 (outline-next-visible-heading 1))
8758 (if (looking-at ^re_)
8759 (- (match-end 0) (match-beginning 0) 1)
8761 (error 1))))
8762 (new-level (or force-level (max previous-level next-level)))
8763 (shift (if (or (= old-level -1)
8764 (= new-level -1)
8765 (= old-level new-level))
8767 (- new-level old-level)))
8768 (delta (if (> shift 0) -1 1))
8769 (func (if (> shift 0) 'org-demote 'org-promote))
8770 (org-odd-levels-only nil)
8771 beg end newend)
8772 ;; Remove the forced level indicator
8773 (when force-level
8774 (delete-region (point-at-bol) (point)))
8775 ;; Paste
8776 (beginning-of-line (if (bolp) 1 2))
8777 (setq beg (point))
8778 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8779 (insert-before-markers txt)
8780 (unless (string-suffix-p "\n" txt) (insert "\n"))
8781 (setq newend (point))
8782 (org-reinstall-markers-in-region beg)
8783 (setq end (point))
8784 (goto-char beg)
8785 (skip-chars-forward " \t\n\r")
8786 (setq beg (point))
8787 (when (and (outline-invisible-p) visp)
8788 (save-excursion (outline-show-heading)))
8789 ;; Shift if necessary
8790 (unless (= shift 0)
8791 (save-restriction
8792 (narrow-to-region beg end)
8793 (while (not (= shift 0))
8794 (org-map-region func (point-min) (point-max))
8795 (setq shift (+ delta shift)))
8796 (goto-char (point-min))
8797 (setq newend (point-max))))
8798 (when (or (called-interactively-p 'interactive) for-yank)
8799 (message "Clipboard pasted as level %d subtree" new-level))
8800 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8801 kill-ring
8802 (eq org-subtree-clip (current-kill 0))
8803 org-subtree-clip-folded)
8804 ;; The tree was folded before it was killed/copied
8805 (outline-hide-subtree))
8806 (and for-yank (goto-char newend))
8807 (and remove (setq kill-ring (cdr kill-ring))))))
8809 (defun org-kill-is-subtree-p (&optional txt)
8810 "Check if the current kill is an outline subtree, or a set of trees.
8811 Returns nil if kill does not start with a headline, or if the first
8812 headline level is not the largest headline level in the tree.
8813 So this will actually accept several entries of equal levels as well,
8814 which is OK for `org-paste-subtree'.
8815 If optional TXT is given, check this string instead of the current kill."
8816 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8817 (re (org-get-limited-outline-regexp))
8818 (^re (concat "^" re))
8819 (start-level (and kill
8820 (string-match
8821 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8822 kill)
8823 (- (match-end 2) (match-beginning 2) 1)))
8824 (start (1+ (or (match-beginning 2) -1))))
8825 (if (not start-level)
8826 (progn
8827 nil) ;; does not even start with a heading
8828 (catch 'exit
8829 (while (setq start (string-match ^re kill (1+ start)))
8830 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8831 (throw 'exit nil)))
8832 t))))
8834 (defvar org-markers-to-move nil
8835 "Markers that should be moved with a cut-and-paste operation.
8836 Those markers are stored together with their positions relative to
8837 the start of the region.")
8839 (defun org-save-markers-in-region (beg end)
8840 "Check markers in region.
8841 If these markers are between BEG and END, record their position relative
8842 to BEG, so that after moving the block of text, we can put the markers back
8843 into place.
8844 This function gets called just before an entry or tree gets cut from the
8845 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8846 called immediately, to move the markers with the entries."
8847 (setq org-markers-to-move nil)
8848 (when (featurep 'org-clock)
8849 (org-clock-save-markers-for-cut-and-paste beg end))
8850 (when (featurep 'org-agenda)
8851 (org-agenda-save-markers-for-cut-and-paste beg end)))
8853 (defun org-check-and-save-marker (marker beg end)
8854 "Check if MARKER is between BEG and END.
8855 If yes, remember the marker and the distance to BEG."
8856 (when (and (marker-buffer marker)
8857 (equal (marker-buffer marker) (current-buffer))
8858 (>= marker beg) (< marker end))
8859 (push (cons marker (- marker beg)) org-markers-to-move)))
8861 (defun org-reinstall-markers-in-region (beg)
8862 "Move all remembered markers to their position relative to BEG."
8863 (dolist (x org-markers-to-move)
8864 (move-marker (car x) (+ beg (cdr x))))
8865 (setq org-markers-to-move nil))
8867 (defun org-narrow-to-subtree ()
8868 "Narrow buffer to the current subtree."
8869 (interactive)
8870 (save-excursion
8871 (save-match-data
8872 (org-with-limited-levels
8873 (narrow-to-region
8874 (progn (org-back-to-heading t) (point))
8875 (progn (org-end-of-subtree t t)
8876 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8877 (point)))))))
8879 (defun org-narrow-to-block ()
8880 "Narrow buffer to the current block."
8881 (interactive)
8882 (let* ((case-fold-search t)
8883 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8884 "^[ \t]*#\\+end_.*")))
8885 (if blockp
8886 (narrow-to-region (car blockp) (cdr blockp))
8887 (user-error "Not in a block"))))
8889 (defun org-clone-subtree-with-time-shift (n &optional shift)
8890 "Clone the task (subtree) at point N times.
8891 The clones will be inserted as siblings.
8893 In interactive use, the user will be prompted for the number of
8894 clones to be produced. If the entry has a timestamp, the user
8895 will also be prompted for a time shift, which may be a repeater
8896 as used in time stamps, for example `+3d'. To disable this,
8897 you can call the function with a universal prefix argument.
8899 When a valid repeater is given and the entry contains any time
8900 stamps, the clones will become a sequence in time, with time
8901 stamps in the subtree shifted for each clone produced. If SHIFT
8902 is nil or the empty string, time stamps will be left alone. The
8903 ID property of the original subtree is removed.
8905 In each clone, all the CLOCK entries will be removed. This
8906 prevents Org from considering that the clocked times overlap.
8908 If the original subtree did contain time stamps with a repeater,
8909 the following will happen:
8910 - the repeater will be removed in each clone
8911 - an additional clone will be produced, with the current, unshifted
8912 date(s) in the entry.
8913 - the original entry will be placed *after* all the clones, with
8914 repeater intact.
8915 - the start days in the repeater in the original entry will be shifted
8916 to past the last clone.
8917 In this way you can spell out a number of instances of a repeating task,
8918 and still retain the repeater to cover future instances of the task.
8920 As described above, N+1 clones are produced when the original
8921 subtree has a repeater. Setting N to 0, then, can be used to
8922 remove the repeater from a subtree and create a shifted clone
8923 with the original repeater."
8924 (interactive "nNumber of clones to produce: ")
8925 (let ((shift
8926 (or shift
8927 (if (and (not (equal current-prefix-arg '(4)))
8928 (save-excursion
8929 (re-search-forward org-ts-regexp-both
8930 (save-excursion
8931 (org-end-of-subtree t)
8932 (point)) t)))
8933 (read-from-minibuffer
8934 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8935 ""))) ;; No time shift
8936 (n-no-remove -1)
8937 (drawer-re org-drawer-regexp)
8938 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8939 beg end template task idprop
8940 shift-n shift-what doshift nmin nmax)
8941 (unless (wholenump n)
8942 (user-error "Invalid number of replications %s" n))
8943 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8944 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8945 shift)))
8946 (user-error "Invalid shift specification %s" shift))
8947 (when doshift
8948 (setq shift-n (string-to-number (match-string 1 shift))
8949 shift-what (cdr (assoc (match-string 2 shift)
8950 '(("d" . day) ("w" . week)
8951 ("m" . month) ("y" . year))))))
8952 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8953 (setq nmin 1 nmax n)
8954 (org-back-to-heading t)
8955 (setq beg (point))
8956 (setq idprop (org-entry-get nil "ID"))
8957 (org-end-of-subtree t t)
8958 (or (bolp) (insert "\n"))
8959 (setq end (point))
8960 (setq template (buffer-substring beg end))
8961 (when (and doshift
8962 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8963 (delete-region beg end)
8964 (setq end beg)
8965 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8966 (goto-char end)
8967 (cl-loop for n from nmin to nmax do
8968 ;; prepare clone
8969 (with-temp-buffer
8970 (insert template)
8971 (org-mode)
8972 (goto-char (point-min))
8973 (org-show-subtree)
8974 (and idprop (if org-clone-delete-id
8975 (org-entry-delete nil "ID")
8976 (org-id-get-create t)))
8977 (unless (= n 0)
8978 (while (re-search-forward org-clock-re nil t)
8979 (kill-whole-line))
8980 (goto-char (point-min))
8981 (while (re-search-forward drawer-re nil t)
8982 (org-remove-empty-drawer-at (point))))
8983 (goto-char (point-min))
8984 (when doshift
8985 (while (re-search-forward org-ts-regexp-both nil t)
8986 (org-timestamp-change (* n shift-n) shift-what))
8987 (unless (= n n-no-remove)
8988 (goto-char (point-min))
8989 (while (re-search-forward org-ts-regexp nil t)
8990 (save-excursion
8991 (goto-char (match-beginning 0))
8992 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8993 (delete-region (match-beginning 1) (match-end 1)))))))
8994 (setq task (buffer-string)))
8995 (insert task))
8996 (goto-char beg)))
8998 ;;; Outline Sorting
9000 (defun org-sort (with-case)
9001 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9002 Optional argument WITH-CASE means sort case-sensitively."
9003 (interactive "P")
9004 (cond
9005 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9006 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9008 (org-call-with-arg 'org-sort-entries with-case))))
9010 (defun org-sort-remove-invisible (s)
9011 "Remove invisible links from string S."
9012 (remove-text-properties 0 (length s) org-rm-props s)
9013 (while (string-match org-bracket-link-regexp s)
9014 (setq s (replace-match (if (match-end 2)
9015 (match-string 3 s)
9016 (match-string 1 s))
9017 t t s)))
9018 (let ((st (format " %s " s)))
9019 (while (string-match org-emph-re st)
9020 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9021 (setq s (substring st 1 -1)))
9024 (defvar org-priority-regexp) ; defined later in the file
9026 (defvar org-after-sorting-entries-or-items-hook nil
9027 "Hook that is run after a bunch of entries or items have been sorted.
9028 When children are sorted, the cursor is in the parent line when this
9029 hook gets called. When a region or a plain list is sorted, the cursor
9030 will be in the first entry of the sorted region/list.")
9032 (defun org-sort-entries
9033 (&optional with-case sorting-type getkey-func compare-func property)
9034 "Sort entries on a certain level of an outline tree.
9035 If there is an active region, the entries in the region are sorted.
9036 Else, if the cursor is before the first entry, sort the top-level items.
9037 Else, the children of the entry at point are sorted.
9039 Sorting can be alphabetically, numerically, by date/time as given by
9040 a time stamp, by a property, by priority order, or by a custom function.
9042 The command prompts for the sorting type unless it has been given to the
9043 function through the SORTING-TYPE argument, which needs to be a character,
9044 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9045 the precise meaning of each character:
9047 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9048 c By creation time, which is assumed to be the first inactive time stamp
9049 at the beginning of a line.
9050 d By deadline date/time.
9051 k By clocking time.
9052 n Numerically, by converting the beginning of the entry/item to a number.
9053 o By order of TODO keywords.
9054 p By priority according to the cookie.
9055 r By the value of a property.
9056 s By scheduled date/time.
9057 t By date/time, either the first active time stamp in the entry, or, if
9058 none exist, by the first inactive one.
9060 Capital letters will reverse the sort order.
9062 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9063 called with point at the beginning of the record. It must return either
9064 a string or a number that should serve as the sorting key for that record.
9066 Comparing entries ignores case by default. However, with an optional argument
9067 WITH-CASE, the sorting considers case as well.
9069 Sorting is done against the visible part of the headlines, it ignores hidden
9070 links.
9072 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9073 (interactive "P")
9074 (let ((case-func (if with-case 'identity 'downcase))
9075 (cmstr
9076 ;; The clock marker is lost when using `sort-subr', let's
9077 ;; store the clocking string.
9078 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9079 (save-excursion
9080 (goto-char org-clock-marker)
9081 (buffer-substring-no-properties (line-beginning-position)
9082 (point)))))
9083 start beg end stars re re2
9084 txt what tmp)
9085 ;; Find beginning and end of region to sort
9086 (cond
9087 ((org-region-active-p)
9088 ;; we will sort the region
9089 (setq end (region-end)
9090 what "region")
9091 (goto-char (region-beginning))
9092 (unless (org-at-heading-p) (outline-next-heading))
9093 (setq start (point)))
9094 ((or (org-at-heading-p)
9095 (ignore-errors (progn (org-back-to-heading) t)))
9096 ;; we will sort the children of the current headline
9097 (org-back-to-heading)
9098 (setq start (point)
9099 end (progn (org-end-of-subtree t t)
9100 (or (bolp) (insert "\n"))
9101 (when (>= (org-back-over-empty-lines) 1)
9102 (forward-line 1))
9103 (point))
9104 what "children")
9105 (goto-char start)
9106 (outline-show-subtree)
9107 (outline-next-heading))
9109 ;; we will sort the top-level entries in this file
9110 (goto-char (point-min))
9111 (or (org-at-heading-p) (outline-next-heading))
9112 (setq start (point))
9113 (goto-char (point-max))
9114 (beginning-of-line 1)
9115 (when (looking-at ".*?\\S-")
9116 ;; File ends in a non-white line
9117 (end-of-line 1)
9118 (insert "\n"))
9119 (setq end (point-max))
9120 (setq what "top-level")
9121 (goto-char start)
9122 (outline-show-all)))
9124 (setq beg (point))
9125 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9127 (looking-at "\\(\\*+\\)")
9128 (setq stars (match-string 1)
9129 re (concat "^" (regexp-quote stars) " +")
9130 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9131 txt (buffer-substring beg end))
9132 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9133 (when (and (not (equal stars "*")) (string-match re2 txt))
9134 (user-error "Region to sort contains a level above the first entry"))
9136 (unless sorting-type
9137 (message
9138 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9139 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9140 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9141 what)
9142 (setq sorting-type (read-char-exclusive))
9144 (unless getkey-func
9145 (and (= (downcase sorting-type) ?f)
9146 (setq getkey-func
9147 (completing-read "Sort using function: "
9148 obarray 'fboundp t nil nil))
9149 (setq getkey-func (intern getkey-func))))
9151 (and (= (downcase sorting-type) ?r)
9152 (not property)
9153 (setq property
9154 (completing-read "Property: "
9155 (mapcar #'list (org-buffer-property-keys t))
9156 nil t))))
9158 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9159 (message "Sorting entries...")
9161 (save-restriction
9162 (narrow-to-region start end)
9163 (let ((dcst (downcase sorting-type))
9164 (case-fold-search nil)
9165 (now (current-time)))
9166 (sort-subr
9167 (/= dcst sorting-type)
9168 ;; This function moves to the beginning character of the "record" to
9169 ;; be sorted.
9170 (lambda nil
9171 (if (re-search-forward re nil t)
9172 (goto-char (match-beginning 0))
9173 (goto-char (point-max))))
9174 ;; This function moves to the last character of the "record" being
9175 ;; sorted.
9176 (lambda nil
9177 (save-match-data
9178 (condition-case nil
9179 (outline-forward-same-level 1)
9180 (error
9181 (goto-char (point-max))))))
9182 ;; This function returns the value that gets sorted against.
9183 (lambda nil
9184 (cond
9185 ((= dcst ?n)
9186 (if (looking-at org-complex-heading-regexp)
9187 (string-to-number (org-sort-remove-invisible (match-string 4)))
9188 nil))
9189 ((= dcst ?a)
9190 (if (looking-at org-complex-heading-regexp)
9191 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9192 nil))
9193 ((= dcst ?k)
9194 (or (get-text-property (point) :org-clock-minutes) 0))
9195 ((= dcst ?t)
9196 (let ((end (save-excursion (outline-next-heading) (point))))
9197 (if (or (re-search-forward org-ts-regexp end t)
9198 (re-search-forward org-ts-regexp-both end t))
9199 (org-time-string-to-seconds (match-string 0))
9200 (float-time now))))
9201 ((= dcst ?c)
9202 (let ((end (save-excursion (outline-next-heading) (point))))
9203 (if (re-search-forward
9204 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9205 end t)
9206 (org-time-string-to-seconds (match-string 0))
9207 (float-time now))))
9208 ((= dcst ?s)
9209 (let ((end (save-excursion (outline-next-heading) (point))))
9210 (if (re-search-forward org-scheduled-time-regexp end t)
9211 (org-time-string-to-seconds (match-string 1))
9212 (float-time now))))
9213 ((= dcst ?d)
9214 (let ((end (save-excursion (outline-next-heading) (point))))
9215 (if (re-search-forward org-deadline-time-regexp end t)
9216 (org-time-string-to-seconds (match-string 1))
9217 (float-time now))))
9218 ((= dcst ?p)
9219 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9220 (string-to-char (match-string 2))
9221 org-default-priority))
9222 ((= dcst ?r)
9223 (or (org-entry-get nil property) ""))
9224 ((= dcst ?o)
9225 (when (looking-at org-complex-heading-regexp)
9226 (let* ((m (match-string 2))
9227 (s (if (member m org-done-keywords) '- '+)))
9228 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9229 ((= dcst ?f)
9230 (if getkey-func
9231 (progn
9232 (setq tmp (funcall getkey-func))
9233 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9234 tmp)
9235 (error "Invalid key function `%s'" getkey-func)))
9236 (t (error "Invalid sorting type `%c'" sorting-type))))
9238 (cond
9239 ((= dcst ?a) 'string<)
9240 ((= dcst ?f) compare-func)
9241 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9242 (run-hooks 'org-after-sorting-entries-or-items-hook)
9243 ;; Reset the clock marker if needed
9244 (when cmstr
9245 (save-excursion
9246 (goto-char start)
9247 (search-forward cmstr nil t)
9248 (move-marker org-clock-marker (point))))
9249 (message "Sorting entries...done")))
9251 ;;; The orgstruct minor mode
9253 ;; Define a minor mode which can be used in other modes in order to
9254 ;; integrate the Org mode structure editing commands.
9256 ;; This is really a hack, because the Org mode structure commands use
9257 ;; keys which normally belong to the major mode. Here is how it
9258 ;; works: The minor mode defines all the keys necessary to operate the
9259 ;; structure commands, but wraps the commands into a function which
9260 ;; tests if the cursor is currently at a headline or a plain list
9261 ;; item. If that is the case, the structure command is used,
9262 ;; temporarily setting many Org mode variables like regular
9263 ;; expressions for filling etc. However, when any of those keys is
9264 ;; used at a different location, function uses `key-binding' to look
9265 ;; up if the key has an associated command in another currently active
9266 ;; keymap (minor modes, major mode, global), and executes that
9267 ;; command. There might be problems if any of the keys is otherwise
9268 ;; used as a prefix key.
9270 (defcustom orgstruct-heading-prefix-regexp ""
9271 "Regexp that matches the custom prefix of Org headlines in
9272 orgstruct(++)-mode."
9273 :group 'org
9274 :version "24.4"
9275 :package-version '(Org . "8.3")
9276 :type 'regexp)
9277 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9279 (defcustom orgstruct-setup-hook nil
9280 "Hook run after orgstruct-mode-map is filled."
9281 :group 'org
9282 :version "24.4"
9283 :package-version '(Org . "8.0")
9284 :type 'hook)
9286 (defvar orgstruct-initialized nil)
9288 (defvar org-local-vars nil
9289 "List of local variables, for use by `orgstruct-mode'.")
9291 ;;;###autoload
9292 (define-minor-mode orgstruct-mode
9293 "Toggle the minor mode `orgstruct-mode'.
9294 This mode is for using Org mode structure commands in other
9295 modes. The following keys behave as if Org mode were active, if
9296 the cursor is on a headline, or on a plain list item (both as
9297 defined by Org mode)."
9298 nil " OrgStruct" (make-sparse-keymap)
9299 (funcall (if orgstruct-mode
9300 'add-to-invisibility-spec
9301 'remove-from-invisibility-spec)
9302 '(outline . t))
9303 (when orgstruct-mode
9304 (org-load-modules-maybe)
9305 (unless orgstruct-initialized
9306 (orgstruct-setup)
9307 (setq orgstruct-initialized t))))
9309 ;;;###autoload
9310 (defun turn-on-orgstruct ()
9311 "Unconditionally turn on `orgstruct-mode'."
9312 (orgstruct-mode 1))
9314 (defvar-local orgstruct-is-++ nil
9315 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9316 (defvar-local org-fb-vars nil)
9317 (defun orgstruct++-mode (&optional arg)
9318 "Toggle `orgstruct-mode', the enhanced version of it.
9319 In addition to setting orgstruct-mode, this also exports all
9320 indentation and autofilling variables from Org mode into the
9321 buffer. It will also recognize item context in multiline items."
9322 (interactive "P")
9323 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9324 (if (< arg 1)
9325 (progn (orgstruct-mode -1)
9326 (dolist (v org-fb-vars)
9327 (set (make-local-variable (car v))
9328 (if (eq (car-safe (cadr v)) 'quote)
9329 (cl-cadadr v)
9330 (nth 1 v)))))
9331 (orgstruct-mode 1)
9332 (setq org-fb-vars nil)
9333 (unless org-local-vars
9334 (setq org-local-vars (org-get-local-variables)))
9335 (let (var val)
9336 (dolist (x org-local-vars)
9337 (when (string-match
9338 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9339 \\|fill-prefix\\|indent-\\)"
9340 (symbol-name (car x)))
9341 (setq var (car x) val (nth 1 x))
9342 (push (list var `(quote ,(eval var))) org-fb-vars)
9343 (set (make-local-variable var)
9344 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9345 (setq-local orgstruct-is-++ t))))
9347 ;;;###autoload
9348 (defun turn-on-orgstruct++ ()
9349 "Unconditionally turn on `orgstruct++-mode'."
9350 (orgstruct++-mode 1))
9352 (defun orgstruct-error ()
9353 "Error when there is no default binding for a structure key."
9354 (interactive)
9355 (funcall (if (fboundp 'user-error)
9356 'user-error
9357 'error)
9358 "This key has no function outside structure elements"))
9360 (defun orgstruct-setup ()
9361 "Setup orgstruct keymap."
9362 (dolist (cell '((org-demote . t)
9363 (org-metaleft . t)
9364 (org-metaright . t)
9365 (org-promote . t)
9366 (org-shiftmetaleft . t)
9367 (org-shiftmetaright . t)
9368 org-backward-element
9369 org-backward-heading-same-level
9370 org-ctrl-c-ret
9371 org-ctrl-c-minus
9372 org-ctrl-c-star
9373 org-cycle
9374 org-force-cycle-archived
9375 org-forward-heading-same-level
9376 org-insert-heading
9377 org-insert-heading-respect-content
9378 org-kill-note-or-show-branches
9379 org-mark-subtree
9380 org-meta-return
9381 org-metadown
9382 org-metaup
9383 org-narrow-to-subtree
9384 org-promote-subtree
9385 org-reveal
9386 org-shiftdown
9387 org-shiftleft
9388 org-shiftmetadown
9389 org-shiftmetaup
9390 org-shiftright
9391 org-shifttab
9392 org-shifttab
9393 org-shiftup
9394 org-show-children
9395 org-show-subtree
9396 org-sort
9397 org-up-element
9398 outline-demote
9399 outline-next-visible-heading
9400 outline-previous-visible-heading
9401 outline-promote
9402 outline-up-heading))
9403 (let ((f (or (car-safe cell) cell))
9404 (disable-when-heading-prefix (cdr-safe cell)))
9405 (when (fboundp f)
9406 (let ((new-bindings))
9407 (dolist (binding (nconc (where-is-internal f org-mode-map)
9408 (where-is-internal f outline-mode-map)))
9409 (push binding new-bindings)
9410 ;; TODO use local-function-key-map
9411 (dolist (rep '(("<tab>" . "TAB")
9412 ("<return>" . "RET")
9413 ("<escape>" . "ESC")
9414 ("<delete>" . "DEL")))
9415 (setq binding (read-kbd-macro
9416 (let ((case-fold-search))
9417 (replace-regexp-in-string
9418 (regexp-quote (cdr rep))
9419 (car rep)
9420 (key-description binding)))))
9421 (cl-pushnew binding new-bindings :test 'equal)))
9422 (dolist (binding new-bindings)
9423 (let ((key (lookup-key orgstruct-mode-map binding)))
9424 (when (or (not key) (numberp key))
9425 (ignore-errors
9426 (org-defkey orgstruct-mode-map
9427 binding
9428 (orgstruct-make-binding
9429 f binding disable-when-heading-prefix))))))))))
9430 (run-hooks 'orgstruct-setup-hook))
9432 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9433 "Create a function for binding in the structure minor mode.
9434 FUN is the command to call inside a table. KEY is the key that
9435 should be checked in for a command to execute outside of tables.
9436 Non-nil `disable-when-heading-prefix' means to disable the command
9437 if `orgstruct-heading-prefix-regexp' is not empty."
9438 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9439 (let ((nname name)
9440 (i 0))
9441 (while (fboundp (intern nname))
9442 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9443 (setq name (intern nname)))
9444 (eval
9445 (let ((bindings '((org-heading-regexp
9446 (concat "^"
9447 orgstruct-heading-prefix-regexp
9448 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9449 (org-outline-regexp
9450 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9451 (org-outline-regexp-bol
9452 (concat "^" org-outline-regexp))
9453 (outline-regexp org-outline-regexp)
9454 (outline-heading-end-regexp "\n")
9455 (outline-level 'org-outline-level)
9456 (outline-heading-alist))))
9457 `(defun ,name (arg)
9458 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9459 "Outside of structure, run the binding of `"
9460 (key-description key) "'."
9461 (when disable-when-heading-prefix
9462 (concat
9463 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9464 "back to the default binding due to limitations of Org's implementation of\n"
9465 "`" (symbol-name fun) "'.")))
9466 (interactive "p")
9467 (let* ((disable
9468 ,(and disable-when-heading-prefix
9469 '(not (string= orgstruct-heading-prefix-regexp ""))))
9470 (fallback
9471 (or disable
9472 (not
9473 (let* ,bindings
9474 (org-context-p 'headline 'item
9475 ,(when (memq fun
9476 '(org-insert-heading
9477 org-insert-heading-respect-content
9478 org-meta-return))
9479 '(when orgstruct-is-++
9480 'item-body))))))))
9481 (if fallback
9482 (let* ((orgstruct-mode)
9483 (binding
9484 (let ((key ,key))
9485 (catch 'exit
9486 (dolist
9487 (rep
9488 '(nil
9489 ("<\\([^>]*\\)tab>" . "\\1TAB")
9490 ("<\\([^>]*\\)return>" . "\\1RET")
9491 ("<\\([^>]*\\)escape>" . "\\1ESC")
9492 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9493 nil)
9494 (when rep
9495 (setq key (read-kbd-macro
9496 (let ((case-fold-search))
9497 (replace-regexp-in-string
9498 (car rep)
9499 (cdr rep)
9500 (key-description key))))))
9501 (when (key-binding key)
9502 (throw 'exit (key-binding key))))))))
9503 (if (keymapp binding)
9504 (org-set-transient-map binding)
9505 (let ((func (or binding
9506 (unless disable
9507 'orgstruct-error))))
9508 (when func
9509 (call-interactively func)))))
9510 (org-run-like-in-org-mode
9511 (lambda ()
9512 (interactive)
9513 (let* ,bindings
9514 (call-interactively ',fun)))))))))
9515 name))
9517 (defun org-contextualize-keys (alist contexts)
9518 "Return valid elements in ALIST depending on CONTEXTS.
9520 `org-agenda-custom-commands' or `org-capture-templates' are the
9521 values used for ALIST, and `org-agenda-custom-commands-contexts'
9522 or `org-capture-templates-contexts' are the associated contexts
9523 definitions."
9524 (let ((contexts
9525 ;; normalize contexts
9526 (mapcar
9527 (lambda(c) (cond ((listp (cadr c))
9528 (list (car c) (car c) (nth 1 c)))
9529 ((string= "" (cadr c))
9530 (list (car c) (car c) (nth 2 c)))
9531 (t c)))
9532 contexts))
9533 (a alist) r s)
9534 ;; loop over all commands or templates
9535 (dolist (c a)
9536 (let (vrules repl)
9537 (cond
9538 ((not (assoc (car c) contexts))
9539 (push c r))
9540 ((and (assoc (car c) contexts)
9541 (setq vrules (org-contextualize-validate-key
9542 (car c) contexts)))
9543 (mapc (lambda (vr)
9544 (unless (equal (car vr) (cadr vr))
9545 (setq repl vr)))
9546 vrules)
9547 (if (not repl) (push c r)
9548 (push (cadr repl) s)
9549 (push
9550 (cons (car c)
9551 (cdr (or (assoc (cadr repl) alist)
9552 (error "Undefined key `%s' as contextual replacement for `%s'"
9553 (cadr repl) (car c)))))
9554 r))))))
9555 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9556 (delq
9558 (delete-dups
9559 (mapcar (lambda (x)
9560 (let ((tpl (car x)))
9561 (unless (delq
9563 (mapcar (lambda (y)
9564 (equal y tpl))
9566 x)))
9567 (reverse r))))))
9569 (defun org-contextualize-validate-key (key contexts)
9570 "Check CONTEXTS for agenda or capture KEY."
9571 (let (res)
9572 (dolist (r contexts)
9573 (dolist (rr (car (last r)))
9574 (when
9575 (and (equal key (car r))
9576 (if (functionp rr) (funcall rr)
9577 (or (and (eq (car rr) 'in-file)
9578 (buffer-file-name)
9579 (string-match (cdr rr) (buffer-file-name)))
9580 (and (eq (car rr) 'in-mode)
9581 (string-match (cdr rr) (symbol-name major-mode)))
9582 (and (eq (car rr) 'in-buffer)
9583 (string-match (cdr rr) (buffer-name)))
9584 (when (and (eq (car rr) 'not-in-file)
9585 (buffer-file-name))
9586 (not (string-match (cdr rr) (buffer-file-name))))
9587 (when (eq (car rr) 'not-in-mode)
9588 (not (string-match (cdr rr) (symbol-name major-mode))))
9589 (when (eq (car rr) 'not-in-buffer)
9590 (not (string-match (cdr rr) (buffer-name)))))))
9591 (push r res))))
9592 (delete-dups (delq nil res))))
9594 (defun org-context-p (&rest contexts)
9595 "Check if local context is any of CONTEXTS.
9596 Possible values in the list of contexts are `table', `headline', and `item'."
9597 (let ((pos (point)))
9598 (goto-char (point-at-bol))
9599 (prog1 (or (and (memq 'table contexts)
9600 (looking-at "[ \t]*|"))
9601 (and (memq 'headline contexts)
9602 (looking-at org-outline-regexp))
9603 (and (memq 'item contexts)
9604 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9605 (and (memq 'item-body contexts)
9606 (org-in-item-p)))
9607 (goto-char pos))))
9609 (defconst org-unique-local-variables
9610 '(org-element--cache
9611 org-element--cache-objects
9612 org-element--cache-sync-keys
9613 org-element--cache-sync-requests
9614 org-element--cache-sync-timer)
9615 "List of local variables that cannot be transferred to another buffer.")
9617 (defun org-get-local-variables ()
9618 "Return a list of all local variables in an Org mode buffer."
9619 (delq nil
9620 (mapcar
9621 (lambda (x)
9622 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9623 (name (car binding)))
9624 (and (not (get name 'org-state))
9625 (not (memq name org-unique-local-variables))
9626 (string-match-p
9627 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9628 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9629 (symbol-name name))
9630 binding)))
9631 (with-temp-buffer
9632 (org-mode)
9633 (buffer-local-variables)))))
9635 (defun org-clone-local-variables (from-buffer &optional regexp)
9636 "Clone local variables from FROM-BUFFER.
9637 Optional argument REGEXP selects variables to clone."
9638 (dolist (pair (buffer-local-variables from-buffer))
9639 (let ((name (car pair)))
9640 (when (and (symbolp name)
9641 (not (memq name org-unique-local-variables))
9642 (or (null regexp) (string-match regexp (symbol-name name))))
9643 (set (make-local-variable name) (cdr pair))))))
9645 ;;;###autoload
9646 (defun org-run-like-in-org-mode (cmd)
9647 "Run a command, pretending that the current buffer is in Org mode.
9648 This will temporarily bind local variables that are typically bound in
9649 Org mode to the values they have in Org mode, and then interactively
9650 call CMD."
9651 (org-load-modules-maybe)
9652 (unless org-local-vars
9653 (setq org-local-vars (org-get-local-variables)))
9654 (let (binds)
9655 (dolist (var org-local-vars)
9656 (when (or (not (boundp (car var)))
9657 (eq (symbol-value (car var))
9658 (default-value (car var))))
9659 (push (list (car var) `(quote ,(cadr var))) binds)))
9660 (eval `(let ,binds
9661 (call-interactively (quote ,cmd))))))
9663 (defun org-get-category (&optional pos force-refresh)
9664 "Get the category applying to position POS."
9665 (save-match-data
9666 (when force-refresh (org-refresh-category-properties))
9667 (let ((pos (or pos (point))))
9668 (or (get-text-property pos 'org-category)
9669 (progn (org-refresh-category-properties)
9670 (get-text-property pos 'org-category))))))
9672 ;;; Refresh properties
9674 (defun org-refresh-properties (dprop tprop)
9675 "Refresh buffer text properties.
9676 DPROP is the drawer property and TPROP is either the
9677 corresponding text property to set, or an alist with each element
9678 being a text property (as a symbol) and a function to apply to
9679 the value of the drawer property."
9680 (let ((case-fold-search t)
9681 (inhibit-read-only t))
9682 (org-with-silent-modifications
9683 (org-with-wide-buffer
9684 (goto-char (point-min))
9685 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9686 (org-refresh-property tprop (match-string-no-properties 1)))))))
9688 (defun org-refresh-property (tprop p)
9689 "Refresh the buffer text property TPROP from the drawer property P.
9690 The refresh happens only for the current tree (not subtree)."
9691 (unless (org-before-first-heading-p)
9692 (save-excursion
9693 (org-back-to-heading t)
9694 (if (symbolp tprop)
9695 ;; TPROP is a text property symbol
9696 (put-text-property
9697 (point) (or (outline-next-heading) (point-max)) tprop p)
9698 ;; TPROP is an alist with (properties . function) elements
9699 (dolist (al tprop)
9700 (save-excursion
9701 (put-text-property
9702 (line-beginning-position) (or (outline-next-heading) (point-max))
9703 (car al)
9704 (funcall (cdr al) p))))))))
9706 (defun org-refresh-category-properties ()
9707 "Refresh category text properties in the buffer."
9708 (let ((case-fold-search t)
9709 (inhibit-read-only t)
9710 (default-category
9711 (cond ((null org-category)
9712 (if buffer-file-name
9713 (file-name-sans-extension
9714 (file-name-nondirectory buffer-file-name))
9715 "???"))
9716 ((symbolp org-category) (symbol-name org-category))
9717 (t org-category))))
9718 (org-with-silent-modifications
9719 (org-with-wide-buffer
9720 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9721 ;; This is the default category for the buffer. If none is
9722 ;; found, fall-back to `org-category' or buffer file name.
9723 (put-text-property
9724 (point-min) (point-max)
9725 'org-category
9726 (catch 'buffer-category
9727 (goto-char (point-max))
9728 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9729 (let ((element (org-element-at-point)))
9730 (when (eq (org-element-type element) 'keyword)
9731 (throw 'buffer-category
9732 (org-element-property :value element)))))
9733 default-category))
9734 ;; Set sub-tree specific categories.
9735 (goto-char (point-min))
9736 (let ((regexp (org-re-property "CATEGORY")))
9737 (while (re-search-forward regexp nil t)
9738 (let ((value (match-string-no-properties 3)))
9739 (when (org-at-property-p)
9740 (put-text-property
9741 (save-excursion (org-back-to-heading t) (point))
9742 (save-excursion (org-end-of-subtree t t) (point))
9743 'org-category
9744 value)))))))))
9746 (defun org-refresh-stats-properties ()
9747 "Refresh stats text properties in the buffer."
9748 (let (stats)
9749 (org-with-silent-modifications
9750 (org-with-wide-buffer
9751 (goto-char (point-min))
9752 (while (re-search-forward
9753 (concat org-outline-regexp-bol ".*"
9754 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9755 nil t)
9756 (setq stats (cond ((equal (match-string 3) "0") 0)
9757 ((match-string 2)
9758 (/ (* (string-to-number (match-string 2)) 100)
9759 (string-to-number (match-string 3))))
9760 (t (string-to-number (match-string 1)))))
9761 (org-back-to-heading t)
9762 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9763 'org-stats stats))))))
9765 (defun org-refresh-effort-properties ()
9766 "Refresh effort properties"
9767 (org-refresh-properties
9768 org-effort-property
9769 '((effort . identity)
9770 (effort-minutes . org-duration-string-to-minutes))))
9772 ;;;; Link Stuff
9774 ;;; Link abbreviations
9776 (defun org-link-expand-abbrev (link)
9777 "Apply replacements as defined in `org-link-abbrev-alist'."
9778 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9779 (let* ((key (match-string 1 link))
9780 (as (or (assoc key org-link-abbrev-alist-local)
9781 (assoc key org-link-abbrev-alist)))
9782 (tag (and (match-end 2) (match-string 3 link)))
9783 rpl)
9784 (if (not as)
9785 link
9786 (setq rpl (cdr as))
9787 (cond
9788 ((symbolp rpl) (funcall rpl tag))
9789 ((string-match "%(\\([^)]+\\))" rpl)
9790 (replace-match
9791 (save-match-data
9792 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9793 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9794 ((string-match "%h" rpl)
9795 (replace-match (url-hexify-string (or tag "")) t t rpl))
9796 (t (concat rpl tag)))))
9797 link))
9799 ;;; Storing and inserting links
9801 (defvar org-insert-link-history nil
9802 "Minibuffer history for links inserted with `org-insert-link'.")
9804 (defvar org-stored-links nil
9805 "Contains the links stored with `org-store-link'.")
9807 (defvar org-store-link-plist nil
9808 "Plist with info about the most recently link created with `org-store-link'.")
9810 (defun org-store-link-functions ()
9811 "Return a list of functions that are called to create and store a link.
9812 The functions defined in the :store property of
9813 `org-link-parameters'.
9815 Each function will be called in turn until one returns a non-nil
9816 value. Each function should check if it is responsible for
9817 creating this link (for example by looking at the major mode).
9818 If not, it must exit and return nil. If yes, it should return
9819 a non-nil value after calling `org-store-link-props' with a list
9820 of properties and values. Special properties are:
9822 :type The link prefix, like \"http\". This must be given.
9823 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9824 This is obligatory as well.
9825 :description Optional default description for the second pair
9826 of brackets in an Org mode link. The user can still change
9827 this when inserting this link into an Org mode buffer.
9829 In addition to these, any additional properties can be specified
9830 and then used in capture templates."
9831 (cl-loop for link in org-link-parameters
9832 with store-func
9833 do (setq store-func (org-link-get-parameter (car link) :store))
9834 if store-func
9835 collect store-func))
9837 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9838 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9840 ;;;###autoload
9841 (defun org-store-link (arg)
9842 "\\<org-mode-map>Store an org-link to the current location.
9843 This link is added to `org-stored-links' and can later be inserted
9844 into an Org buffer with \\[org-insert-link].
9846 For some link types, a prefix ARG is interpreted.
9847 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9848 For file links, ARG negates `org-context-in-file-links'.
9850 A double prefix ARG force skipping storing functions that are not
9851 part of Org's core.
9853 A triple prefix ARG force storing a link for each line in the
9854 active region."
9855 (interactive "P")
9856 (org-load-modules-maybe)
9857 (if (and (equal arg '(64)) (org-region-active-p))
9858 (save-excursion
9859 (let ((end (region-end)))
9860 (goto-char (region-beginning))
9861 (set-mark (point))
9862 (while (< (point-at-eol) end)
9863 (move-end-of-line 1) (activate-mark)
9864 (let (current-prefix-arg)
9865 (call-interactively 'org-store-link))
9866 (move-beginning-of-line 2)
9867 (set-mark (point)))))
9868 (setq org-store-link-plist nil)
9869 (let (link cpltxt desc description search
9870 txt custom-id agenda-link sfuns sfunsn)
9871 (cond
9873 ;; Store a link using an external link type
9874 ((and (not (equal arg '(16)))
9875 (setq sfuns
9876 (delq
9877 nil (mapcar (lambda (f)
9878 (let (fs) (if (funcall f) (push f fs))))
9879 (org-store-link-functions)))
9880 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9881 (or (and (cdr sfuns)
9882 (funcall (intern
9883 (completing-read
9884 "Which function for creating the link? "
9885 sfunsn nil t (car sfunsn)))))
9886 (funcall (caar sfuns)))
9887 (setq link (plist-get org-store-link-plist :link)
9888 desc (or (plist-get org-store-link-plist
9889 :description)
9890 link))))
9892 ;; Store a link from a source code buffer.
9893 ((org-src-edit-buffer-p)
9894 (let ((coderef-format (org-src-coderef-format)))
9895 (cond ((save-excursion
9896 (beginning-of-line)
9897 (looking-at (org-src-coderef-regexp coderef-format)))
9898 (setq link (format "(%s)" (match-string-no-properties 3))))
9899 ((called-interactively-p 'any)
9900 (let ((label (read-string "Code line label: ")))
9901 (end-of-line)
9902 (setq link (format coderef-format label))
9903 (let ((gc (- 79 (length link))))
9904 (if (< (current-column) gc)
9905 (org-move-to-column gc t)
9906 (insert " ")))
9907 (insert link)
9908 (setq link (concat "(" label ")"))
9909 (setq desc nil)))
9910 (t (setq link nil)))))
9912 ;; We are in the agenda, link to referenced location
9913 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9914 (let ((m (or (get-text-property (point) 'org-hd-marker)
9915 (get-text-property (point) 'org-marker))))
9916 (when m
9917 (org-with-point-at m
9918 (setq agenda-link
9919 (if (called-interactively-p 'any)
9920 (call-interactively 'org-store-link)
9921 (org-store-link nil)))))))
9923 ((eq major-mode 'calendar-mode)
9924 (let ((cd (calendar-cursor-to-date)))
9925 (setq link
9926 (format-time-string
9927 (car org-time-stamp-formats)
9928 (apply 'encode-time
9929 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9930 nil nil nil))))
9931 (org-store-link-props :type "calendar" :date cd)))
9933 ((eq major-mode 'help-mode)
9934 (setq link (concat "help:" (save-excursion
9935 (goto-char (point-min))
9936 (looking-at "^[^ ]+")
9937 (match-string 0))))
9938 (org-store-link-props :type "help"))
9940 ((eq major-mode 'w3-mode)
9941 (setq cpltxt (if (and (buffer-name)
9942 (not (string-match "Untitled" (buffer-name))))
9943 (buffer-name)
9944 (url-view-url t))
9945 link (url-view-url t))
9946 (org-store-link-props :type "w3" :url (url-view-url t)))
9948 ((eq major-mode 'image-mode)
9949 (setq cpltxt (concat "file:"
9950 (abbreviate-file-name buffer-file-name))
9951 link cpltxt)
9952 (org-store-link-props :type "image" :file buffer-file-name))
9954 ;; In dired, store a link to the file of the current line
9955 ((derived-mode-p 'dired-mode)
9956 (let ((file (dired-get-filename nil t)))
9957 (setq file (if file
9958 (abbreviate-file-name
9959 (expand-file-name (dired-get-filename nil t)))
9960 ;; otherwise, no file so use current directory.
9961 default-directory))
9962 (setq cpltxt (concat "file:" file)
9963 link cpltxt)))
9965 ((setq search (run-hook-with-args-until-success
9966 'org-create-file-search-functions))
9967 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9968 "::" search))
9969 (setq cpltxt (or description link)))
9971 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9972 (org-with-limited-levels
9973 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9974 (cond
9975 ;; Store a link using the target at point
9976 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9977 (setq cpltxt
9978 (concat "file:"
9979 (abbreviate-file-name
9980 (buffer-file-name (buffer-base-buffer)))
9981 "::" (match-string 1))
9982 link cpltxt))
9983 ((and (featurep 'org-id)
9984 (or (eq org-id-link-to-org-use-id t)
9985 (and (called-interactively-p 'any)
9986 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9987 (and (eq org-id-link-to-org-use-id
9988 'create-if-interactive-and-no-custom-id)
9989 (not custom-id))))
9990 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9991 ;; Store a link using the ID at point
9992 (setq link (condition-case nil
9993 (prog1 (org-id-store-link)
9994 (setq desc (or (plist-get org-store-link-plist
9995 :description)
9996 "")))
9997 (error
9998 ;; Probably before first headline, link only to file
9999 (concat "file:"
10000 (abbreviate-file-name
10001 (buffer-file-name (buffer-base-buffer))))))))
10003 ;; Just link to current headline
10004 (setq cpltxt (concat "file:"
10005 (abbreviate-file-name
10006 (buffer-file-name (buffer-base-buffer)))))
10007 ;; Add a context search string
10008 (when (org-xor org-context-in-file-links arg)
10009 (let* ((element (org-element-at-point))
10010 (name (org-element-property :name element)))
10011 (setq txt (cond
10012 ((org-at-heading-p) nil)
10013 (name)
10014 ((org-region-active-p)
10015 (buffer-substring (region-beginning) (region-end)))))
10016 (when (or (null txt) (string-match "\\S-" txt))
10017 (setq cpltxt
10018 (concat cpltxt "::"
10019 (condition-case nil
10020 (org-make-org-heading-search-string txt)
10021 (error "")))
10022 desc (or name
10023 (nth 4 (ignore-errors (org-heading-components)))
10024 "NONE")))))
10025 (when (string-match "::\\'" cpltxt)
10026 (setq cpltxt (substring cpltxt 0 -2)))
10027 (setq link cpltxt)))))
10029 ((buffer-file-name (buffer-base-buffer))
10030 ;; Just link to this file here.
10031 (setq cpltxt (concat "file:"
10032 (abbreviate-file-name
10033 (buffer-file-name (buffer-base-buffer)))))
10034 ;; Add a context string.
10035 (when (org-xor org-context-in-file-links arg)
10036 (setq txt (if (org-region-active-p)
10037 (buffer-substring (region-beginning) (region-end))
10038 (buffer-substring (point-at-bol) (point-at-eol))))
10039 ;; Only use search option if there is some text.
10040 (when (string-match "\\S-" txt)
10041 (setq cpltxt
10042 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10043 desc "NONE")))
10044 (setq link cpltxt))
10046 ((called-interactively-p 'interactive)
10047 (user-error "No method for storing a link from this buffer"))
10049 (t (setq link nil)))
10051 ;; We're done setting link and desc, clean up
10052 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10053 (setq link (or link cpltxt)
10054 desc (or desc cpltxt))
10055 (cond ((not desc))
10056 ((equal desc "NONE") (setq desc nil))
10057 (t (setq desc
10058 (replace-regexp-in-string
10059 org-bracket-link-analytic-regexp
10060 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10061 desc))))
10062 ;; Return the link
10063 (if (not (and (or (called-interactively-p 'any)
10064 executing-kbd-macro)
10065 link))
10066 (or agenda-link (and link (org-make-link-string link desc)))
10067 (push (list link desc) org-stored-links)
10068 (message "Stored: %s" (or desc link))
10069 (when custom-id
10070 (setq link (concat "file:" (abbreviate-file-name
10071 (buffer-file-name)) "::#" custom-id))
10072 (push (list link desc) org-stored-links))
10073 (car org-stored-links)))))
10075 (defun org-store-link-props (&rest plist)
10076 "Store link properties, extract names, addresses and dates."
10077 (let ((x (plist-get plist :from)))
10078 (when x
10079 (let ((adr (mail-extract-address-components x)))
10080 (setq plist (plist-put plist :fromname (car adr)))
10081 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10082 (let ((x (plist-get plist :to)))
10083 (when x
10084 (let ((adr (mail-extract-address-components x)))
10085 (setq plist (plist-put plist :toname (car adr)))
10086 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10087 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10088 (when x
10089 (setq plist (plist-put plist :date-timestamp
10090 (format-time-string
10091 (org-time-stamp-format t) x)))
10092 (setq plist (plist-put plist :date-timestamp-inactive
10093 (format-time-string
10094 (org-time-stamp-format t t) x)))))
10095 (let ((from (plist-get plist :from))
10096 (to (plist-get plist :to)))
10097 (when (and from to org-from-is-user-regexp)
10098 (setq plist
10099 (plist-put plist :fromto
10100 (if (string-match org-from-is-user-regexp from)
10101 (concat "to %t")
10102 (concat "from %f"))))))
10103 (setq org-store-link-plist plist))
10105 (defun org-add-link-props (&rest plist)
10106 "Add these properties to the link property list."
10107 (let (key value)
10108 (while plist
10109 (setq key (pop plist) value (pop plist))
10110 (setq org-store-link-plist
10111 (plist-put org-store-link-plist key value)))))
10113 (defun org-email-link-description (&optional fmt)
10114 "Return the description part of an email link.
10115 This takes information from `org-store-link-plist' and formats it
10116 according to FMT (default from `org-email-link-description-format')."
10117 (setq fmt (or fmt org-email-link-description-format))
10118 (let* ((p org-store-link-plist)
10119 (to (plist-get p :toaddress))
10120 (from (plist-get p :fromaddress))
10121 (table
10122 (list
10123 (cons "%c" (plist-get p :fromto))
10124 (cons "%F" (plist-get p :from))
10125 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10126 (cons "%T" (plist-get p :to))
10127 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10128 (cons "%s" (plist-get p :subject))
10129 (cons "%d" (plist-get p :date))
10130 (cons "%m" (plist-get p :message-id)))))
10131 (when (string-match "%c" fmt)
10132 ;; Check if the user wrote this message
10133 (if (and org-from-is-user-regexp from to
10134 (save-match-data (string-match org-from-is-user-regexp from)))
10135 (setq fmt (replace-match "to %t" t t fmt))
10136 (setq fmt (replace-match "from %f" t t fmt))))
10137 (org-replace-escapes fmt table)))
10139 (defun org-make-org-heading-search-string (&optional string)
10140 "Make search string for the current headline or STRING."
10141 (let ((s (or string
10142 (and (derived-mode-p 'org-mode)
10143 (save-excursion
10144 (org-back-to-heading t)
10145 (org-element-property :raw-value (org-element-at-point))))))
10146 (lines org-context-in-file-links))
10147 (or string (setq s (concat "*" s))) ; Add * for headlines
10148 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10149 (when (and string (integerp lines) (> lines 0))
10150 (let ((slines (org-split-string s "\n")))
10151 (when (< lines (length slines))
10152 (setq s (mapconcat
10153 'identity
10154 (reverse (nthcdr (- (length slines) lines)
10155 (reverse slines))) "\n")))))
10156 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10158 (defun org-make-link-string (link &optional description)
10159 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10160 (unless (org-string-nw-p link) (error "Empty link"))
10161 (let ((uri (cond ((string-match org-link-types-re link)
10162 (concat (match-string 1 link)
10163 (org-link-escape (substring link (match-end 1)))))
10164 ;; For readability, url-encode internal links only
10165 ;; when absolutely needed (i.e, when they contain
10166 ;; square brackets). File links however, are
10167 ;; encoded since, e.g., spaces are significant.
10168 ((or (file-name-absolute-p link)
10169 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10170 (org-link-escape link))
10171 (t link)))
10172 (description
10173 (and (org-string-nw-p description)
10174 ;; Remove brackets from description, as they are fatal.
10175 (replace-regexp-in-string
10176 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10177 (org-trim description)))))
10178 (format "[[%s]%s]"
10180 (if description (format "[%s]" description) ""))))
10182 (defconst org-link-escape-chars
10183 ;;%20 %5B %5D %25
10184 '(?\s ?\[ ?\] ?%)
10185 "List of characters that should be escaped in a link when stored to Org.
10186 This is the list that is used for internal purposes.")
10188 (defun org-link-escape (text &optional table merge)
10189 "Return percent escaped representation of TEXT.
10190 TEXT is a string with the text to escape.
10191 Optional argument TABLE is a list with characters that should be
10192 escaped. When nil, `org-link-escape-chars' is used.
10193 If optional argument MERGE is set, merge TABLE into
10194 `org-link-escape-chars'."
10195 (let ((characters-to-encode
10196 (cond ((null table) org-link-escape-chars)
10197 (merge (append org-link-escape-chars table))
10198 (t table))))
10199 (mapconcat
10200 (lambda (c)
10201 (if (or (memq c characters-to-encode)
10202 (and org-url-hexify-p (or (< c 32) (> c 126))))
10203 (mapconcat (lambda (e) (format "%%%.2X" e))
10204 (or (encode-coding-char c 'utf-8)
10205 (error "Unable to percent escape character: %c" c))
10207 (char-to-string c)))
10208 text "")))
10210 (defun org-link-unescape (str)
10211 "Unhex hexified Unicode parts in string STR.
10212 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10213 reciprocal of `org-link-escape', which see."
10214 (if (org-string-nw-p str)
10215 (replace-regexp-in-string
10216 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10217 str))
10219 (defun org-link-unescape-compound (hex)
10220 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10221 Note: this function also decodes single byte encodings like
10222 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10223 (save-match-data
10224 (let* ((bytes (cdr (split-string hex "%")))
10225 (ret "")
10226 (eat 0)
10227 (sum 0))
10228 (while bytes
10229 (let* ((val (string-to-number (pop bytes) 16))
10230 (shift-xor
10231 (if (= 0 eat)
10232 (cond
10233 ((>= val 252) (cons 6 252))
10234 ((>= val 248) (cons 5 248))
10235 ((>= val 240) (cons 4 240))
10236 ((>= val 224) (cons 3 224))
10237 ((>= val 192) (cons 2 192))
10238 (t (cons 0 0)))
10239 (cons 6 128))))
10240 (when (>= val 192) (setq eat (car shift-xor)))
10241 (setq val (logxor val (cdr shift-xor)))
10242 (setq sum (+ (lsh sum (car shift-xor)) val))
10243 (when (> eat 0) (setq eat (- eat 1)))
10244 (cond
10245 ((= 0 eat) ;multi byte
10246 (setq ret (concat ret (char-to-string sum)))
10247 (setq sum 0))
10248 ((not bytes) ; single byte(s)
10249 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10250 ret)))
10252 (defun org-link-unescape-single-byte-sequence (hex)
10253 "Unhexify hex-encoded single byte character sequences."
10254 (mapconcat (lambda (byte)
10255 (char-to-string (string-to-number byte 16)))
10256 (cdr (split-string hex "%")) ""))
10258 (defun org-xor (a b)
10259 "Exclusive or."
10260 (if a (not b) b))
10262 (defun org-fixup-message-id-for-http (s)
10263 "Replace special characters in a message id, so it can be used in an http query."
10264 (when (string-match "%" s)
10265 (setq s (mapconcat (lambda (c)
10266 (if (eq c ?%)
10267 "%25"
10268 (char-to-string c)))
10269 s "")))
10270 (while (string-match "<" s)
10271 (setq s (replace-match "%3C" t t s)))
10272 (while (string-match ">" s)
10273 (setq s (replace-match "%3E" t t s)))
10274 (while (string-match "@" s)
10275 (setq s (replace-match "%40" t t s)))
10278 (defun org-link-prettify (link)
10279 "Return a human-readable representation of LINK.
10280 The car of LINK must be a raw link.
10281 The cdr of LINK must be either a link description or nil."
10282 (let ((desc (or (cadr link) "<no description>")))
10283 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10284 "<" (car link) ">")))
10286 ;;;###autoload
10287 (defun org-insert-link-global ()
10288 "Insert a link like Org mode does.
10289 This command can be called in any mode to insert a link in Org syntax."
10290 (interactive)
10291 (org-load-modules-maybe)
10292 (org-run-like-in-org-mode 'org-insert-link))
10294 (defun org-insert-all-links (arg &optional pre post)
10295 "Insert all links in `org-stored-links'.
10296 When a universal prefix, do not delete the links from `org-stored-links'.
10297 When `ARG' is a number, insert the last N link(s).
10298 `PRE' and `POST' are optional arguments to define a string to
10299 prepend or to append."
10300 (interactive "P")
10301 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10302 (links (copy-sequence org-stored-links))
10303 (pr (or pre "- "))
10304 (po (or post "\n"))
10305 (cnt 1) l)
10306 (if (null org-stored-links)
10307 (message "No link to insert")
10308 (while (and (or (listp arg) (>= arg cnt))
10309 (setq l (if (listp arg)
10310 (pop links)
10311 (pop org-stored-links))))
10312 (setq cnt (1+ cnt))
10313 (insert pr)
10314 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10315 (insert po)))))
10317 (defun org-insert-last-stored-link (arg)
10318 "Insert the last link stored in `org-stored-links'."
10319 (interactive "p")
10320 (org-insert-all-links arg "" "\n"))
10322 (defun org-link-fontify-links-to-this-file ()
10323 "Fontify links to the current file in `org-stored-links'."
10324 (let ((f (buffer-file-name)) a b)
10325 (setq a (mapcar (lambda(l)
10326 (let ((ll (car l)))
10327 (when (and (string-match "^file:\\(.+\\)::" ll)
10328 (equal f (expand-file-name (match-string 1 ll))))
10329 ll)))
10330 org-stored-links))
10331 (when (featurep 'org-id)
10332 (setq b (mapcar (lambda(l)
10333 (let ((ll (car l)))
10334 (when (and (string-match "^id:\\(.+\\)$" ll)
10335 (equal f (expand-file-name
10336 (or (org-id-find-id-file
10337 (match-string 1 ll)) ""))))
10338 ll)))
10339 org-stored-links)))
10340 (mapcar (lambda(l)
10341 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10342 (delq nil (append a b)))))
10344 (defvar org--links-history nil)
10345 (defun org-insert-link (&optional complete-file link-location default-description)
10346 "Insert a link. At the prompt, enter the link.
10348 Completion can be used to insert any of the link protocol prefixes like
10349 http or ftp in use.
10351 The history can be used to select a link previously stored with
10352 `org-store-link'. When the empty string is entered (i.e. if you just
10353 press RET at the prompt), the link defaults to the most recently
10354 stored link. As SPC triggers completion in the minibuffer, you need to
10355 use M-SPC or C-q SPC to force the insertion of a space character.
10357 You will also be prompted for a description, and if one is given, it will
10358 be displayed in the buffer instead of the link.
10360 If there is already a link at point, this command will allow you to edit link
10361 and description parts.
10363 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10364 be selected using completion. The path to the file will be relative to the
10365 current directory if the file is in the current directory or a subdirectory.
10366 Otherwise, the link will be the absolute path as completed in the minibuffer
10367 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10368 option `org-link-file-path-type'.
10370 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10371 the current directory or below.
10373 With three \\[universal-argument] prefixes, negate the meaning of
10374 `org-keep-stored-link-after-insertion'.
10376 If `org-make-link-description-function' is non-nil, this function will be
10377 called with the link target, and the result will be the default
10378 link description.
10380 If the LINK-LOCATION parameter is non-nil, this value will be
10381 used as the link location instead of reading one interactively.
10383 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10384 be used as the default description."
10385 (interactive "P")
10386 (let* ((wcf (current-window-configuration))
10387 (origbuf (current-buffer))
10388 (region (when (org-region-active-p)
10389 (buffer-substring (region-beginning) (region-end))))
10390 (remove (and region (list (region-beginning) (region-end))))
10391 (desc region)
10392 (link link-location)
10393 (abbrevs org-link-abbrev-alist-local)
10394 entry all-prefixes auto-desc)
10395 (cond
10396 (link-location) ; specified by arg, just use it.
10397 ((org-in-regexp org-bracket-link-regexp 1)
10398 ;; We do have a link at point, and we are going to edit it.
10399 (setq remove (list (match-beginning 0) (match-end 0)))
10400 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10401 (setq link (read-string "Link: "
10402 (org-link-unescape
10403 (match-string-no-properties 1)))))
10404 ((or (org-in-regexp org-angle-link-re)
10405 (org-in-regexp org-plain-link-re))
10406 ;; Convert to bracket link
10407 (setq remove (list (match-beginning 0) (match-end 0))
10408 link (read-string "Link: "
10409 (org-unbracket-string "<" ">" (match-string 0)))))
10410 ((member complete-file '((4) (16)))
10411 ;; Completing read for file names.
10412 (setq link (org-file-complete-link complete-file)))
10414 ;; Read link, with completion for stored links.
10415 (org-link-fontify-links-to-this-file)
10416 (org-switch-to-buffer-other-window "*Org Links*")
10417 (with-current-buffer "*Org Links*"
10418 (erase-buffer)
10419 (insert "Insert a link.
10420 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10421 (when org-stored-links
10422 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10423 (insert (mapconcat 'org-link-prettify
10424 (reverse org-stored-links) "\n")))
10425 (goto-char (point-min)))
10426 (let ((cw (selected-window)))
10427 (select-window (get-buffer-window "*Org Links*" 'visible))
10428 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10429 (unless (pos-visible-in-window-p (point-max))
10430 (org-fit-window-to-buffer))
10431 (and (window-live-p cw) (select-window cw)))
10432 (setq all-prefixes (append (mapcar 'car abbrevs)
10433 (mapcar 'car org-link-abbrev-alist)
10434 (org-link-types)))
10435 (unwind-protect
10436 ;; Fake a link history, containing the stored links.
10437 (let ((org--links-history
10438 (append (mapcar #'car org-stored-links)
10439 org-insert-link-history)))
10440 (setq link
10441 (org-completing-read
10442 "Link: "
10443 (append
10444 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10445 (mapcar #'car org-stored-links))
10446 nil nil nil
10447 'org--links-history
10448 (caar org-stored-links)))
10449 (unless (org-string-nw-p link) (user-error "No link selected"))
10450 (dolist (l org-stored-links)
10451 (when (equal link (cadr l))
10452 (setq link (car l))
10453 (setq auto-desc t)))
10454 (when (or (member link all-prefixes)
10455 (and (equal ":" (substring link -1))
10456 (member (substring link 0 -1) all-prefixes)
10457 (setq link (substring link 0 -1))))
10458 (setq link (with-current-buffer origbuf
10459 (org-link-try-special-completion link)))))
10460 (set-window-configuration wcf)
10461 (kill-buffer "*Org Links*"))
10462 (setq entry (assoc link org-stored-links))
10463 (or entry (push link org-insert-link-history))
10464 (setq desc (or desc (nth 1 entry)))))
10466 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10467 (not org-keep-stored-link-after-insertion))
10468 (setq org-stored-links (delq (assoc link org-stored-links)
10469 org-stored-links)))
10471 (when (and (string-match org-plain-link-re link)
10472 (not (string-match org-ts-regexp link)))
10473 ;; URL-like link, normalize the use of angular brackets.
10474 (setq link (org-unbracket-string "<" ">" link)))
10476 ;; Check if we are linking to the current file with a search
10477 ;; option If yes, simplify the link by using only the search
10478 ;; option.
10479 (when (and buffer-file-name
10480 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10481 (let* ((path (match-string 1 link))
10482 (case-fold-search nil)
10483 (search (match-string 2 link)))
10484 (save-match-data
10485 (when (equal (file-truename buffer-file-name) (file-truename path))
10486 ;; We are linking to this same file, with a search option
10487 (setq link search)))))
10489 ;; Check if we can/should use a relative path. If yes, simplify the link
10490 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10491 (let* ((type (match-string 1 link))
10492 (path (match-string 2 link))
10493 (origpath path)
10494 (case-fold-search nil))
10495 (cond
10496 ((or (eq org-link-file-path-type 'absolute)
10497 (equal complete-file '(16)))
10498 (setq path (abbreviate-file-name (expand-file-name path))))
10499 ((eq org-link-file-path-type 'noabbrev)
10500 (setq path (expand-file-name path)))
10501 ((eq org-link-file-path-type 'relative)
10502 (setq path (file-relative-name path)))
10504 (save-match-data
10505 (if (string-match (concat "^" (regexp-quote
10506 (expand-file-name
10507 (file-name-as-directory
10508 default-directory))))
10509 (expand-file-name path))
10510 ;; We are linking a file with relative path name.
10511 (setq path (substring (expand-file-name path)
10512 (match-end 0)))
10513 (setq path (abbreviate-file-name (expand-file-name path)))))))
10514 (setq link (concat type path))
10515 (when (equal desc origpath)
10516 (setq desc path))))
10518 (if org-make-link-description-function
10519 (setq desc
10520 (or (condition-case nil
10521 (funcall org-make-link-description-function link desc)
10522 (error (progn (message "Can't get link description from `%s'"
10523 (symbol-name org-make-link-description-function))
10524 (sit-for 2) nil)))
10525 (read-string "Description: " default-description)))
10526 (if default-description (setq desc default-description)
10527 (setq desc (or (and auto-desc desc)
10528 (read-string "Description: " desc)))))
10530 (unless (string-match "\\S-" desc) (setq desc nil))
10531 (when remove (apply 'delete-region remove))
10532 (insert (org-make-link-string link desc))
10533 ;; Redisplay so as the new link has proper invisible characters.
10534 (sit-for 0)))
10536 (defun org-link-try-special-completion (type)
10537 "If there is completion support for link type TYPE, offer it."
10538 (let ((fun (org-link-get-parameter type :complete)))
10539 (if (functionp fun)
10540 (funcall fun)
10541 (read-string "Link (no completion support): " (concat type ":")))))
10543 (defun org-file-complete-link (&optional arg)
10544 "Create a file link using completion."
10545 (let ((file (read-file-name "File: "))
10546 (pwd (file-name-as-directory (expand-file-name ".")))
10547 (pwd1 (file-name-as-directory (abbreviate-file-name
10548 (expand-file-name ".")))))
10549 (cond ((equal arg '(16))
10550 (concat "file:"
10551 (abbreviate-file-name (expand-file-name file))))
10552 ((string-match
10553 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10554 (concat "file:" (match-string 1 file)))
10555 ((string-match
10556 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10557 (expand-file-name file))
10558 (concat "file:"
10559 (match-string 1 (expand-file-name file))))
10560 (t (concat "file:" file)))))
10562 (defun org-completing-read (&rest args)
10563 "Completing-read with SPACE being a normal character."
10564 (let ((enable-recursive-minibuffers t)
10565 (minibuffer-local-completion-map
10566 (copy-keymap minibuffer-local-completion-map)))
10567 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10568 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10569 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10570 'org-time-stamp-inactive)
10571 (apply #'completing-read args)))
10573 ;;; Opening/following a link
10575 (defvar org-link-search-failed nil)
10577 (defvar org-open-link-functions nil
10578 "Hook for functions finding a plain text link.
10579 These functions must take a single argument, the link content.
10580 They will be called for links that look like [[link text][description]]
10581 when LINK TEXT does not have a protocol like \"http:\" and does not look
10582 like a filename (e.g. \"./blue.png\").
10584 These functions will be called *before* Org attempts to resolve the
10585 link by doing text searches in the current buffer - so if you want a
10586 link \"[[target]]\" to still find \"<<target>>\", your function should
10587 handle this as a special case.
10589 When the function does handle the link, it must return a non-nil value.
10590 If it decides that it is not responsible for this link, it must return
10591 nil to indicate that that Org can continue with other options like
10592 exact and fuzzy text search.")
10594 (defun org-next-link (&optional search-backward)
10595 "Move forward to the next link.
10596 If the link is in hidden text, expose it."
10597 (interactive "P")
10598 (when (and org-link-search-failed (eq this-command last-command))
10599 (goto-char (point-min))
10600 (message "Link search wrapped back to beginning of buffer"))
10601 (setq org-link-search-failed nil)
10602 (let* ((pos (point))
10603 (ct (org-context))
10604 (a (assq :link ct))
10605 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10606 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10607 ((looking-at org-any-link-re)
10608 ;; Don't stay stuck at link without an org-link face
10609 (forward-char (if search-backward -1 1))))
10610 (if (funcall srch-fun org-any-link-re nil t)
10611 (progn
10612 (goto-char (match-beginning 0))
10613 (when (outline-invisible-p) (org-show-context)))
10614 (goto-char pos)
10615 (setq org-link-search-failed t)
10616 (message "No further link found"))))
10618 (defun org-previous-link ()
10619 "Move backward to the previous link.
10620 If the link is in hidden text, expose it."
10621 (interactive)
10622 (funcall 'org-next-link t))
10624 (defun org-translate-link (s)
10625 "Translate a link string if a translation function has been defined."
10626 (with-temp-buffer
10627 (insert (org-trim s))
10628 (org-trim (org-element-interpret-data (org-element-context)))))
10630 (defun org-translate-link-from-planner (type path)
10631 "Translate a link from Emacs Planner syntax so that Org can follow it.
10632 This is still an experimental function, your mileage may vary."
10633 (cond
10634 ((member type '("http" "https" "news" "ftp"))
10635 ;; standard Internet links are the same.
10636 nil)
10637 ((and (equal type "irc") (string-match "^//" path))
10638 ;; Planner has two / at the beginning of an irc link, we have 1.
10639 ;; We should have zero, actually....
10640 (setq path (substring path 1)))
10641 ((and (equal type "lisp") (string-match "^/" path))
10642 ;; Planner has a slash, we do not.
10643 (setq type "elisp" path (substring path 1)))
10644 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10645 ;; A typical message link. Planner has the id after the final slash,
10646 ;; we separate it with a hash mark
10647 (setq path (concat (match-string 1 path) "#"
10648 (org-unbracket-string "<" ">" (match-string 2 path))))))
10649 (cons type path))
10651 (defun org-find-file-at-mouse (ev)
10652 "Open file link or URL at mouse."
10653 (interactive "e")
10654 (mouse-set-point ev)
10655 (org-open-at-point 'in-emacs))
10657 (defun org-open-at-mouse (ev)
10658 "Open file link or URL at mouse.
10659 See the docstring of `org-open-file' for details."
10660 (interactive "e")
10661 (mouse-set-point ev)
10662 (when (eq major-mode 'org-agenda-mode)
10663 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10664 (org-open-at-point))
10666 (defvar org-window-config-before-follow-link nil
10667 "The window configuration before following a link.
10668 This is saved in case the need arises to restore it.")
10670 ;;;###autoload
10671 (defun org-open-at-point-global ()
10672 "Follow a link or time-stamp like Org mode does.
10673 This command can be called in any mode to follow an external link
10674 or a time-stamp that has Org mode syntax. Its behavior is
10675 undefined when called on internal links (e.g., fuzzy links).
10676 Raise an error when there is nothing to follow. "
10677 (interactive)
10678 (cond ((org-in-regexp org-any-link-re)
10679 (org-open-link-from-string (match-string-no-properties 0)))
10680 ((or (org-in-regexp org-ts-regexp-both nil t)
10681 (org-in-regexp org-tsr-regexp-both nil t))
10682 (org-follow-timestamp-link))
10683 (t (user-error "No link found"))))
10685 ;;;###autoload
10686 (defun org-open-link-from-string (s &optional arg reference-buffer)
10687 "Open a link in the string S, as if it was in Org mode."
10688 (interactive "sLink: \nP")
10689 (let ((reference-buffer (or reference-buffer (current-buffer))))
10690 (with-temp-buffer
10691 (let ((org-inhibit-startup (not reference-buffer)))
10692 (org-mode)
10693 (insert s)
10694 (goto-char (point-min))
10695 (when reference-buffer
10696 (setq org-link-abbrev-alist-local
10697 (with-current-buffer reference-buffer
10698 org-link-abbrev-alist-local)))
10699 (org-open-at-point arg reference-buffer)))))
10701 (defvar org-open-at-point-functions nil
10702 "Hook that is run when following a link at point.
10704 Functions in this hook must return t if they identify and follow
10705 a link at point. If they don't find anything interesting at point,
10706 they must return nil.")
10708 (defvar org-link-search-inhibit-query nil)
10709 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10710 (defun org--open-doi-link (path)
10711 "Open a \"doi\" type link.
10712 PATH is a the path to search for, as a string."
10713 (browse-url (url-encode-url (concat org-doi-server-url path))))
10715 (defun org--open-elisp-link (path)
10716 "Open a \"elisp\" type link.
10717 PATH is the sexp to evaluate, as a string."
10718 (let ((cmd path))
10719 (if (or (and (org-string-nw-p
10720 org-confirm-elisp-link-not-regexp)
10721 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10722 (not org-confirm-elisp-link-function)
10723 (funcall org-confirm-elisp-link-function
10724 (format "Execute \"%s\" as elisp? "
10725 (org-add-props cmd nil 'face 'org-warning))))
10726 (message "%s => %s" cmd
10727 (if (eq (string-to-char cmd) ?\()
10728 (eval (read cmd))
10729 (call-interactively (read cmd))))
10730 (user-error "Abort"))))
10732 (defun org--open-help-link (path)
10733 "Open a \"help\" type link.
10734 PATH is a symbol name, as a string."
10735 (pcase (intern path)
10736 ((and (pred fboundp) variable) (describe-function variable))
10737 ((and (pred boundp) function) (describe-variable function))
10738 (name (user-error "Unknown function or variable: %s" name))))
10740 (defun org--open-shell-link (path)
10741 "Open a \"shell\" type link.
10742 PATH is the command to execute, as a string."
10743 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10744 (cmd path))
10745 (if (or (and (org-string-nw-p
10746 org-confirm-shell-link-not-regexp)
10747 (string-match
10748 org-confirm-shell-link-not-regexp cmd))
10749 (not org-confirm-shell-link-function)
10750 (funcall org-confirm-shell-link-function
10751 (format "Execute \"%s\" in shell? "
10752 (org-add-props cmd nil
10753 'face 'org-warning))))
10754 (progn
10755 (message "Executing %s" cmd)
10756 (shell-command cmd buf)
10757 (when (featurep 'midnight)
10758 (setq clean-buffer-list-kill-buffer-names
10759 (cons (buffer-name buf)
10760 clean-buffer-list-kill-buffer-names))))
10761 (user-error "Abort"))))
10763 (defun org-open-at-point (&optional arg reference-buffer)
10764 "Open link, timestamp, footnote or tags at point.
10766 When point is on a link, follow it. Normally, files will be
10767 opened by an appropriate application. If the optional prefix
10768 argument ARG is non-nil, Emacs will visit the file. With
10769 a double prefix argument, try to open outside of Emacs, in the
10770 application the system uses for this file type.
10772 When point is on a timestamp, open the agenda at the day
10773 specified.
10775 When point is a footnote definition, move to the first reference
10776 found. If it is on a reference, move to the associated
10777 definition.
10779 When point is on a headline, display a list of every link in the
10780 entry, so it is possible to pick one, or all, of them. If point
10781 is on a tag, call `org-tags-view' instead.
10783 When optional argument REFERENCE-BUFFER is non-nil, it should
10784 specify a buffer from where the link search should happen. This
10785 is used internally by `org-open-link-from-string'.
10787 On top of syntactically correct links, this function will open
10788 the link at point in comments or comment blocks and the first
10789 link in a property drawer line."
10790 (interactive "P")
10791 ;; On a code block, open block's results.
10792 (unless (call-interactively 'org-babel-open-src-block-result)
10793 (org-load-modules-maybe)
10794 (setq org-window-config-before-follow-link (current-window-configuration))
10795 (org-remove-occur-highlights nil nil t)
10796 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10797 (let* ((context
10798 ;; Only consider supported types, even if they are not
10799 ;; the closest one.
10800 (org-element-lineage
10801 (org-element-context)
10802 '(clock comment comment-block footnote-definition
10803 footnote-reference headline inlinetask keyword link
10804 node-property timestamp)
10806 (type (org-element-type context))
10807 (value (org-element-property :value context)))
10808 (cond
10809 ((not context) (user-error "No link found"))
10810 ;; Exception: open timestamps and links in properties
10811 ;; drawers, keywords and comments.
10812 ((memq type '(comment comment-block keyword node-property))
10813 (call-interactively #'org-open-at-point-global))
10814 ;; On a headline or an inlinetask, but not on a timestamp,
10815 ;; a link, a footnote reference or on tags.
10816 ((and (memq type '(headline inlinetask))
10817 ;; Not on tags.
10818 (progn (save-excursion (beginning-of-line)
10819 (looking-at org-complex-heading-regexp))
10820 (or (not (match-beginning 5))
10821 (< (point) (match-beginning 5)))))
10822 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10823 (links (car data))
10824 (links-end (cdr data)))
10825 (if links
10826 (dolist (link (if (stringp links) (list links) links))
10827 (search-forward link nil links-end)
10828 (goto-char (match-beginning 0))
10829 (org-open-at-point))
10830 (require 'org-attach)
10831 (org-attach-reveal 'if-exists))))
10832 ;; On a clock line, make sure point is on the timestamp
10833 ;; before opening it.
10834 ((and (eq type 'clock)
10835 value
10836 (>= (point) (org-element-property :begin value))
10837 (<= (point) (org-element-property :end value)))
10838 (org-follow-timestamp-link))
10839 ;; Do nothing on white spaces after an object.
10840 ((>= (point)
10841 (save-excursion
10842 (goto-char (org-element-property :end context))
10843 (skip-chars-backward " \t")
10844 (point)))
10845 (user-error "No link found"))
10846 ((eq type 'timestamp) (org-follow-timestamp-link))
10847 ;; On tags within a headline or an inlinetask.
10848 ((and (memq type '(headline inlinetask))
10849 (progn (save-excursion (beginning-of-line)
10850 (looking-at org-complex-heading-regexp))
10851 (and (match-beginning 5)
10852 (>= (point) (match-beginning 5)))))
10853 (org-tags-view arg (substring (match-string 5) 0 -1)))
10854 ((eq type 'link)
10855 ;; When link is located within the description of another
10856 ;; link (e.g., an inline image), always open the parent
10857 ;; link.
10858 (let* ((link (let ((up (org-element-property :parent context)))
10859 (if (eq (org-element-type up) 'link) up context)))
10860 (type (org-element-property :type link))
10861 (path (org-link-unescape (org-element-property :path link))))
10862 ;; Switch back to REFERENCE-BUFFER needed when called in
10863 ;; a temporary buffer through `org-open-link-from-string'.
10864 (with-current-buffer (or reference-buffer (current-buffer))
10865 (cond
10866 ((equal type "file")
10867 (if (string-match "[*?{]" (file-name-nondirectory path))
10868 (dired path)
10869 ;; Look into `org-link-parameters' in order to find
10870 ;; a DEDICATED-FUNCTION to open file. The function
10871 ;; will be applied on raw link instead of parsed
10872 ;; link due to the limitation in `org-add-link-type'
10873 ;; ("open" function called with a single argument).
10874 ;; If no such function is found, fallback to
10875 ;; `org-open-file'.
10876 (let* ((option (org-element-property :search-option link))
10877 (app (org-element-property :application link))
10878 (dedicated-function
10879 (org-link-get-parameter
10880 (if app (concat type "+" app) type)
10881 :follow)))
10882 (if dedicated-function
10883 (funcall dedicated-function
10884 (concat path
10885 (and option (concat "::" option))))
10886 (apply #'org-open-file
10887 path
10888 (cond (arg)
10889 ((equal app "emacs") 'emacs)
10890 ((equal app "sys") 'system))
10891 (cond ((not option) nil)
10892 ((string-match-p "\\`[0-9]+\\'" option)
10893 (list (string-to-number option)))
10894 (t (list nil
10895 (org-link-unescape option)))))))))
10896 ((functionp (org-link-get-parameter type :follow))
10897 (funcall (org-link-get-parameter type :follow) path))
10898 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10899 (unless (run-hook-with-args-until-success
10900 'org-open-link-functions path)
10901 (if (not arg) (org-mark-ring-push)
10902 (switch-to-buffer-other-window
10903 (org-get-buffer-for-internal-link (current-buffer))))
10904 (let ((destination
10905 (org-with-wide-buffer
10906 (if (equal type "radio")
10907 (org-search-radio-target
10908 (org-element-property :path link))
10909 (org-link-search
10910 (if (member type '("custom-id" "coderef"))
10911 (org-element-property :raw-link link)
10912 path)
10913 ;; Prevent fuzzy links from matching
10914 ;; themselves.
10915 (and (equal type "fuzzy")
10916 (+ 2 (org-element-property :begin link)))))
10917 (point))))
10918 (unless (and (<= (point-min) destination)
10919 (>= (point-max) destination))
10920 (widen))
10921 (goto-char destination))))
10922 (t (browse-url-at-point))))))
10923 ;; On a footnote reference or at a footnote definition's label.
10924 ((or (eq type 'footnote-reference)
10925 (and (eq type 'footnote-definition)
10926 (save-excursion
10927 ;; Do not validate action when point is on the
10928 ;; spaces right after the footnote label, in
10929 ;; order to be on par with behaviour on links.
10930 (skip-chars-forward " \t")
10931 (let ((begin
10932 (org-element-property :contents-begin context)))
10933 (if begin (< (point) begin)
10934 (= (org-element-property :post-affiliated context)
10935 (line-beginning-position)))))))
10936 (org-footnote-action))
10937 (t (user-error "No link found")))))
10938 (run-hook-with-args 'org-follow-link-hook)))
10940 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10941 "Offer links in the current entry and return the selected link.
10942 If there is only one link, return it.
10943 If NTH is an integer, return the NTH link found.
10944 If ZERO is a string, check also this string for a link, and if
10945 there is one, return it."
10946 (with-current-buffer buffer
10947 (org-with-wide-buffer
10948 (goto-char marker)
10949 (let ((cnt ?0)
10950 have-zero end links link c)
10951 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10952 (push (match-string 0 zero) links)
10953 (setq cnt (1- cnt) have-zero t))
10954 (save-excursion
10955 (org-back-to-heading t)
10956 (setq end (save-excursion (outline-next-heading) (point)))
10957 (while (re-search-forward org-any-link-re end t)
10958 (push (match-string 0) links))
10959 (setq links (org-uniquify (reverse links))))
10960 (cond
10961 ((null links)
10962 (message "No links"))
10963 ((equal (length links) 1)
10964 (setq link (car links)))
10965 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10966 (setq link (nth (if have-zero nth (1- nth)) links)))
10967 (t ; we have to select a link
10968 (save-excursion
10969 (save-window-excursion
10970 (delete-other-windows)
10971 (with-output-to-temp-buffer "*Select Link*"
10972 (dolist (l links)
10973 (cond
10974 ((not (string-match org-bracket-link-regexp l))
10975 (princ (format "[%c] %s\n" (cl-incf cnt)
10976 (org-unbracket-string "<" ">" l))))
10977 ((match-end 3)
10978 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10979 (match-string 3 l) (match-string 1 l))))
10980 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10981 (match-string 1 l)))))))
10982 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10983 (message "Select link to open, RET to open all:")
10984 (setq c (read-char-exclusive))
10985 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10986 (when (equal c ?q) (user-error "Abort"))
10987 (if (equal c ?\C-m)
10988 (setq link links)
10989 (setq nth (- c ?0))
10990 (when have-zero (setq nth (1+ nth)))
10991 (unless (and (integerp nth) (>= (length links) nth))
10992 (user-error "Invalid link selection"))
10993 (setq link (nth (1- nth) links)))))
10994 (cons link end)))))
10996 ;; TODO: These functions are deprecated since `org-open-at-point'
10997 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10998 (defun org-open-file-with-system (path)
10999 "Open file at PATH using the system way of opening it."
11000 (org-open-file path 'system))
11001 (defun org-open-file-with-emacs (path)
11002 "Open file at PATH in Emacs."
11003 (org-open-file path 'emacs))
11006 ;;; File search
11008 (defvar org-create-file-search-functions nil
11009 "List of functions to construct the right search string for a file link.
11010 These functions are called in turn with point at the location to
11011 which the link should point.
11013 A function in the hook should first test if it would like to
11014 handle this file type, for example by checking the `major-mode'
11015 or the file extension. If it decides not to handle this file, it
11016 should just return nil to give other functions a chance. If it
11017 does handle the file, it must return the search string to be used
11018 when following the link. The search string will be part of the
11019 file link, given after a double colon, and `org-open-at-point'
11020 will automatically search for it. If special measures must be
11021 taken to make the search successful, another function should be
11022 added to the companion hook `org-execute-file-search-functions',
11023 which see.
11025 A function in this hook may also use `setq' to set the variable
11026 `description' to provide a suggestion for the descriptive text to
11027 be used for this link when it gets inserted into an Org buffer
11028 with \\[org-insert-link].")
11030 (defvar org-execute-file-search-functions nil
11031 "List of functions to execute a file search triggered by a link.
11033 Functions added to this hook must accept a single argument, the
11034 search string that was part of the file link, the part after the
11035 double colon. The function must first check if it would like to
11036 handle this search, for example by checking the `major-mode' or
11037 the file extension. If it decides not to handle this search, it
11038 should just return nil to give other functions a chance. If it
11039 does handle the search, it must return a non-nil value to keep
11040 other functions from trying.
11042 Each function can access the current prefix argument through the
11043 variable `current-prefix-arg'. Note that a single prefix is used
11044 to force opening a link in Emacs, so it may be good to only use a
11045 numeric or double prefix to guide the search function.
11047 In case this is needed, a function in this hook can also restore
11048 the window configuration before `org-open-at-point' was called using:
11050 \(set-window-configuration org-window-config-before-follow-link)")
11052 (defun org-search-radio-target (target)
11053 "Search a radio target matching TARGET in current buffer.
11054 White spaces are not significant."
11055 (let ((re (format "<<<%s>>>"
11056 (mapconcat #'regexp-quote
11057 (org-split-string target "[ \t\n]+")
11058 "[ \t]+\\(?:\n[ \t]*\\)?")))
11059 (origin (point)))
11060 (goto-char (point-min))
11061 (catch :radio-match
11062 (while (re-search-forward re nil t)
11063 (backward-char)
11064 (let ((object (org-element-context)))
11065 (when (eq (org-element-type object) 'radio-target)
11066 (goto-char (org-element-property :begin object))
11067 (org-show-context 'link-search)
11068 (throw :radio-match nil))))
11069 (goto-char origin)
11070 (user-error "No match for radio target: %s" target))))
11072 (defun org-link-search (s &optional avoid-pos stealth)
11073 "Search for a search string S.
11075 If S starts with \"#\", it triggers a custom ID search.
11077 If S is enclosed within parenthesis, it initiates a coderef
11078 search.
11080 If S is surrounded by forward slashes, it is interpreted as
11081 a regular expression. In Org mode files, this will create an
11082 `org-occur' sparse tree. In ordinary files, `occur' will be used
11083 to list matches. If the current buffer is in `dired-mode', grep
11084 will be used to search in all files.
11086 When AVOID-POS is given, ignore matches near that position.
11088 When optional argument STEALTH is non-nil, do not modify
11089 visibility around point, thus ignoring `org-show-context-detail'
11090 variable.
11092 Search is case-insensitive and ignores white spaces. Return type
11093 of matched result, with is either `dedicated' or `fuzzy'."
11094 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11095 (let* ((case-fold-search t)
11096 (origin (point))
11097 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11098 (words (org-split-string s "[ \t\n]+"))
11099 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11100 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11101 type)
11102 (cond
11103 ;; Check if there are any special search functions.
11104 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11105 ((eq (string-to-char s) ?#)
11106 ;; Look for a custom ID S if S starts with "#".
11107 (let* ((id (substring normalized 1))
11108 (match (org-find-property "CUSTOM_ID" id)))
11109 (if match (progn (goto-char match) (setf type 'dedicated))
11110 (error "No match for custom ID: %s" id))))
11111 ((string-match "\\`(\\(.*\\))\\'" normalized)
11112 ;; Look for coderef targets if S is enclosed within parenthesis.
11113 (let ((coderef (match-string-no-properties 1 normalized))
11114 (re (substring s-single-re 1 -1)))
11115 (goto-char (point-min))
11116 (catch :coderef-match
11117 (while (re-search-forward re nil t)
11118 (let ((element (org-element-at-point)))
11119 (when (and (memq (org-element-type element)
11120 '(example-block src-block))
11121 ;; Build proper regexp according to current
11122 ;; block's label format.
11123 (let ((label-fmt
11124 (regexp-quote
11125 (or (org-element-property :label-fmt element)
11126 org-coderef-label-format))))
11127 (save-excursion
11128 (beginning-of-line)
11129 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11130 (format label-fmt coderef))))))
11131 (setq type 'dedicated)
11132 (goto-char (match-beginning 1))
11133 (throw :coderef-match nil))))
11134 (goto-char origin)
11135 (error "No match for coderef: %s" coderef))))
11136 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11137 ;; Look for a regular expression.
11138 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11139 (match-string 1 s)))
11140 ;; Fuzzy links.
11142 (let ((starred (eq (string-to-char normalized) ?*)))
11143 (cond
11144 ;; Look for targets, only if not in a headline search.
11145 ((and (not starred)
11146 (let ((target (format "<<%s>>" s-multi-re)))
11147 (catch :target-match
11148 (goto-char (point-min))
11149 (while (re-search-forward target nil t)
11150 (backward-char)
11151 (let ((context (org-element-context)))
11152 (when (eq (org-element-type context) 'target)
11153 (setq type 'dedicated)
11154 (goto-char (org-element-property :begin context))
11155 (throw :target-match t))))
11156 nil))))
11157 ;; Look for elements named after S, only if not in a headline
11158 ;; search.
11159 ((and (not starred)
11160 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11161 (catch :name-match
11162 (goto-char (point-min))
11163 (while (re-search-forward name nil t)
11164 (let ((element (org-element-at-point)))
11165 (when (equal (org-split-string
11166 (org-element-property :name element)
11167 "[ \t]+")
11168 words)
11169 (setq type 'dedicated)
11170 (beginning-of-line)
11171 (throw :name-match t))))
11172 nil))))
11173 ;; Regular text search. Prefer headlines in Org mode
11174 ;; buffers.
11175 ((and (derived-mode-p 'org-mode)
11176 (let* ((wspace "[ \t]")
11177 (wspaceopt (concat wspace "*"))
11178 (cookie (concat "\\(?:"
11179 wspaceopt
11180 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11181 wspaceopt
11182 "\\)"))
11183 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11184 (re (concat
11185 org-outline-regexp-bol
11186 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11187 "\\(?:\\[#.\\][ \t]+\\)?"
11188 "\\(?:" org-comment-string "[ \t]+\\)?"
11189 sep "?"
11190 (let ((title (mapconcat #'regexp-quote
11191 words
11192 sep)))
11193 (if starred (substring title 1) title))
11194 sep "?"
11195 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11196 "[ \t]*$")))
11197 (goto-char (point-min))
11198 (re-search-forward re nil t)))
11199 (goto-char (match-beginning 0))
11200 (setq type 'dedicated))
11201 ;; Offer to create non-existent headline depending on
11202 ;; `org-link-search-must-match-exact-headline'.
11203 ((and (derived-mode-p 'org-mode)
11204 (not org-link-search-inhibit-query)
11205 (eq org-link-search-must-match-exact-headline 'query-to-create)
11206 (yes-or-no-p "No match - create this as a new heading? "))
11207 (goto-char (point-max))
11208 (unless (bolp) (newline))
11209 (org-insert-heading nil t t)
11210 (insert s "\n")
11211 (beginning-of-line 0))
11212 ;; Only headlines are looked after. No need to process
11213 ;; further: throw an error.
11214 ((and (derived-mode-p 'org-mode)
11215 (or starred org-link-search-must-match-exact-headline))
11216 (goto-char origin)
11217 (error "No match for fuzzy expression: %s" normalized))
11218 ;; Regular text search.
11219 ((catch :fuzzy-match
11220 (goto-char (point-min))
11221 (while (re-search-forward s-multi-re nil t)
11222 ;; Skip match if it contains AVOID-POS or it is included
11223 ;; in a link with a description but outside the
11224 ;; description.
11225 (unless (or (and avoid-pos
11226 (<= (match-beginning 0) avoid-pos)
11227 (> (match-end 0) avoid-pos))
11228 (and (save-match-data
11229 (org-in-regexp org-bracket-link-regexp))
11230 (match-beginning 3)
11231 (or (> (match-beginning 3) (point))
11232 (<= (match-end 3) (point)))
11233 (org-element-lineage
11234 (save-match-data (org-element-context))
11235 '(link) t)))
11236 (goto-char (match-beginning 0))
11237 (setq type 'fuzzy)
11238 (throw :fuzzy-match t)))
11239 nil))
11240 ;; All failed. Throw an error.
11241 (t (goto-char origin)
11242 (error "No match for fuzzy expression: %s" normalized))))))
11243 ;; Disclose surroundings of match, if appropriate.
11244 (when (and (derived-mode-p 'org-mode) (not stealth))
11245 (org-show-context 'link-search))
11246 type))
11248 (defun org-get-buffer-for-internal-link (buffer)
11249 "Return a buffer to be used for displaying the link target of internal links."
11250 (cond
11251 ((not org-display-internal-link-with-indirect-buffer)
11252 buffer)
11253 ((string-suffix-p "(Clone)" (buffer-name buffer))
11254 (message "Buffer is already a clone, not making another one")
11255 ;; we also do not modify visibility in this case
11256 buffer)
11257 (t ; make a new indirect buffer for displaying the link
11258 (let* ((bn (buffer-name buffer))
11259 (ibn (concat bn "(Clone)"))
11260 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11261 (with-current-buffer ib (org-overview))
11262 ib))))
11264 (defun org-do-occur (regexp &optional cleanup)
11265 "Call the Emacs command `occur'.
11266 If CLEANUP is non-nil, remove the printout of the regular expression
11267 in the *Occur* buffer. This is useful if the regex is long and not useful
11268 to read."
11269 (occur regexp)
11270 (when cleanup
11271 (let ((cwin (selected-window)) win beg end)
11272 (when (setq win (get-buffer-window "*Occur*"))
11273 (select-window win))
11274 (goto-char (point-min))
11275 (when (re-search-forward "match[a-z]+" nil t)
11276 (setq beg (match-end 0))
11277 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11278 (setq end (1- (match-beginning 0)))))
11279 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11280 (goto-char (point-min))
11281 (select-window cwin))))
11283 ;;; The mark ring for links jumps
11285 (defvar org-mark-ring nil
11286 "Mark ring for positions before jumps in Org mode.")
11287 (defvar org-mark-ring-last-goto nil
11288 "Last position in the mark ring used to go back.")
11289 ;; Fill and close the ring
11290 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11291 (dotimes (_ org-mark-ring-length)
11292 (push (make-marker) org-mark-ring))
11293 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11294 org-mark-ring)
11296 (defun org-mark-ring-push (&optional pos buffer)
11297 "Put the current position or POS into the mark ring and rotate it."
11298 (interactive)
11299 (setq pos (or pos (point)))
11300 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11301 (move-marker (car org-mark-ring)
11302 (or pos (point))
11303 (or buffer (current-buffer)))
11304 (message "%s"
11305 (substitute-command-keys
11306 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11308 (defun org-mark-ring-goto (&optional n)
11309 "Jump to the previous position in the mark ring.
11310 With prefix arg N, jump back that many stored positions. When
11311 called several times in succession, walk through the entire ring.
11312 Org mode commands jumping to a different position in the current file,
11313 or to another Org file, automatically push the old position onto the ring."
11314 (interactive "p")
11315 (let (p m)
11316 (if (eq last-command this-command)
11317 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11318 (setq p org-mark-ring))
11319 (setq org-mark-ring-last-goto p)
11320 (setq m (car p))
11321 (pop-to-buffer-same-window (marker-buffer m))
11322 (goto-char m)
11323 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11325 (defun org-add-angle-brackets (s)
11326 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11327 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11330 ;;; Following specific links
11332 (defvar org-agenda-buffer-tmp-name)
11333 (defvar org-agenda-start-on-weekday)
11334 (defun org-follow-timestamp-link ()
11335 "Open an agenda view for the time-stamp date/range at point."
11336 (cond
11337 ((org-at-date-range-p t)
11338 (let ((org-agenda-start-on-weekday)
11339 (t1 (match-string 1))
11340 (t2 (match-string 2)) tt1 tt2)
11341 (setq tt1 (time-to-days (org-time-string-to-time t1))
11342 tt2 (time-to-days (org-time-string-to-time t2)))
11343 (let ((org-agenda-buffer-tmp-name
11344 (format "*Org Agenda(a:%s)"
11345 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11346 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11347 ((org-at-timestamp-p t)
11348 (let ((org-agenda-buffer-tmp-name
11349 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11350 (org-agenda-list nil (time-to-days (org-time-string-to-time
11351 (substring (match-string 1) 0 10)))
11352 1)))
11353 (t (error "This should not happen"))))
11356 ;;; Following file links
11357 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11358 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11359 (declare-function mailcap-mime-info
11360 "mailcap" (string &optional request no-decode))
11361 (defvar org-wait nil)
11362 (defun org-open-file (path &optional in-emacs line search)
11363 "Open the file at PATH.
11364 First, this expands any special file name abbreviations. Then the
11365 configuration variable `org-file-apps' is checked if it contains an
11366 entry for this file type, and if yes, the corresponding command is launched.
11368 If no application is found, Emacs simply visits the file.
11370 With optional prefix argument IN-EMACS, Emacs will visit the file.
11371 With a double \\[universal-argument] \\[universal-argument] \
11372 prefix arg, Org tries to avoid opening in Emacs
11373 and to use an external application to visit the file.
11375 Optional LINE specifies a line to go to, optional SEARCH a string
11376 to search for. If LINE or SEARCH is given, the file will be
11377 opened in Emacs, unless an entry from org-file-apps that makes
11378 use of groups in a regexp matches.
11380 If you want to change the way frames are used when following a
11381 link, please customize `org-link-frame-setup'.
11383 If the file does not exist, an error is thrown."
11384 (let* ((file (if (equal path "")
11385 buffer-file-name
11386 (substitute-in-file-name (expand-file-name path))))
11387 (file-apps (append org-file-apps (org-default-apps)))
11388 (apps (cl-remove-if
11389 'org-file-apps-entry-match-against-dlink-p file-apps))
11390 (apps-dlink (cl-remove-if-not
11391 'org-file-apps-entry-match-against-dlink-p file-apps))
11392 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11393 (dirp (unless remp (file-directory-p file)))
11394 (file (if (and dirp org-open-directory-means-index-dot-org)
11395 (concat (file-name-as-directory file) "index.org")
11396 file))
11397 (a-m-a-p (assq 'auto-mode apps))
11398 (dfile (downcase file))
11399 ;; Reconstruct the original link from the PATH, LINE and
11400 ;; SEARCH args.
11401 (link (cond (line (concat file "::" (number-to-string line)))
11402 (search (concat file "::" search))
11403 (t file)))
11404 (dlink (downcase link))
11405 (old-buffer (current-buffer))
11406 (old-pos (point))
11407 (old-mode major-mode)
11408 (ext
11409 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11410 (match-string 1 dfile)))
11411 cmd link-match-data)
11412 (cond
11413 ((member in-emacs '((16) system))
11414 (setq cmd (cdr (assq 'system apps))))
11415 (in-emacs (setq cmd 'emacs))
11417 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11418 (and dirp (cdr (assq 'directory apps)))
11419 ;; First, try matching against apps-dlink if we
11420 ;; get a match here, store the match data for
11421 ;; later.
11422 (let ((match (assoc-default dlink apps-dlink
11423 'string-match)))
11424 (if match
11425 (progn (setq link-match-data (match-data))
11426 match)
11427 (progn (setq in-emacs (or in-emacs line search))
11428 nil))) ; if we have no match in apps-dlink,
11429 ; always open the file in emacs if line or search
11430 ; is given (for backwards compatibility)
11431 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11432 'string-match)
11433 (cdr (assoc ext apps))
11434 (cdr (assq t apps))))))
11435 (when (eq cmd 'system)
11436 (setq cmd (cdr (assq 'system apps))))
11437 (when (eq cmd 'default)
11438 (setq cmd (cdr (assoc t apps))))
11439 (when (eq cmd 'mailcap)
11440 (require 'mailcap)
11441 (mailcap-parse-mailcaps)
11442 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11443 (command (mailcap-mime-info mime-type)))
11444 (if (stringp command)
11445 (setq cmd command)
11446 (setq cmd 'emacs))))
11447 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11448 (not (file-exists-p file))
11449 (not org-open-non-existing-files))
11450 (user-error "No such file: %s" file))
11451 (cond
11452 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11453 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11454 (while (string-match "['\"]%s['\"]" cmd)
11455 (setq cmd (replace-match "%s" t t cmd)))
11456 (setq cmd (replace-regexp-in-string
11457 "%s"
11458 (shell-quote-argument (convert-standard-filename file))
11460 nil t))
11462 ;; Replace "%1", "%2" etc. in command with group matches from regex
11463 (save-match-data
11464 (let ((match-index 1)
11465 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11466 (set-match-data link-match-data)
11467 (while (<= match-index number-of-groups)
11468 (let ((regex (concat "%" (number-to-string match-index)))
11469 (replace-with (match-string match-index dlink)))
11470 (while (string-match regex cmd)
11471 (setq cmd (replace-match replace-with t t cmd))))
11472 (setq match-index (+ match-index 1)))))
11474 (save-window-excursion
11475 (message "Running %s...done" cmd)
11476 (start-process-shell-command cmd nil cmd)
11477 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11478 ((or (stringp cmd)
11479 (eq cmd 'emacs))
11480 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11481 (widen)
11482 (cond (line (org-goto-line line)
11483 (when (derived-mode-p 'org-mode) (org-reveal)))
11484 (search (org-link-search search))))
11485 ((functionp cmd)
11486 (save-match-data
11487 (set-match-data link-match-data)
11488 (condition-case nil
11489 (funcall cmd file link)
11490 ;; FIXME: Remove this check when most default installations
11491 ;; of Emacs have at least Org 9.0.
11492 ((debug wrong-number-of-arguments wrong-type-argument
11493 invalid-function)
11494 (user-error "Please see Org News for version 9.0 about \
11495 `org-file-apps'--Lisp error: %S" cmd)))))
11496 ((consp cmd)
11497 ;; FIXME: Remove this check when most default installations of
11498 ;; Emacs have at least Org 9.0.
11499 ;; Heads-up instead of silently fall back to
11500 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11501 ;; with sexp instead of a function for `cmd'.
11502 (user-error "Please see Org News for version 9.0 about \
11503 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11504 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11505 (and (derived-mode-p 'org-mode)
11506 (eq old-mode 'org-mode)
11507 (or (not (eq old-buffer (current-buffer)))
11508 (not (eq old-pos (point))))
11509 (org-mark-ring-push old-pos old-buffer))))
11511 (defun org-file-apps-entry-match-against-dlink-p (entry)
11512 "This function returns non-nil if `entry' uses a regular
11513 expression which should be matched against the whole link by
11514 org-open-file.
11516 It assumes that is the case when the entry uses a regular
11517 expression which has at least one grouping construct and the
11518 action is either a lisp form or a command string containing
11519 `%1', i.e. using at least one subexpression match as a
11520 parameter."
11521 (let ((selector (car entry))
11522 (action (cdr entry)))
11523 (if (stringp selector)
11524 (and (> (regexp-opt-depth selector) 0)
11525 (or (and (stringp action)
11526 (string-match "%[0-9]" action))
11527 (consp action)))
11528 nil)))
11530 (defun org-default-apps ()
11531 "Return the default applications for this operating system."
11532 (cond
11533 ((eq system-type 'darwin)
11534 org-file-apps-defaults-macosx)
11535 ((eq system-type 'windows-nt)
11536 org-file-apps-defaults-windowsnt)
11537 (t org-file-apps-defaults-gnu)))
11539 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11540 "Convert extensions to regular expressions in the cars of LIST.
11541 Also, weed out any non-string entries, because the return value is used
11542 only for regexp matching.
11543 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11544 point to the symbol `emacs', indicating that the file should
11545 be opened in Emacs."
11546 (append
11547 (delq nil
11548 (mapcar (lambda (x)
11549 (unless (not (stringp (car x)))
11550 (if (string-match "\\W" (car x))
11552 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11553 list))
11554 (when add-auto-mode
11555 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11557 (defvar ange-ftp-name-format)
11558 (defun org-file-remote-p (file)
11559 "Test whether FILE specifies a location on a remote system.
11560 Return non-nil if the location is indeed remote.
11562 For example, the filename \"/user@host:/foo\" specifies a location
11563 on the system \"/user@host:\"."
11564 (cond ((fboundp 'file-remote-p)
11565 (file-remote-p file))
11566 ((fboundp 'tramp-handle-file-remote-p)
11567 (tramp-handle-file-remote-p file))
11568 ((and (boundp 'ange-ftp-name-format)
11569 (string-match (car ange-ftp-name-format) file))
11570 t)))
11573 ;;;; Refiling
11575 (defun org-get-org-file ()
11576 "Read a filename, with default directory `org-directory'."
11577 (let ((default (or org-default-notes-file remember-data-file)))
11578 (read-file-name (format "File name [%s]: " default)
11579 (file-name-as-directory org-directory)
11580 default)))
11582 (defun org-notes-order-reversed-p ()
11583 "Check if the current file should receive notes in reversed order."
11584 (cond
11585 ((not org-reverse-note-order) nil)
11586 ((eq t org-reverse-note-order) t)
11587 ((not (listp org-reverse-note-order)) nil)
11588 (t (catch 'exit
11589 (dolist (entry org-reverse-note-order)
11590 (when (string-match (car entry) buffer-file-name)
11591 (throw 'exit (cdr entry))))))))
11593 (defvar org-refile-target-table nil
11594 "The list of refile targets, created by `org-refile'.")
11596 (defvar org-agenda-new-buffers nil
11597 "Buffers created to visit agenda files.")
11599 (defvar org-refile-cache nil
11600 "Cache for refile targets.")
11602 (defvar org-refile-markers nil
11603 "All the markers used for caching refile locations.")
11605 (defun org-refile-marker (pos)
11606 "Get a new refile marker, but only if caching is in use."
11607 (if (not org-refile-use-cache)
11609 (let ((m (make-marker)))
11610 (move-marker m pos)
11611 (push m org-refile-markers)
11612 m)))
11614 (defun org-refile-cache-clear ()
11615 "Clear the refile cache and disable all the markers."
11616 (dolist (m org-refile-markers) (move-marker m nil))
11617 (setq org-refile-markers nil)
11618 (setq org-refile-cache nil)
11619 (message "Refile cache has been cleared"))
11621 (defun org-refile-cache-check-set (set)
11622 "Check if all the markers in the cache still have live buffers."
11623 (let (marker)
11624 (catch 'exit
11625 (while (and set (setq marker (nth 3 (pop set))))
11626 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11627 (when (and marker (null (marker-buffer marker)))
11628 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11629 (sit-for 3)
11630 (throw 'exit nil)))
11631 t)))
11633 (defun org-refile-cache-put (set &rest identifiers)
11634 "Push the refile targets SET into the cache, under IDENTIFIERS."
11635 (let* ((key (sha1 (prin1-to-string identifiers)))
11636 (entry (assoc key org-refile-cache)))
11637 (if entry
11638 (setcdr entry set)
11639 (push (cons key set) org-refile-cache))))
11641 (defun org-refile-cache-get (&rest identifiers)
11642 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11643 (cond
11644 ((not org-refile-cache) nil)
11645 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11647 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11648 org-refile-cache))))
11649 (and set (org-refile-cache-check-set set) set)))))
11651 (defvar org-outline-path-cache nil
11652 "Alist between buffer positions and outline paths.
11653 It value is an alist (POSITION . PATH) where POSITION is the
11654 buffer position at the beginning of an entry and PATH is a list
11655 of strings describing the outline path for that entry, in reverse
11656 order.")
11658 (defun org-refile-get-targets (&optional default-buffer)
11659 "Produce a table with refile targets."
11660 (let ((case-fold-search nil)
11661 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11662 (entries (or org-refile-targets '((nil . (:level . 1)))))
11663 targets tgs files desc descre)
11664 (message "Getting targets...")
11665 (with-current-buffer (or default-buffer (current-buffer))
11666 (dolist (entry entries)
11667 (setq files (car entry) desc (cdr entry))
11668 (cond
11669 ((null files) (setq files (list (current-buffer))))
11670 ((eq files 'org-agenda-files)
11671 (setq files (org-agenda-files 'unrestricted)))
11672 ((and (symbolp files) (fboundp files))
11673 (setq files (funcall files)))
11674 ((and (symbolp files) (boundp files))
11675 (setq files (symbol-value files))))
11676 (when (stringp files) (setq files (list files)))
11677 (cond
11678 ((eq (car desc) :tag)
11679 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11680 ((eq (car desc) :todo)
11681 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11682 ((eq (car desc) :regexp)
11683 (setq descre (cdr desc)))
11684 ((eq (car desc) :level)
11685 (setq descre (concat "^\\*\\{" (number-to-string
11686 (if org-odd-levels-only
11687 (1- (* 2 (cdr desc)))
11688 (cdr desc)))
11689 "\\}[ \t]")))
11690 ((eq (car desc) :maxlevel)
11691 (setq descre (concat "^\\*\\{1," (number-to-string
11692 (if org-odd-levels-only
11693 (1- (* 2 (cdr desc)))
11694 (cdr desc)))
11695 "\\}[ \t]")))
11696 (t (error "Bad refiling target description %s" desc)))
11697 (dolist (f files)
11698 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11700 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11701 (progn
11702 (when (bufferp f)
11703 (setq f (buffer-file-name (buffer-base-buffer f))))
11704 (setq f (and f (expand-file-name f)))
11705 (when (eq org-refile-use-outline-path 'file)
11706 (push (list (file-name-nondirectory f) f nil nil) tgs))
11707 (org-with-wide-buffer
11708 (goto-char (point-min))
11709 (setq org-outline-path-cache nil)
11710 (while (re-search-forward descre nil t)
11711 (beginning-of-line)
11712 (looking-at org-complex-heading-regexp)
11713 (let ((begin (point))
11714 (heading (match-string-no-properties 4)))
11715 (unless (or (and
11716 org-refile-target-verify-function
11717 (not
11718 (funcall org-refile-target-verify-function)))
11719 (not heading))
11720 (let ((re (format org-complex-heading-regexp-format
11721 (regexp-quote heading)))
11722 (target
11723 (if (not org-refile-use-outline-path) heading
11724 (mapconcat
11725 #'org-protect-slash
11726 (append
11727 (pcase org-refile-use-outline-path
11728 (`file (list (file-name-nondirectory
11729 (buffer-file-name
11730 (buffer-base-buffer)))))
11731 (`full-file-path
11732 (list (buffer-file-name
11733 (buffer-base-buffer))))
11734 (_ nil))
11735 (org-get-outline-path t t))
11736 "/"))))
11737 (push (list target f re (org-refile-marker (point)))
11738 tgs)))
11739 (when (= (point) begin)
11740 ;; Verification function has not moved point.
11741 (end-of-line)))))))
11742 (when org-refile-use-cache
11743 (org-refile-cache-put tgs (buffer-file-name) descre))
11744 (setq targets (append tgs targets))))))
11745 (message "Getting targets...done")
11746 (nreverse targets)))
11748 (defun org-protect-slash (s)
11749 (replace-regexp-in-string "/" "\\/" s nil t))
11751 (defun org--get-outline-path-1 (&optional use-cache)
11752 "Return outline path to current headline.
11754 Outline path is a list of strings, in reverse order. When
11755 optional argument USE-CACHE is non-nil, make use of a cache. See
11756 `org-get-outline-path' for details.
11758 Assume buffer is widened and point is on a headline."
11759 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11760 (let ((p (point))
11761 (heading (progn
11762 (looking-at org-complex-heading-regexp)
11763 (if (not (match-end 4)) ""
11764 ;; Remove statistics cookies.
11765 (org-trim
11766 (org-link-display-format
11767 (replace-regexp-in-string
11768 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11769 (match-string-no-properties 4))))))))
11770 (if (org-up-heading-safe)
11771 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11772 (when use-cache
11773 (push (cons p path) org-outline-path-cache))
11774 path)
11775 ;; This is a new root node. Since we assume we are moving
11776 ;; forward, we can drop previous cache so as to limit number
11777 ;; of associations there.
11778 (let ((path (list heading)))
11779 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11780 path)))))
11782 (defun org-get-outline-path (&optional with-self use-cache)
11783 "Return the outline path to the current entry.
11785 An outline path is a list of ancestors for current headline, as
11786 a list of strings. Statistics cookies are removed and links are
11787 replaced with their description, if any, or their path otherwise.
11789 When optional argument WITH-SELF is non-nil, the path also
11790 includes the current headline.
11792 When optional argument USE-CACHE is non-nil, cache outline paths
11793 between calls to this function so as to avoid backtracking. This
11794 argument is useful when planning to find more than one outline
11795 path in the same document. In that case, there are two
11796 conditions to satisfy:
11797 - `org-outline-path-cache' is set to nil before starting the
11798 process;
11799 - outline paths are computed by increasing buffer positions."
11800 (org-with-wide-buffer
11801 (and (or (and with-self (org-back-to-heading t))
11802 (org-up-heading-safe))
11803 (reverse (org--get-outline-path-1 use-cache)))))
11805 (defun org-format-outline-path (path &optional width prefix separator)
11806 "Format the outline path PATH for display.
11807 WIDTH is the maximum number of characters that is available.
11808 PREFIX is a prefix to be included in the returned string,
11809 such as the file name.
11810 SEPARATOR is inserted between the different parts of the path,
11811 the default is \"/\"."
11812 (setq width (or width 79))
11813 (setq path (delq nil path))
11814 (unless (> width 0)
11815 (user-error "Argument `width' must be positive"))
11816 (setq separator (or separator "/"))
11817 (let* ((org-odd-levels-only nil)
11818 (fpath (concat
11819 prefix (and prefix path separator)
11820 (mapconcat
11821 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11822 (cl-loop for head in path
11823 for n from 0
11824 collect (org-add-props
11825 head nil 'face
11826 (nth (% n org-n-level-faces) org-level-faces)))
11827 separator))))
11828 (when (> (length fpath) width)
11829 (if (< width 7)
11830 ;; It's unlikely that `width' will be this small, but don't
11831 ;; waste characters by adding ".." if it is.
11832 (setq fpath (substring fpath 0 width))
11833 (setf (substring fpath (- width 2)) "..")))
11834 fpath))
11836 (defun org-display-outline-path (&optional file current separator just-return-string)
11837 "Display the current outline path in the echo area.
11839 If FILE is non-nil, prepend the output with the file name.
11840 If CURRENT is non-nil, append the current heading to the output.
11841 SEPARATOR is passed through to `org-format-outline-path'. It separates
11842 the different parts of the path and defaults to \"/\".
11843 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11844 (interactive "P")
11845 (let* (case-fold-search
11846 (bfn (buffer-file-name (buffer-base-buffer)))
11847 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11848 res)
11849 (when current (setq path (append path
11850 (save-excursion
11851 (org-back-to-heading t)
11852 (when (looking-at org-complex-heading-regexp)
11853 (list (match-string 4)))))))
11854 (setq res
11855 (org-format-outline-path
11856 path
11857 (1- (frame-width))
11858 (and file bfn (concat (file-name-nondirectory bfn) separator))
11859 separator))
11860 (if just-return-string
11861 (org-no-properties res)
11862 (org-unlogged-message "%s" res))))
11864 (defvar org-refile-history nil
11865 "History for refiling operations.")
11867 (defvar org-after-refile-insert-hook nil
11868 "Hook run after `org-refile' has inserted its stuff at the new location.
11869 Note that this is still *before* the stuff will be removed from
11870 the *old* location.")
11872 (defvar org-capture-last-stored-marker)
11873 (defvar org-refile-keep nil
11874 "Non-nil means `org-refile' will copy instead of refile.")
11876 (defun org-copy ()
11877 "Like `org-refile', but copy."
11878 (interactive)
11879 (let ((org-refile-keep t))
11880 (funcall 'org-refile nil nil nil "Copy")))
11882 (defun org-refile (&optional arg default-buffer rfloc msg)
11883 "Move the entry or entries at point to another heading.
11884 The list of target headings is compiled using the information in
11885 `org-refile-targets', which see.
11887 At the target location, the entry is filed as a subitem of the
11888 target heading. Depending on `org-reverse-note-order', the new
11889 subitem will either be the first or the last subitem.
11891 If there is an active region, all entries in that region will be
11892 refiled. However, the region must fulfill the requirement that
11893 the first heading sets the top-level of the moved text.
11895 With prefix arg ARG, the command will only visit the target
11896 location and not actually move anything.
11898 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11899 refiling operation has put the subtree.
11901 With a numeric prefix argument of `2', refile to the running clock.
11903 With a numeric prefix argument of `3', emulate `org-refile-keep'
11904 being set to t and copy to the target location, don't move it.
11905 Beware that keeping refiled entries may result in duplicated ID
11906 properties.
11908 RFLOC can be a refile location obtained in a different way.
11910 MSG is a string to replace \"Refile\" in the default prompt with
11911 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11913 See also `org-refile-use-outline-path'.
11915 If you are using target caching (see `org-refile-use-cache'), you
11916 have to clear the target cache in order to find new targets.
11917 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11918 prefix argument (`C-u C-u C-u C-c C-w')."
11919 (interactive "P")
11920 (if (member arg '(0 (64)))
11921 (org-refile-cache-clear)
11922 (let* ((actionmsg (cond (msg msg)
11923 ((equal arg 3) "Refile (and keep)")
11924 (t "Refile")))
11925 (regionp (org-region-active-p))
11926 (region-start (and regionp (region-beginning)))
11927 (region-end (and regionp (region-end)))
11928 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11929 pos it nbuf file level reversed)
11930 (setq last-command nil)
11931 (when regionp
11932 (goto-char region-start)
11933 (or (bolp) (goto-char (point-at-bol)))
11934 (setq region-start (point))
11935 (unless (or (org-kill-is-subtree-p
11936 (buffer-substring region-start region-end))
11937 (prog1 org-refile-active-region-within-subtree
11938 (let ((s (point-at-eol)))
11939 (org-toggle-heading)
11940 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11941 (user-error "The region is not a (sequence of) subtree(s)")))
11942 (if (equal arg '(16))
11943 (org-refile-goto-last-stored)
11944 (when (or
11945 (and (equal arg 2)
11946 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11947 (prog1
11948 (setq it (list (or org-clock-heading "running clock")
11949 (buffer-file-name
11950 (marker-buffer org-clock-hd-marker))
11952 (marker-position org-clock-hd-marker)))
11953 (setq arg nil)))
11954 (setq it
11955 (or rfloc
11956 (let (heading-text)
11957 (save-excursion
11958 (unless (and arg (listp arg))
11959 (org-back-to-heading t)
11960 (setq heading-text
11961 (replace-regexp-in-string
11962 org-bracket-link-regexp
11963 "\\3"
11964 (or (nth 4 (org-heading-components))
11965 ""))))
11966 (org-refile-get-location
11967 (cond ((and arg (listp arg)) "Goto")
11968 (regionp (concat actionmsg " region to"))
11969 (t (concat actionmsg " subtree \""
11970 heading-text "\" to")))
11971 default-buffer
11972 (and (not (equal '(4) arg))
11973 org-refile-allow-creating-parent-nodes)))))))
11974 (setq file (nth 1 it)
11975 pos (nth 3 it))
11976 (when (and (not arg)
11978 (equal (buffer-file-name) file)
11979 (if regionp
11980 (and (>= pos region-start)
11981 (<= pos region-end))
11982 (and (>= pos (point))
11983 (< pos (save-excursion
11984 (org-end-of-subtree t t))))))
11985 (error "Cannot refile to position inside the tree or region"))
11986 (setq nbuf (or (find-buffer-visiting file)
11987 (find-file-noselect file)))
11988 (if (and arg (not (equal arg 3)))
11989 (progn
11990 (pop-to-buffer-same-window nbuf)
11991 (goto-char pos)
11992 (org-show-context 'org-goto))
11993 (if regionp
11994 (progn
11995 (org-kill-new (buffer-substring region-start region-end))
11996 (org-save-markers-in-region region-start region-end))
11997 (org-copy-subtree 1 nil t))
11998 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11999 (find-file-noselect file)))
12000 (setq reversed (org-notes-order-reversed-p))
12001 (org-with-wide-buffer
12002 (if pos
12003 (progn
12004 (goto-char pos)
12005 (looking-at org-outline-regexp)
12006 (setq level (org-get-valid-level (funcall outline-level) 1))
12007 (goto-char
12008 (if reversed
12009 (or (outline-next-heading) (point-max))
12010 (or (save-excursion (org-get-next-sibling))
12011 (org-end-of-subtree t t)
12012 (point-max)))))
12013 (setq level 1)
12014 (if (not reversed)
12015 (goto-char (point-max))
12016 (goto-char (point-min))
12017 (or (outline-next-heading) (goto-char (point-max)))))
12018 (unless (bolp) (newline))
12019 (org-paste-subtree level nil nil t)
12020 (when org-log-refile
12021 (org-add-log-setup 'refile nil nil org-log-refile)
12022 (unless (eq org-log-refile 'note)
12023 (save-excursion (org-add-log-note))))
12024 (and org-auto-align-tags
12025 (let ((org-loop-over-headlines-in-active-region nil))
12026 (org-set-tags nil t)))
12027 (let ((bookmark-name (plist-get org-bookmark-names-plist
12028 :last-refile)))
12029 (when bookmark-name
12030 (with-demoted-errors
12031 (bookmark-set bookmark-name))))
12032 ;; If we are refiling for capture, make sure that the
12033 ;; last-capture pointers point here
12034 (when (bound-and-true-p org-capture-is-refiling)
12035 (let ((bookmark-name (plist-get org-bookmark-names-plist
12036 :last-capture-marker)))
12037 (when bookmark-name
12038 (with-demoted-errors
12039 (bookmark-set bookmark-name))))
12040 (move-marker org-capture-last-stored-marker (point)))
12041 (when (fboundp 'deactivate-mark) (deactivate-mark))
12042 (run-hooks 'org-after-refile-insert-hook)))
12043 (unless org-refile-keep
12044 (if regionp
12045 (delete-region (point) (+ (point) (- region-end region-start)))
12046 (delete-region
12047 (and (org-back-to-heading t) (point))
12048 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12049 (when (featurep 'org-inlinetask)
12050 (org-inlinetask-remove-END-maybe))
12051 (setq org-markers-to-move nil)
12052 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12054 (defun org-refile-goto-last-stored ()
12055 "Go to the location where the last refile was stored."
12056 (interactive)
12057 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12058 (message "This is the location of the last refile"))
12060 (defun org-refile--get-location (refloc tbl)
12061 "When user refile to REFLOC, find the associated target in TBL.
12062 Also check `org-refile-target-table'."
12063 (car (delq
12065 (mapcar
12066 (lambda (r) (or (assoc r tbl)
12067 (assoc r org-refile-target-table)))
12068 (list (replace-regexp-in-string "/$" "" refloc)
12069 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12071 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12072 "Prompt the user for a refile location, using PROMPT.
12073 PROMPT should not be suffixed with a colon and a space, because
12074 this function appends the default value from
12075 `org-refile-history' automatically, if that is not empty."
12076 (let ((org-refile-targets org-refile-targets)
12077 (org-refile-use-outline-path org-refile-use-outline-path))
12078 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12079 (unless org-refile-target-table
12080 (user-error "No refile targets"))
12081 (let* ((cbuf (current-buffer))
12082 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12083 (cfunc (if (and org-refile-use-outline-path
12084 org-outline-path-complete-in-steps)
12085 #'org-olpath-completing-read
12086 #'completing-read))
12087 (extra (if org-refile-use-outline-path "/" ""))
12088 (cbnex (concat (buffer-name) extra))
12089 (filename (and cfn (expand-file-name cfn)))
12090 (tbl (mapcar
12091 (lambda (x)
12092 (if (and (not (member org-refile-use-outline-path
12093 '(file full-file-path)))
12094 (not (equal filename (nth 1 x))))
12095 (cons (concat (car x) extra " ("
12096 (file-name-nondirectory (nth 1 x)) ")")
12097 (cdr x))
12098 (cons (concat (car x) extra) (cdr x))))
12099 org-refile-target-table))
12100 (completion-ignore-case t)
12101 cdef
12102 (prompt (concat prompt
12103 (or (and (car org-refile-history)
12104 (concat " (default " (car org-refile-history) ")"))
12105 (and (assoc cbnex tbl) (setq cdef cbnex)
12106 (concat " (default " cbnex ")"))) ": "))
12107 pa answ parent-target child parent old-hist)
12108 (setq old-hist org-refile-history)
12109 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12110 nil 'org-refile-history (or cdef (car org-refile-history))))
12111 (if (setq pa (org-refile--get-location answ tbl))
12112 (progn
12113 (org-refile-check-position pa)
12114 (when (or (not org-refile-history)
12115 (not (eq old-hist org-refile-history))
12116 (not (equal (car pa) (car org-refile-history))))
12117 (setq org-refile-history
12118 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12119 org-refile-history
12120 (cdr org-refile-history))))
12121 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12122 (pop org-refile-history)))
12124 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12125 (progn
12126 (setq parent (match-string 1 answ)
12127 child (match-string 2 answ))
12128 (setq parent-target (org-refile--get-location parent tbl))
12129 (when (and parent-target
12130 (or (eq new-nodes t)
12131 (and (eq new-nodes 'confirm)
12132 (y-or-n-p (format "Create new node \"%s\"? "
12133 child)))))
12134 (org-refile-new-child parent-target child)))
12135 (user-error "Invalid target location")))))
12137 (declare-function org-string-nw-p "org-macs" (s))
12138 (defun org-refile-check-position (refile-pointer)
12139 "Check if the refile pointer matches the headline to which it points."
12140 (let* ((file (nth 1 refile-pointer))
12141 (re (nth 2 refile-pointer))
12142 (pos (nth 3 refile-pointer))
12143 buffer)
12144 (if (and (not (markerp pos)) (not file))
12145 (user-error "Please indicate a target file in the refile path")
12146 (when (org-string-nw-p re)
12147 (setq buffer (if (markerp pos)
12148 (marker-buffer pos)
12149 (or (find-buffer-visiting file)
12150 (find-file-noselect file))))
12151 (with-current-buffer buffer
12152 (org-with-wide-buffer
12153 (goto-char pos)
12154 (beginning-of-line 1)
12155 (unless (looking-at-p re)
12156 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12158 (defun org-refile-new-child (parent-target child)
12159 "Use refile target PARENT-TARGET to add new CHILD below it."
12160 (unless parent-target
12161 (error "Cannot find parent for new node"))
12162 (let ((file (nth 1 parent-target))
12163 (pos (nth 3 parent-target))
12164 level)
12165 (with-current-buffer (or (find-buffer-visiting file)
12166 (find-file-noselect file))
12167 (org-with-wide-buffer
12168 (if pos
12169 (goto-char pos)
12170 (goto-char (point-max))
12171 (unless (bolp) (newline)))
12172 (when (looking-at org-outline-regexp)
12173 (setq level (funcall outline-level))
12174 (org-end-of-subtree t t))
12175 (org-back-over-empty-lines)
12176 (insert "\n" (make-string
12177 (if pos (org-get-valid-level level 1) 1) ?*)
12178 " " child "\n")
12179 (beginning-of-line 0)
12180 (list (concat (car parent-target) "/" child) file "" (point))))))
12182 (defun org-olpath-completing-read (prompt collection &rest args)
12183 "Read an outline path like a file name."
12184 (let ((thetable collection))
12185 (apply #'completing-read
12186 prompt
12187 (lambda (string predicate &optional flag)
12188 (cond
12189 ((eq flag nil) (try-completion string thetable))
12190 ((eq flag t)
12191 (let ((l (length string)))
12192 (mapcar (lambda (x)
12193 (let ((r (substring x l))
12194 (f (if (string-match " ([^)]*)$" x)
12195 (match-string 0 x)
12196 "")))
12197 (if (string-match "/" r)
12198 (concat string (substring r 0 (match-end 0)) f)
12199 x)))
12200 (all-completions string thetable predicate))))
12201 ;; Exact match?
12202 ((eq flag 'lambda) (assoc string thetable))))
12203 args)))
12205 ;;;; Dynamic blocks
12207 (defun org-find-dblock (name)
12208 "Find the first dynamic block with name NAME in the buffer.
12209 If not found, stay at current position and return nil."
12210 (let ((case-fold-search t) pos)
12211 (save-excursion
12212 (goto-char (point-min))
12213 (setq pos (and (re-search-forward
12214 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12215 (match-beginning 0))))
12216 (when pos (goto-char pos))
12217 pos))
12219 (defun org-create-dblock (plist)
12220 "Create a dynamic block section, with parameters taken from PLIST.
12221 PLIST must contain a :name entry which is used as the name of the block."
12222 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12223 (end-of-line 1)
12224 (newline))
12225 (let ((col (current-column))
12226 (name (plist-get plist :name)))
12227 (insert "#+BEGIN: " name)
12228 (while plist
12229 (if (eq (car plist) :name)
12230 (setq plist (cddr plist))
12231 (insert " " (prin1-to-string (pop plist)))))
12232 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12233 (beginning-of-line -2)))
12235 (defun org-prepare-dblock ()
12236 "Prepare dynamic block for refresh.
12237 This empties the block, puts the cursor at the insert position and returns
12238 the property list including an extra property :name with the block name."
12239 (unless (looking-at org-dblock-start-re)
12240 (user-error "Not at a dynamic block"))
12241 (let* ((begdel (1+ (match-end 0)))
12242 (name (org-no-properties (match-string 1)))
12243 (params (append (list :name name)
12244 (read (concat "(" (match-string 3) ")")))))
12245 (save-excursion
12246 (beginning-of-line 1)
12247 (skip-chars-forward " \t")
12248 (setq params (plist-put params :indentation-column (current-column))))
12249 (unless (re-search-forward org-dblock-end-re nil t)
12250 (error "Dynamic block not terminated"))
12251 (setq params
12252 (append params
12253 (list :content (buffer-substring
12254 begdel (match-beginning 0)))))
12255 (delete-region begdel (match-beginning 0))
12256 (goto-char begdel)
12257 (open-line 1)
12258 params))
12260 (defun org-map-dblocks (&optional command)
12261 "Apply COMMAND to all dynamic blocks in the current buffer.
12262 If COMMAND is not given, use `org-update-dblock'."
12263 (let ((cmd (or command 'org-update-dblock)))
12264 (save-excursion
12265 (goto-char (point-min))
12266 (while (re-search-forward org-dblock-start-re nil t)
12267 (goto-char (match-beginning 0))
12268 (save-excursion
12269 (condition-case nil
12270 (funcall cmd)
12271 (error (message "Error during update of dynamic block"))))
12272 (unless (re-search-forward org-dblock-end-re nil t)
12273 (error "Dynamic block not terminated"))))))
12275 (defun org-dblock-update (&optional arg)
12276 "User command for updating dynamic blocks.
12277 Update the dynamic block at point. With prefix ARG, update all dynamic
12278 blocks in the buffer."
12279 (interactive "P")
12280 (if arg
12281 (org-update-all-dblocks)
12282 (or (looking-at org-dblock-start-re)
12283 (org-beginning-of-dblock))
12284 (org-update-dblock)))
12286 (defun org-update-dblock ()
12287 "Update the dynamic block at point.
12288 This means to empty the block, parse for parameters and then call
12289 the correct writing function."
12290 (interactive)
12291 (save-excursion
12292 (let* ((win (selected-window))
12293 (pos (point))
12294 (line (org-current-line))
12295 (params (org-prepare-dblock))
12296 (name (plist-get params :name))
12297 (indent (plist-get params :indentation-column))
12298 (cmd (intern (concat "org-dblock-write:" name))))
12299 (message "Updating dynamic block `%s' at line %d..." name line)
12300 (funcall cmd params)
12301 (message "Updating dynamic block `%s' at line %d...done" name line)
12302 (goto-char pos)
12303 (when (and indent (> indent 0))
12304 (setq indent (make-string indent ?\ ))
12305 (save-excursion
12306 (select-window win)
12307 (org-beginning-of-dblock)
12308 (forward-line 1)
12309 (while (not (looking-at org-dblock-end-re))
12310 (insert indent)
12311 (beginning-of-line 2))
12312 (when (looking-at org-dblock-end-re)
12313 (and (looking-at "[ \t]+")
12314 (replace-match ""))
12315 (insert indent)))))))
12317 (defun org-beginning-of-dblock ()
12318 "Find the beginning of the dynamic block at point.
12319 Error if there is no such block at point."
12320 (let ((pos (point))
12321 beg)
12322 (end-of-line 1)
12323 (if (and (re-search-backward org-dblock-start-re nil t)
12324 (setq beg (match-beginning 0))
12325 (re-search-forward org-dblock-end-re nil t)
12326 (> (match-end 0) pos))
12327 (goto-char beg)
12328 (goto-char pos)
12329 (error "Not in a dynamic block"))))
12331 (defun org-update-all-dblocks ()
12332 "Update all dynamic blocks in the buffer.
12333 This function can be used in a hook."
12334 (interactive)
12335 (when (derived-mode-p 'org-mode)
12336 (org-map-dblocks 'org-update-dblock)))
12339 ;;;; Completion
12341 (declare-function org-export-backend-options "ox" (cl-x) t)
12342 (defun org-get-export-keywords ()
12343 "Return a list of all currently understood export keywords.
12344 Export keywords include options, block names, attributes and
12345 keywords relative to each registered export back-end."
12346 (let (keywords)
12347 (dolist (backend
12348 (bound-and-true-p org-export-registered-backends)
12349 (delq nil keywords))
12350 ;; Back-end name (for keywords, like #+LATEX:)
12351 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12352 (dolist (option-entry (org-export-backend-options backend))
12353 ;; Back-end options.
12354 (push (nth 1 option-entry) keywords)))))
12356 (defconst org-options-keywords
12357 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12358 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12359 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12360 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12361 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12363 (defcustom org-structure-template-alist
12364 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12365 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12366 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12367 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12368 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12369 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12370 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12371 ("L" "#+LaTeX: ")
12372 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12373 ("H" "#+HTML: ")
12374 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12375 ("A" "#+ASCII: ")
12376 ("i" "#+INDEX: ?")
12377 ("I" "#+INCLUDE: %file ?"))
12378 "Structure completion elements.
12379 This is a list of abbreviation keys and values. The value gets inserted
12380 if you type `<' followed by the key and then press the completion key,
12381 usually `TAB'. %file will be replaced by a file name after prompting
12382 for the file using completion. The cursor will be placed at the position
12383 of the `?' in the template.
12384 There are two templates for each key, the first uses the original Org syntax,
12385 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12386 the default when the /org-mtags.el/ module has been loaded. See also the
12387 variable `org-mtags-prefer-muse-templates'."
12388 :group 'org-completion
12389 :type '(repeat
12390 (list
12391 (string :tag "Key")
12392 (string :tag "Template")))
12393 :version "25.2"
12394 :package-version '(Org . "8.3"))
12396 (defun org-try-structure-completion ()
12397 "Try to complete a structure template before point.
12398 This looks for strings like \"<e\" on an otherwise empty line and
12399 expands them."
12400 (let ((l (buffer-substring (point-at-bol) (point)))
12402 (when (and (looking-at "[ \t]*$")
12403 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12404 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12405 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12406 (match-beginning 1)) a)
12407 t)))
12409 (defun org-complete-expand-structure-template (start cell)
12410 "Expand a structure template."
12411 (let ((rpl (nth 1 cell))
12412 (ind ""))
12413 (delete-region start (point))
12414 (when (string-match "\\`[ \t]*#\\+" rpl)
12415 (cond
12416 ((bolp))
12417 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12418 (setq ind (buffer-substring (point-at-bol) (point))))
12419 (t (newline))))
12420 (setq start (point))
12421 (when (string-match "%file" rpl)
12422 (setq rpl (replace-match
12423 (concat
12424 "\""
12425 (save-match-data
12426 (abbreviate-file-name (read-file-name "Include file: ")))
12427 "\"")
12428 t t rpl)))
12429 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12430 (concat "\n" ind)))
12431 (insert rpl)
12432 (when (re-search-backward "\\?" start t) (delete-char 1))))
12434 ;;;; TODO, DEADLINE, Comments
12436 (defun org-toggle-comment ()
12437 "Change the COMMENT state of an entry."
12438 (interactive)
12439 (save-excursion
12440 (org-back-to-heading)
12441 (looking-at org-complex-heading-regexp)
12442 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12443 (skip-chars-forward " \t")
12444 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12445 (if (org-in-commented-heading-p t)
12446 (delete-region (point)
12447 (progn (search-forward " " (line-end-position) 'move)
12448 (skip-chars-forward " \t")
12449 (point)))
12450 (insert org-comment-string)
12451 (unless (eolp) (insert " ")))))
12453 (defvar org-last-todo-state-is-todo nil
12454 "This is non-nil when the last TODO state change led to a TODO state.
12455 If the last change removed the TODO tag or switched to DONE, then
12456 this is nil.")
12458 (defvar org-setting-tags nil) ; dynamically skipped
12460 (defvar org-todo-setup-filter-hook nil
12461 "Hook for functions that pre-filter todo specs.
12462 Each function takes a todo spec and returns either nil or the spec
12463 transformed into canonical form." )
12465 (defvar org-todo-get-default-hook nil
12466 "Hook for functions that get a default item for todo.
12467 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12468 nil or a string to be used for the todo mark." )
12470 (defvar org-agenda-headline-snapshot-before-repeat)
12472 (defun org-current-effective-time ()
12473 "Return current time adjusted for `org-extend-today-until' variable."
12474 (let* ((ct (org-current-time))
12475 (dct (decode-time ct))
12476 (ct1
12477 (cond
12478 (org-use-last-clock-out-time-as-effective-time
12479 (or (org-clock-get-last-clock-out-time) ct))
12480 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12481 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12482 (t ct))))
12483 ct1))
12485 (defun org-todo-yesterday (&optional arg)
12486 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12487 (interactive "P")
12488 (if (eq major-mode 'org-agenda-mode)
12489 (apply 'org-agenda-todo-yesterday arg)
12490 (let* ((org-use-effective-time t)
12491 (hour (nth 2 (decode-time (org-current-time))))
12492 (org-extend-today-until (1+ hour)))
12493 (org-todo arg))))
12495 (defvar org-block-entry-blocking ""
12496 "First entry preventing the TODO state change.")
12498 (defun org-cancel-repeater ()
12499 "Cancel a repeater by setting its numeric value to zero."
12500 (interactive)
12501 (save-excursion
12502 (org-back-to-heading t)
12503 (let ((bound1 (point))
12504 (bound0 (save-excursion (outline-next-heading) (point))))
12505 (when (and (re-search-forward
12506 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12507 org-deadline-time-regexp "\\)\\|\\("
12508 org-ts-regexp "\\)")
12509 bound0 t)
12510 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12511 bound1 t))
12512 (replace-match "0" t nil nil 1)))))
12514 (defvar org-state) ;; dynamically scoped into this function
12515 (defun org-todo (&optional arg)
12516 "Change the TODO state of an item.
12517 The state of an item is given by a keyword at the start of the heading,
12518 like
12519 *** TODO Write paper
12520 *** DONE Call mom
12522 The different keywords are specified in the variable `org-todo-keywords'.
12523 By default the available states are \"TODO\" and \"DONE\".
12524 So for this example: when the item starts with TODO, it is changed to DONE.
12525 When it starts with DONE, the DONE is removed. And when neither TODO nor
12526 DONE are present, add TODO at the beginning of the heading.
12528 With \\[universal-argument] prefix arg, use completion to determine the new \
12529 state.
12530 With numeric prefix arg, switch to that state.
12531 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12532 keywords (nextset).
12533 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12534 With a numeric prefix arg of 0, inhibit note taking for the change.
12535 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12537 When called through ELisp, arg is also interpreted in the following way:
12538 `none' -> empty state
12539 \"\"(empty string) -> switch to empty state
12540 `done' -> switch to DONE
12541 `nextset' -> switch to the next set of keywords
12542 `previousset' -> switch to the previous set of keywords
12543 \"WAITING\" -> switch to the specified keyword, but only if it
12544 really is a member of `org-todo-keywords'."
12545 (interactive "P")
12546 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12547 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12548 'region-start-level 'region))
12549 org-loop-over-headlines-in-active-region)
12550 (org-map-entries
12551 `(org-todo ,arg)
12552 org-loop-over-headlines-in-active-region
12553 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12554 (when (equal arg '(16)) (setq arg 'nextset))
12555 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12556 (let ((org-blocker-hook org-blocker-hook)
12557 commentp
12558 case-fold-search)
12559 (when (equal arg '(64))
12560 (setq arg nil org-blocker-hook nil))
12561 (when (and org-blocker-hook
12562 (or org-inhibit-blocking
12563 (org-entry-get nil "NOBLOCKING")))
12564 (setq org-blocker-hook nil))
12565 (save-excursion
12566 (catch 'exit
12567 (org-back-to-heading t)
12568 (when (org-in-commented-heading-p t)
12569 (org-toggle-comment)
12570 (setq commentp t))
12571 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12572 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12573 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12574 (let* ((match-data (match-data))
12575 (startpos (point-at-bol))
12576 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12577 (org-log-done org-log-done)
12578 (org-log-repeat org-log-repeat)
12579 (org-todo-log-states org-todo-log-states)
12580 (org-inhibit-logging
12581 (if (equal arg 0)
12582 (progn (setq arg nil) 'note) org-inhibit-logging))
12583 (this (match-string 1))
12584 (hl-pos (match-beginning 0))
12585 (head (org-get-todo-sequence-head this))
12586 (ass (assoc head org-todo-kwd-alist))
12587 (interpret (nth 1 ass))
12588 (done-word (nth 3 ass))
12589 (final-done-word (nth 4 ass))
12590 (org-last-state (or this ""))
12591 (completion-ignore-case t)
12592 (member (member this org-todo-keywords-1))
12593 (tail (cdr member))
12594 (org-state (cond
12595 ((and org-todo-key-trigger
12596 (or (and (equal arg '(4))
12597 (eq org-use-fast-todo-selection 'prefix))
12598 (and (not arg) org-use-fast-todo-selection
12599 (not (eq org-use-fast-todo-selection
12600 'prefix)))))
12601 ;; Use fast selection
12602 (org-fast-todo-selection))
12603 ((and (equal arg '(4))
12604 (or (not org-use-fast-todo-selection)
12605 (not org-todo-key-trigger)))
12606 ;; Read a state with completion
12607 (completing-read
12608 "State: " (mapcar #'list org-todo-keywords-1)
12609 nil t))
12610 ((eq arg 'right)
12611 (if this
12612 (if tail (car tail) nil)
12613 (car org-todo-keywords-1)))
12614 ((eq arg 'left)
12615 (unless (equal member org-todo-keywords-1)
12616 (if this
12617 (nth (- (length org-todo-keywords-1)
12618 (length tail) 2)
12619 org-todo-keywords-1)
12620 (org-last org-todo-keywords-1))))
12621 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12622 (setq arg nil))) ; hack to fall back to cycling
12623 (arg
12624 ;; user or caller requests a specific state
12625 (cond
12626 ((equal arg "") nil)
12627 ((eq arg 'none) nil)
12628 ((eq arg 'done) (or done-word (car org-done-keywords)))
12629 ((eq arg 'nextset)
12630 (or (car (cdr (member head org-todo-heads)))
12631 (car org-todo-heads)))
12632 ((eq arg 'previousset)
12633 (let ((org-todo-heads (reverse org-todo-heads)))
12634 (or (car (cdr (member head org-todo-heads)))
12635 (car org-todo-heads))))
12636 ((car (member arg org-todo-keywords-1)))
12637 ((stringp arg)
12638 (user-error "State `%s' not valid in this file" arg))
12639 ((nth (1- (prefix-numeric-value arg))
12640 org-todo-keywords-1))))
12641 ((null member) (or head (car org-todo-keywords-1)))
12642 ((equal this final-done-word) nil) ;; -> make empty
12643 ((null tail) nil) ;; -> first entry
12644 ((memq interpret '(type priority))
12645 (if (eq this-command last-command)
12646 (car tail)
12647 (if (> (length tail) 0)
12648 (or done-word (car org-done-keywords))
12649 nil)))
12651 (car tail))))
12652 (org-state (or
12653 (run-hook-with-args-until-success
12654 'org-todo-get-default-hook org-state org-last-state)
12655 org-state))
12656 (next (if org-state (concat " " org-state " ") " "))
12657 (change-plist (list :type 'todo-state-change :from this :to org-state
12658 :position startpos))
12659 dolog now-done-p)
12660 (when org-blocker-hook
12661 (setq org-last-todo-state-is-todo
12662 (not (member this org-done-keywords)))
12663 (unless (save-excursion
12664 (save-match-data
12665 (org-with-wide-buffer
12666 (run-hook-with-args-until-failure
12667 'org-blocker-hook change-plist))))
12668 (if (called-interactively-p 'interactive)
12669 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12670 this org-state org-block-entry-blocking)
12671 ;; fail silently
12672 (message "TODO state change from %s to %s blocked (by \"%s\")"
12673 this org-state org-block-entry-blocking)
12674 (throw 'exit nil))))
12675 (store-match-data match-data)
12676 (replace-match next t t)
12677 (cond ((equal this org-state)
12678 (message "TODO state was already %s" (org-trim next)))
12679 ((pos-visible-in-window-p hl-pos)
12680 (message "TODO state changed to %s" (org-trim next))))
12681 (unless head
12682 (setq head (org-get-todo-sequence-head org-state)
12683 ass (assoc head org-todo-kwd-alist)
12684 interpret (nth 1 ass)
12685 done-word (nth 3 ass)
12686 final-done-word (nth 4 ass)))
12687 (when (memq arg '(nextset previousset))
12688 (message "Keyword-Set %d/%d: %s"
12689 (- (length org-todo-sets) -1
12690 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12691 (length org-todo-sets)
12692 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12693 (setq org-last-todo-state-is-todo
12694 (not (member org-state org-done-keywords)))
12695 (setq now-done-p (and (member org-state org-done-keywords)
12696 (not (member this org-done-keywords))))
12697 (and logging (org-local-logging logging))
12698 (when (and (or org-todo-log-states org-log-done)
12699 (not (eq org-inhibit-logging t))
12700 (not (memq arg '(nextset previousset))))
12701 ;; we need to look at recording a time and note
12702 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12703 (nth 2 (assoc this org-todo-log-states))))
12704 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12705 (setq dolog 'time))
12706 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12707 (and org-state
12708 (member org-state org-not-done-keywords)
12709 (not (member this org-not-done-keywords))))
12710 ;; This is now a todo state and was not one before
12711 ;; If there was a CLOSED time stamp, get rid of it.
12712 (org-add-planning-info nil nil 'closed))
12713 (when (and now-done-p org-log-done)
12714 ;; It is now done, and it was not done before
12715 (org-add-planning-info 'closed (org-current-effective-time))
12716 (when (and (not dolog) (eq 'note org-log-done))
12717 (org-add-log-setup 'done org-state this 'note)))
12718 (when (and org-state dolog)
12719 ;; This is a non-nil state, and we need to log it
12720 (org-add-log-setup 'state org-state this dolog)))
12721 ;; Fixup tag positioning
12722 (org-todo-trigger-tag-changes org-state)
12723 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12724 (when org-provide-todo-statistics
12725 (org-update-parent-todo-statistics))
12726 (run-hooks 'org-after-todo-state-change-hook)
12727 (when (and arg (not (member org-state org-done-keywords)))
12728 (setq head (org-get-todo-sequence-head org-state)))
12729 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12730 ;; Do we need to trigger a repeat?
12731 (when now-done-p
12732 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12733 ;; This is for the agenda, take a snapshot of the headline.
12734 (save-match-data
12735 (setq org-agenda-headline-snapshot-before-repeat
12736 (org-get-heading))))
12737 (org-auto-repeat-maybe org-state))
12738 ;; Fixup cursor location if close to the keyword
12739 (when (and (outline-on-heading-p)
12740 (not (bolp))
12741 (save-excursion (beginning-of-line 1)
12742 (looking-at org-todo-line-regexp))
12743 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12744 (goto-char (or (match-end 2) (match-end 1)))
12745 (and (looking-at " ") (just-one-space)))
12746 (when org-trigger-hook
12747 (save-excursion
12748 (run-hook-with-args 'org-trigger-hook change-plist)))
12749 (when commentp (org-toggle-comment))))))))
12751 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12752 "Block turning an entry into a TODO, using the hierarchy.
12753 This checks whether the current task should be blocked from state
12754 changes. Such blocking occurs when:
12756 1. The task has children which are not all in a completed state.
12758 2. A task has a parent with the property :ORDERED:, and there
12759 are siblings prior to the current task with incomplete
12760 status.
12762 3. The parent of the task is blocked because it has siblings that should
12763 be done first, or is child of a block grandparent TODO entry."
12765 (if (not org-enforce-todo-dependencies)
12766 t ; if locally turned off don't block
12767 (catch 'dont-block
12768 ;; If this is not a todo state change, or if this entry is already DONE,
12769 ;; do not block
12770 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12771 (member (plist-get change-plist :from)
12772 (cons 'done org-done-keywords))
12773 (member (plist-get change-plist :to)
12774 (cons 'todo org-not-done-keywords))
12775 (not (plist-get change-plist :to)))
12776 (throw 'dont-block t))
12777 ;; If this task has children, and any are undone, it's blocked
12778 (save-excursion
12779 (org-back-to-heading t)
12780 (let ((this-level (funcall outline-level)))
12781 (outline-next-heading)
12782 (let ((child-level (funcall outline-level)))
12783 (while (and (not (eobp))
12784 (> child-level this-level))
12785 ;; this todo has children, check whether they are all
12786 ;; completed
12787 (when (and (not (org-entry-is-done-p))
12788 (org-entry-is-todo-p))
12789 (setq org-block-entry-blocking (org-get-heading))
12790 (throw 'dont-block nil))
12791 (outline-next-heading)
12792 (setq child-level (funcall outline-level))))))
12793 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12794 ;; any previous siblings are undone, it's blocked
12795 (save-excursion
12796 (org-back-to-heading t)
12797 (let* ((pos (point))
12798 (parent-pos (and (org-up-heading-safe) (point))))
12799 (unless parent-pos (throw 'dont-block t)) ; no parent
12800 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12801 (forward-line 1)
12802 (re-search-forward org-not-done-heading-regexp pos t))
12803 (setq org-block-entry-blocking (match-string 0))
12804 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12805 ;; Search further up the hierarchy, to see if an ancestor is blocked
12806 (while t
12807 (goto-char parent-pos)
12808 (unless (looking-at org-not-done-heading-regexp)
12809 (throw 'dont-block t)) ; do not block, parent is not a TODO
12810 (setq pos (point))
12811 (setq parent-pos (and (org-up-heading-safe) (point)))
12812 (unless parent-pos (throw 'dont-block t)) ; no parent
12813 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12814 (forward-line 1)
12815 (re-search-forward org-not-done-heading-regexp pos t)
12816 (setq org-block-entry-blocking (org-get-heading)))
12817 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12819 (defcustom org-track-ordered-property-with-tag nil
12820 "Should the ORDERED property also be shown as a tag?
12821 The ORDERED property decides if an entry should require subtasks to be
12822 completed in sequence. Since a property is not very visible, setting
12823 this option means that toggling the ORDERED property with the command
12824 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12825 not relevant for the behavior, but it makes things more visible.
12827 Note that toggling the tag with tags commands will not change the property
12828 and therefore not influence behavior!
12830 This can be t, meaning the tag ORDERED should be used, It can also be a
12831 string to select a different tag for this task."
12832 :group 'org-todo
12833 :type '(choice
12834 (const :tag "No tracking" nil)
12835 (const :tag "Track with ORDERED tag" t)
12836 (string :tag "Use other tag")))
12838 (defun org-toggle-ordered-property ()
12839 "Toggle the ORDERED property of the current entry.
12840 For better visibility, you can track the value of this property with a tag.
12841 See variable `org-track-ordered-property-with-tag'."
12842 (interactive)
12843 (let* ((t1 org-track-ordered-property-with-tag)
12844 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12845 (save-excursion
12846 (org-back-to-heading)
12847 (if (org-entry-get nil "ORDERED")
12848 (progn
12849 (org-delete-property "ORDERED")
12850 (and tag (org-toggle-tag tag 'off))
12851 (message "Subtasks can be completed in arbitrary order"))
12852 (org-entry-put nil "ORDERED" "t")
12853 (and tag (org-toggle-tag tag 'on))
12854 (message "Subtasks must be completed in sequence")))))
12856 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12857 (defun org-block-todo-from-checkboxes (change-plist)
12858 "Block turning an entry into a TODO, using checkboxes.
12859 This checks whether the current task should be blocked from state
12860 changes because there are unchecked boxes in this entry."
12861 (if (not org-enforce-todo-checkbox-dependencies)
12862 t ; if locally turned off don't block
12863 (catch 'dont-block
12864 ;; If this is not a todo state change, or if this entry is already DONE,
12865 ;; do not block
12866 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12867 (member (plist-get change-plist :from)
12868 (cons 'done org-done-keywords))
12869 (member (plist-get change-plist :to)
12870 (cons 'todo org-not-done-keywords))
12871 (not (plist-get change-plist :to)))
12872 (throw 'dont-block t))
12873 ;; If this task has checkboxes that are not checked, it's blocked
12874 (save-excursion
12875 (org-back-to-heading t)
12876 (let ((beg (point)) end)
12877 (outline-next-heading)
12878 (setq end (point))
12879 (goto-char beg)
12880 (when (org-list-search-forward
12881 (concat (org-item-beginning-re)
12882 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12883 "\\[[- ]\\]")
12884 end t)
12885 (when (boundp 'org-blocked-by-checkboxes)
12886 (setq org-blocked-by-checkboxes t))
12887 (throw 'dont-block nil))))
12888 t))) ; do not block
12890 (defun org-entry-blocked-p ()
12891 "Non-nil if entry at point is blocked."
12892 (and (not (org-entry-get nil "NOBLOCKING"))
12893 (member (org-entry-get nil "TODO") org-not-done-keywords)
12894 (not (run-hook-with-args-until-failure
12895 'org-blocker-hook
12896 (list :type 'todo-state-change
12897 :position (point)
12898 :from 'todo
12899 :to 'done)))))
12901 (defun org-update-statistics-cookies (all)
12902 "Update the statistics cookie, either from TODO or from checkboxes.
12903 This should be called with the cursor in a line with a statistics
12904 cookie. When called with a \\[universal-argument] prefix, update
12905 all statistics cookies in the buffer."
12906 (interactive "P")
12907 (if all
12908 (progn
12909 (org-update-checkbox-count 'all)
12910 (org-map-entries 'org-update-parent-todo-statistics))
12911 (if (not (org-at-heading-p))
12912 (org-update-checkbox-count)
12913 (let ((pos (point-marker))
12914 end l1 l2)
12915 (ignore-errors (org-back-to-heading t))
12916 (if (not (org-at-heading-p))
12917 (org-update-checkbox-count)
12918 (setq l1 (org-outline-level))
12919 (setq end (save-excursion
12920 (outline-next-heading)
12921 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12922 (point)))
12923 (if (and (save-excursion
12924 (re-search-forward
12925 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12926 (not (save-excursion (re-search-forward
12927 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12928 (org-update-checkbox-count)
12929 (if (and l2 (> l2 l1))
12930 (progn
12931 (goto-char end)
12932 (org-update-parent-todo-statistics))
12933 (goto-char pos)
12934 (beginning-of-line 1)
12935 (while (re-search-forward
12936 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12937 (point-at-eol) t)
12938 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12939 (goto-char pos)
12940 (move-marker pos nil)))))
12942 (defvar org-entry-property-inherited-from) ;; defined below
12943 (defun org-update-parent-todo-statistics ()
12944 "Update any statistics cookie in the parent of the current headline.
12945 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12946 the entire subtree and this will travel up the hierarchy and update
12947 statistics everywhere."
12948 (let* ((prop (save-excursion (org-up-heading-safe)
12949 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12950 (recursive (or (not org-hierarchical-todo-statistics)
12951 (and prop (string-match "\\<recursive\\>" prop))))
12952 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12954 (first t)
12955 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12956 level ltoggle l1 new ndel
12957 (cnt-all 0) (cnt-done 0) is-percent kwd
12958 checkbox-beg cookie-present)
12959 (catch 'exit
12960 (save-excursion
12961 (beginning-of-line 1)
12962 (setq ltoggle (funcall outline-level))
12963 ;; Three situations are to consider:
12965 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12966 ;; to the top-level ancestor on the headline;
12968 ;; 2. If parent has "recursive" property, repeat up to the
12969 ;; headline setting that property, taking inheritance into
12970 ;; account;
12972 ;; 3. Else, move up to direct parent and proceed only once.
12973 (while (and (setq level (org-up-heading-safe))
12974 (or recursive first)
12975 (>= (point) lim))
12976 (setq first nil cookie-present nil)
12977 (unless (and level
12978 (not (string-match
12979 "\\<checkbox\\>"
12980 (downcase (or (org-entry-get nil "COOKIE_DATA")
12981 "")))))
12982 (throw 'exit nil))
12983 (while (re-search-forward box-re (point-at-eol) t)
12984 (setq cnt-all 0 cnt-done 0 cookie-present t)
12985 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12986 (save-match-data
12987 (unless (outline-next-heading) (throw 'exit nil))
12988 (while (and (looking-at org-complex-heading-regexp)
12989 (> (setq l1 (length (match-string 1))) level))
12990 (setq kwd (and (or recursive (= l1 ltoggle))
12991 (match-string 2)))
12992 (if (or (eq org-provide-todo-statistics 'all-headlines)
12993 (and (eq org-provide-todo-statistics t)
12994 (or (member kwd org-done-keywords)))
12995 (and (listp org-provide-todo-statistics)
12996 (stringp (car org-provide-todo-statistics))
12997 (or (member kwd org-provide-todo-statistics)
12998 (member kwd org-done-keywords)))
12999 (and (listp org-provide-todo-statistics)
13000 (listp (car org-provide-todo-statistics))
13001 (or (member kwd (car org-provide-todo-statistics))
13002 (and (member kwd org-done-keywords)
13003 (member kwd (cadr org-provide-todo-statistics))))))
13004 (setq cnt-all (1+ cnt-all))
13005 (and (eq org-provide-todo-statistics t)
13007 (setq cnt-all (1+ cnt-all))))
13008 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13009 (member kwd org-done-keywords))
13010 (and (listp org-provide-todo-statistics)
13011 (listp (car org-provide-todo-statistics))
13012 (member kwd org-done-keywords)
13013 (member kwd (cadr org-provide-todo-statistics)))
13014 (and (listp org-provide-todo-statistics)
13015 (stringp (car org-provide-todo-statistics))
13016 (member kwd org-done-keywords)))
13017 (setq cnt-done (1+ cnt-done)))
13018 (outline-next-heading)))
13019 (setq new
13020 (if is-percent
13021 (format "[%d%%]" (floor (* 100.0 cnt-done)
13022 (max 1 cnt-all)))
13023 (format "[%d/%d]" cnt-done cnt-all))
13024 ndel (- (match-end 0) checkbox-beg))
13025 (goto-char checkbox-beg)
13026 (insert new)
13027 (delete-region (point) (+ (point) ndel))
13028 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13029 (when cookie-present
13030 (run-hook-with-args 'org-after-todo-statistics-hook
13031 cnt-done (- cnt-all cnt-done))))))
13032 (run-hooks 'org-todo-statistics-hook)))
13034 (defvar org-after-todo-statistics-hook nil
13035 "Hook that is called after a TODO statistics cookie has been updated.
13036 Each function is called with two arguments: the number of not-done entries
13037 and the number of done entries.
13039 For example, the following function, when added to this hook, will switch
13040 an entry to DONE when all children are done, and back to TODO when new
13041 entries are set to a TODO status. Note that this hook is only called
13042 when there is a statistics cookie in the headline!
13044 \(defun org-summary-todo (n-done n-not-done)
13045 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13046 \(let (org-log-done org-log-states) ; turn off logging
13047 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13050 (defvar org-todo-statistics-hook nil
13051 "Hook that is run whenever Org thinks TODO statistics should be updated.
13052 This hook runs even if there is no statistics cookie present, in which case
13053 `org-after-todo-statistics-hook' would not run.")
13055 (defun org-todo-trigger-tag-changes (state)
13056 "Apply the changes defined in `org-todo-state-tags-triggers'."
13057 (let ((l org-todo-state-tags-triggers)
13058 changes)
13059 (when (or (not state) (equal state ""))
13060 (setq changes (append changes (cdr (assoc "" l)))))
13061 (when (and (stringp state) (> (length state) 0))
13062 (setq changes (append changes (cdr (assoc state l)))))
13063 (when (member state org-not-done-keywords)
13064 (setq changes (append changes (cdr (assq 'todo l)))))
13065 (when (member state org-done-keywords)
13066 (setq changes (append changes (cdr (assq 'done l)))))
13067 (dolist (c changes)
13068 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13070 (defun org-local-logging (value)
13071 "Get logging settings from a property VALUE."
13072 ;; Directly set the variables, they are already local.
13073 (setq org-log-done nil
13074 org-log-repeat nil
13075 org-todo-log-states nil)
13076 (dolist (w (org-split-string value))
13077 (let (a)
13078 (cond
13079 ((setq a (assoc w org-startup-options))
13080 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13081 (set (nth 1 a) (nth 2 a))))
13082 ((setq a (org-extract-log-state-settings w))
13083 (and (member (car a) org-todo-keywords-1)
13084 (push a org-todo-log-states)))))))
13086 (defun org-get-todo-sequence-head (kwd)
13087 "Return the head of the TODO sequence to which KWD belongs.
13088 If KWD is not set, check if there is a text property remembering the
13089 right sequence."
13090 (let (p)
13091 (cond
13092 ((not kwd)
13093 (or (get-text-property (point-at-bol) 'org-todo-head)
13094 (progn
13095 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13096 nil (point-at-eol)))
13097 (get-text-property p 'org-todo-head))))
13098 ((not (member kwd org-todo-keywords-1))
13099 (car org-todo-keywords-1))
13100 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13102 (defun org-fast-todo-selection ()
13103 "Fast TODO keyword selection with single keys.
13104 Returns the new TODO keyword, or nil if no state change should occur."
13105 (let* ((fulltable org-todo-key-alist)
13106 (done-keywords org-done-keywords) ;; needed for the faces.
13107 (maxlen (apply 'max (mapcar
13108 (lambda (x)
13109 (if (stringp (car x)) (string-width (car x)) 0))
13110 fulltable)))
13111 (expert nil)
13112 (fwidth (+ maxlen 3 1 3))
13113 (ncol (/ (- (window-width) 4) fwidth))
13114 tg cnt e c tbl
13115 groups ingroup)
13116 (save-excursion
13117 (save-window-excursion
13118 (if expert
13119 (set-buffer (get-buffer-create " *Org todo*"))
13120 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13121 (erase-buffer)
13122 (setq-local org-done-keywords done-keywords)
13123 (setq tbl fulltable cnt 0)
13124 (while (setq e (pop tbl))
13125 (cond
13126 ((equal e '(:startgroup))
13127 (push '() groups) (setq ingroup t)
13128 (unless (= cnt 0)
13129 (setq cnt 0)
13130 (insert "\n"))
13131 (insert "{ "))
13132 ((equal e '(:endgroup))
13133 (setq ingroup nil cnt 0)
13134 (insert "}\n"))
13135 ((equal e '(:newline))
13136 (unless (= cnt 0)
13137 (setq cnt 0)
13138 (insert "\n")
13139 (setq e (car tbl))
13140 (while (equal (car tbl) '(:newline))
13141 (insert "\n")
13142 (setq tbl (cdr tbl)))))
13144 (setq tg (car e) c (cdr e))
13145 (when ingroup (push tg (car groups)))
13146 (setq tg (org-add-props tg nil 'face
13147 (org-get-todo-face tg)))
13148 (when (and (= cnt 0) (not ingroup)) (insert " "))
13149 (insert "[" c "] " tg (make-string
13150 (- fwidth 4 (length tg)) ?\ ))
13151 (when (= (setq cnt (1+ cnt)) ncol)
13152 (insert "\n")
13153 (when ingroup (insert " "))
13154 (setq cnt 0)))))
13155 (insert "\n")
13156 (goto-char (point-min))
13157 (unless expert (org-fit-window-to-buffer))
13158 (message "[a-z..]:Set [SPC]:clear")
13159 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13160 (cond
13161 ((or (= c ?\C-g)
13162 (and (= c ?q) (not (rassoc c fulltable))))
13163 (setq quit-flag t))
13164 ((= c ?\ ) nil)
13165 ((setq e (rassoc c fulltable) tg (car e))
13167 (t (setq quit-flag t)))))))
13169 (defun org-entry-is-todo-p ()
13170 (member (org-get-todo-state) org-not-done-keywords))
13172 (defun org-entry-is-done-p ()
13173 (member (org-get-todo-state) org-done-keywords))
13175 (defun org-get-todo-state ()
13176 "Return the TODO keyword of the current subtree."
13177 (save-excursion
13178 (org-back-to-heading t)
13179 (and (looking-at org-todo-line-regexp)
13180 (match-end 2)
13181 (match-string 2))))
13183 (defun org-at-date-range-p (&optional inactive-ok)
13184 "Non-nil if point is inside a date range.
13186 When optional argument INACTIVE-OK is non-nil, also consider
13187 inactive time ranges.
13189 When this function returns a non-nil value, match data is set
13190 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13191 on INACTIVE-OK."
13192 (interactive)
13193 (save-excursion
13194 (catch 'exit
13195 (let ((pos (point)))
13196 (skip-chars-backward "^[<\r\n")
13197 (skip-chars-backward "<[")
13198 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13199 (>= (match-end 0) pos)
13200 (throw 'exit t))
13201 (skip-chars-backward "^<[\r\n")
13202 (skip-chars-backward "<[")
13203 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13204 (>= (match-end 0) pos)
13205 (throw 'exit t)))
13206 nil)))
13208 (defun org-get-repeat (&optional tagline)
13209 "Check if there is a deadline/schedule with repeater in this entry."
13210 (save-match-data
13211 (save-excursion
13212 (org-back-to-heading t)
13213 (and (re-search-forward (if tagline
13214 (concat tagline "\\s-*" org-repeat-re)
13215 org-repeat-re)
13216 (org-entry-end-position) t)
13217 (match-string-no-properties 1)))))
13219 (defvar org-last-changed-timestamp)
13220 (defvar org-last-inserted-timestamp)
13221 (defvar org-log-post-message)
13222 (defvar org-log-note-purpose)
13223 (defvar org-log-note-how nil)
13224 (defvar org-log-note-extra)
13225 (defun org-auto-repeat-maybe (done-word)
13226 "Check if the current headline contains a repeated time-stamp.
13228 If yes, set TODO state back to what it was and change the base date
13229 of repeating deadline/scheduled time stamps to new date.
13231 This function is run automatically after each state change to a DONE state."
13232 (let* ((repeat (org-get-repeat))
13233 (aa (assoc org-last-state org-todo-kwd-alist))
13234 (interpret (nth 1 aa))
13235 (head (nth 2 aa))
13236 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13237 (msg "Entry repeats: ")
13238 (org-log-done nil)
13239 (org-todo-log-states nil))
13240 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13241 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13242 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13243 org-todo-repeat-to-state)))
13244 (unless (and to-state (member to-state org-todo-keywords-1))
13245 (setq to-state (if (eq interpret 'type) org-last-state head)))
13246 (org-todo to-state))
13247 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13248 (org-entry-put nil "LAST_REPEAT" (format-time-string
13249 (org-time-stamp-format t t))))
13250 (when org-log-repeat
13251 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13252 (memq 'org-add-log-note post-command-hook))
13253 ;; We are already setup for some record.
13254 (when (eq org-log-repeat 'note)
13255 ;; Make sure we take a note, not only a time stamp.
13256 (setq org-log-note-how 'note))
13257 ;; Set up for taking a record.
13258 (org-add-log-setup 'state
13259 (or done-word (car org-done-keywords))
13260 org-last-state
13261 org-log-repeat)))
13262 (org-back-to-heading t)
13263 (org-add-planning-info nil nil 'closed)
13264 (let ((end (save-excursion (outline-next-heading) (point))))
13265 (while (re-search-forward org-ts-regexp end t)
13266 (when (save-match-data
13267 (or (org-at-planning-p)
13268 (org-at-property-p)
13269 (eq (org-element-type (save-excursion
13270 (backward-char)
13271 (org-element-context)))
13272 'timestamp)))
13273 (let ((type (cond ((match-end 1) org-scheduled-string)
13274 ((match-end 3) org-deadline-string)
13275 (t "Plain:")))
13276 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13277 (cond
13278 ((not
13279 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13280 ;; Time-stamps without a repeater are usually skipped.
13281 ;; However, a SCHEDULED time-stamp without one is
13282 ;; removed, as it is considered as no longer relevant.
13283 (when (equal type org-scheduled-string)
13284 (org-remove-timestamp-with-keyword type)))
13286 (let ((n (string-to-number (match-string 2 ts)))
13287 (what (match-string 3 ts)))
13288 (when (equal what "w") (setq n (* n 7) what "d"))
13289 (when (and (equal what "h")
13290 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13291 ts)))
13292 (user-error
13293 "Cannot repeat in Repeat in %d hour(s) because no hour \
13294 has been set"
13296 ;; Preparation, see if we need to modify the start
13297 ;; date for the change.
13298 (when (match-end 1)
13299 (let ((time (save-match-data (org-time-string-to-time ts))))
13300 (cond
13301 ((equal (match-string 1 ts) ".")
13302 ;; Shift starting date to today
13303 (org-timestamp-change
13304 (- (org-today) (time-to-days time))
13305 'day))
13306 ((equal (match-string 1 ts) "+")
13307 (let ((nshiftmax 10)
13308 (nshift 0))
13309 (while (or (= nshift 0)
13310 (not (time-less-p (current-time) time)))
13311 (when (= (cl-incf nshift) nshiftmax)
13312 (or (y-or-n-p
13313 (format "%d repeater intervals were not \
13314 enough to shift date past today. Continue? "
13315 nshift))
13316 (user-error "Abort")))
13317 (org-timestamp-change n (cdr (assoc what whata)))
13318 (org-at-timestamp-p t)
13319 (setq ts (match-string 1))
13320 (setq time
13321 (save-match-data
13322 (org-time-string-to-time ts)))))
13323 (org-timestamp-change (- n) (cdr (assoc what whata)))
13324 ;; Rematch, so that we have everything in
13325 ;; place for the real shift.
13326 (org-at-timestamp-p t)
13327 (setq ts (match-string 1))
13328 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13329 ts)))))
13330 (save-excursion
13331 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13332 (setq msg
13333 (concat
13334 msg type " " org-last-changed-timestamp " ")))))))))
13335 (setq org-log-post-message msg)
13336 (message "%s" msg))))
13338 (defun org-show-todo-tree (arg)
13339 "Make a compact tree which shows all headlines marked with TODO.
13340 The tree will show the lines where the regexp matches, and all higher
13341 headlines above the match.
13342 With a \\[universal-argument] prefix, prompt for a regexp to match.
13343 With a numeric prefix N, construct a sparse tree for the Nth element
13344 of `org-todo-keywords-1'."
13345 (interactive "P")
13346 (let ((case-fold-search nil)
13347 (kwd-re
13348 (cond ((null arg) org-not-done-regexp)
13349 ((equal arg '(4))
13350 (let ((kwd
13351 (completing-read "Keyword (or KWD1|KWD2|...): "
13352 (mapcar #'list org-todo-keywords-1))))
13353 (concat "\\("
13354 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13355 "\\)\\>")))
13356 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13357 (regexp-quote (nth (1- (prefix-numeric-value arg))
13358 org-todo-keywords-1)))
13359 (t (user-error "Invalid prefix argument: %s" arg)))))
13360 (message "%d TODO entries found"
13361 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13363 (defun org-deadline (arg &optional time)
13364 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13365 With one universal prefix argument, remove any deadline from the item.
13366 With two universal prefix arguments, prompt for a warning delay.
13367 With argument TIME, set the deadline at the corresponding date. TIME
13368 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13369 (interactive "P")
13370 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13371 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13372 'region-start-level 'region))
13373 org-loop-over-headlines-in-active-region)
13374 (org-map-entries
13375 `(org-deadline ',arg ,time)
13376 org-loop-over-headlines-in-active-region
13377 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13378 (let* ((old-date (org-entry-get nil "DEADLINE"))
13379 (old-date-time (when old-date (org-time-string-to-time old-date)))
13380 (repeater (and old-date
13381 (string-match
13382 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13383 old-date)
13384 (match-string 1 old-date))))
13385 (cond
13386 ((equal arg '(4))
13387 (when (and old-date org-log-redeadline)
13388 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13389 (org-remove-timestamp-with-keyword org-deadline-string)
13390 (message "Item no longer has a deadline."))
13391 ((equal arg '(16))
13392 (save-excursion
13393 (org-back-to-heading t)
13394 (if (re-search-forward
13395 org-deadline-time-regexp
13396 (save-excursion (outline-next-heading) (point)) t)
13397 (let* ((rpl0 (match-string 1))
13398 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13399 (replace-match
13400 (concat org-deadline-string
13401 " <" rpl
13402 (format " -%dd"
13403 (abs
13404 (- (time-to-days
13405 (save-match-data
13406 (org-read-date nil t nil "Warn starting from" old-date-time)))
13407 (time-to-days old-date-time))))
13408 ">") t t))
13409 (user-error "No deadline information to update"))))
13411 (org-add-planning-info 'deadline time 'closed)
13412 (when (and old-date
13413 org-log-redeadline
13414 (not (equal old-date org-last-inserted-timestamp)))
13415 (org-add-log-setup
13416 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13417 (when repeater
13418 (save-excursion
13419 (org-back-to-heading t)
13420 (when (re-search-forward (concat org-deadline-string " "
13421 org-last-inserted-timestamp)
13422 (save-excursion
13423 (outline-next-heading) (point)) t)
13424 (goto-char (1- (match-end 0)))
13425 (insert " " repeater)
13426 (setq org-last-inserted-timestamp
13427 (concat (substring org-last-inserted-timestamp 0 -1)
13428 " " repeater
13429 (substring org-last-inserted-timestamp -1))))))
13430 (message "Deadline on %s" org-last-inserted-timestamp))))))
13432 (defun org-schedule (arg &optional time)
13433 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13434 With one universal prefix argument, remove any scheduling date from the item.
13435 With two universal prefix arguments, prompt for a delay cookie.
13436 With argument TIME, scheduled at the corresponding date. TIME can
13437 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13438 (interactive "P")
13439 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13440 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13441 'region-start-level 'region))
13442 org-loop-over-headlines-in-active-region)
13443 (org-map-entries
13444 `(org-schedule ',arg ,time)
13445 org-loop-over-headlines-in-active-region
13446 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13447 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13448 (old-date-time (when old-date (org-time-string-to-time old-date)))
13449 (repeater (and old-date
13450 (string-match
13451 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13452 old-date)
13453 (match-string 1 old-date))))
13454 (cond
13455 ((equal arg '(4))
13456 (progn
13457 (when (and old-date org-log-reschedule)
13458 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13459 (org-remove-timestamp-with-keyword org-scheduled-string)
13460 (message "Item is no longer scheduled.")))
13461 ((equal arg '(16))
13462 (save-excursion
13463 (org-back-to-heading t)
13464 (if (re-search-forward
13465 org-scheduled-time-regexp
13466 (save-excursion (outline-next-heading) (point)) t)
13467 (let* ((rpl0 (match-string 1))
13468 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13469 (replace-match
13470 (concat org-scheduled-string
13471 " <" rpl
13472 (format " -%dd"
13473 (abs
13474 (- (time-to-days
13475 (save-match-data
13476 (org-read-date nil t nil "Delay until" old-date-time)))
13477 (time-to-days old-date-time))))
13478 ">") t t))
13479 (user-error "No scheduled information to update"))))
13481 (org-add-planning-info 'scheduled time 'closed)
13482 (when (and old-date
13483 org-log-reschedule
13484 (not (equal old-date org-last-inserted-timestamp)))
13485 (org-add-log-setup
13486 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13487 (when repeater
13488 (save-excursion
13489 (org-back-to-heading t)
13490 (when (re-search-forward (concat org-scheduled-string " "
13491 org-last-inserted-timestamp)
13492 (save-excursion
13493 (outline-next-heading) (point)) t)
13494 (goto-char (1- (match-end 0)))
13495 (insert " " repeater)
13496 (setq org-last-inserted-timestamp
13497 (concat (substring org-last-inserted-timestamp 0 -1)
13498 " " repeater
13499 (substring org-last-inserted-timestamp -1))))))
13500 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13502 (defun org-get-scheduled-time (pom &optional inherit)
13503 "Get the scheduled time as a time tuple, of a format suitable
13504 for calling org-schedule with, or if there is no scheduling,
13505 returns nil."
13506 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13507 (when time
13508 (apply 'encode-time (org-parse-time-string time)))))
13510 (defun org-get-deadline-time (pom &optional inherit)
13511 "Get the deadline as a time tuple, of a format suitable for
13512 calling org-deadline with, or if there is no scheduling, returns
13513 nil."
13514 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13515 (when time
13516 (apply 'encode-time (org-parse-time-string time)))))
13518 (defun org-remove-timestamp-with-keyword (keyword)
13519 "Remove all time stamps with KEYWORD in the current entry."
13520 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13521 beg)
13522 (save-excursion
13523 (org-back-to-heading t)
13524 (setq beg (point))
13525 (outline-next-heading)
13526 (while (re-search-backward re beg t)
13527 (replace-match "")
13528 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13529 (equal (char-before) ?\ ))
13530 (backward-delete-char 1)
13531 (when (string-match "^[ \t]*$" (buffer-substring
13532 (point-at-bol) (point-at-eol)))
13533 (delete-region (point-at-bol)
13534 (min (point-max) (1+ (point-at-eol))))))))))
13536 (defvar org-time-was-given) ; dynamically scoped parameter
13537 (defvar org-end-time-was-given) ; dynamically scoped parameter
13539 (defun org-at-planning-p ()
13540 "Non-nil when point is on a planning info line."
13541 ;; This is as accurate and faster than `org-element-at-point' since
13542 ;; planning info location is fixed in the section.
13543 (org-with-wide-buffer
13544 (beginning-of-line)
13545 (and (looking-at-p org-planning-line-re)
13546 (eq (point)
13547 (ignore-errors
13548 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13549 (org-back-to-heading t)
13550 (org-with-limited-levels (org-back-to-heading t)))
13551 (line-beginning-position 2))))))
13553 (defun org-add-planning-info (what &optional time &rest remove)
13554 "Insert new timestamp with keyword in the planning line.
13555 WHAT indicates what kind of time stamp to add. It is a symbol
13556 among `closed', `deadline', `scheduled' and nil. TIME indicates
13557 the time to use. If none is given, the user is prompted for
13558 a date. REMOVE indicates what kind of entries to remove. An old
13559 WHAT entry will also be removed."
13560 (let (org-time-was-given org-end-time-was-given default-time default-input)
13561 (catch 'exit
13562 (when (and (memq what '(scheduled deadline))
13563 (or (not time)
13564 (and (stringp time)
13565 (string-match "^[-+]+[0-9]" time))))
13566 ;; Try to get a default date/time from existing timestamp
13567 (save-excursion
13568 (org-back-to-heading t)
13569 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13570 (when (re-search-forward (if (eq what 'scheduled)
13571 org-scheduled-time-regexp
13572 org-deadline-time-regexp)
13573 end t)
13574 (setq ts (match-string 1)
13575 default-time (apply 'encode-time (org-parse-time-string ts))
13576 default-input (and ts (org-get-compact-tod ts)))))))
13577 (when what
13578 (setq time
13579 (if (stringp time)
13580 ;; This is a string (relative or absolute), set
13581 ;; proper date.
13582 (apply #'encode-time
13583 (org-read-date-analyze
13584 time default-time (decode-time default-time)))
13585 ;; If necessary, get the time from the user
13586 (or time (org-read-date nil 'to-time nil nil
13587 default-time default-input)))))
13589 (org-with-wide-buffer
13590 (org-back-to-heading t)
13591 (forward-line)
13592 (unless (bolp) (insert "\n"))
13593 (cond ((looking-at-p org-planning-line-re)
13594 ;; Move to current indentation.
13595 (skip-chars-forward " \t")
13596 ;; Check if we have to remove something.
13597 (dolist (type (if what (cons what remove) remove))
13598 (save-excursion
13599 (when (re-search-forward
13600 (cl-case type
13601 (closed org-closed-time-regexp)
13602 (deadline org-deadline-time-regexp)
13603 (scheduled org-scheduled-time-regexp)
13604 (otherwise
13605 (error "Invalid planning type: %s" type)))
13606 (line-end-position) t)
13607 ;; Delete until next keyword or end of line.
13608 (delete-region
13609 (match-beginning 0)
13610 (if (re-search-forward org-keyword-time-not-clock-regexp
13611 (line-end-position)
13613 (match-beginning 0)
13614 (line-end-position))))))
13615 ;; If there is nothing more to add and no more keyword
13616 ;; is left, remove the line completely.
13617 (if (and (looking-at-p "[ \t]*$") (not what))
13618 (delete-region (line-beginning-position)
13619 (line-beginning-position 2))
13620 ;; If we removed last keyword, do not leave trailing
13621 ;; white space at the end of line.
13622 (let ((p (point)))
13623 (save-excursion
13624 (end-of-line)
13625 (unless (= (skip-chars-backward " \t" p) 0)
13626 (delete-region (point) (line-end-position)))))))
13627 ((not what) (throw 'exit nil)) ; Nothing to do.
13628 (t (insert-before-markers "\n")
13629 (backward-char 1)
13630 (when org-adapt-indentation
13631 (indent-to-column (1+ (org-outline-level))))))
13632 (when what
13633 ;; Insert planning keyword.
13634 (insert (cl-case what
13635 (closed org-closed-string)
13636 (deadline org-deadline-string)
13637 (scheduled org-scheduled-string)
13638 (otherwise (error "Invalid planning type: %s" what)))
13639 " ")
13640 ;; Insert associated timestamp.
13641 (let ((ts (org-insert-time-stamp
13642 time
13643 (or org-time-was-given
13644 (and (eq what 'closed) org-log-done-with-time))
13645 (eq what 'closed)
13646 nil nil (list org-end-time-was-given))))
13647 (unless (eolp) (insert " "))
13648 ts))))))
13650 (defvar org-log-note-marker (make-marker)
13651 "Marker pointing at the entry where the note is to be inserted.")
13652 (defvar org-log-note-purpose nil)
13653 (defvar org-log-note-state nil)
13654 (defvar org-log-note-previous-state nil)
13655 (defvar org-log-note-extra nil)
13656 (defvar org-log-note-window-configuration nil)
13657 (defvar org-log-note-return-to (make-marker))
13658 (defvar org-log-note-effective-time nil
13659 "Remembered current time so that dynamically scoped
13660 `org-extend-today-until' affects timestamps in state change log")
13662 (defvar org-log-post-message nil
13663 "Message to be displayed after a log note has been stored.
13664 The auto-repeater uses this.")
13666 (defun org-add-note ()
13667 "Add a note to the current entry.
13668 This is done in the same way as adding a state change note."
13669 (interactive)
13670 (org-add-log-setup 'note))
13672 (defun org-log-beginning (&optional create)
13673 "Return expected start of log notes in current entry.
13674 When optional argument CREATE is non-nil, the function creates
13675 a drawer to store notes, if necessary. Returned position ignores
13676 narrowing."
13677 (org-with-wide-buffer
13678 (let ((drawer (org-log-into-drawer)))
13679 (cond
13680 (drawer
13681 (org-end-of-meta-data)
13682 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13683 (end (if (org-at-heading-p) (point)
13684 (save-excursion (outline-next-heading) (point))))
13685 (case-fold-search t))
13686 (catch 'exit
13687 ;; Try to find existing drawer.
13688 (while (re-search-forward regexp end t)
13689 (let ((element (org-element-at-point)))
13690 (when (eq (org-element-type element) 'drawer)
13691 (let ((cend (org-element-property :contents-end element)))
13692 (when (and (not org-log-states-order-reversed) cend)
13693 (goto-char cend)))
13694 (throw 'exit nil))))
13695 ;; No drawer found. Create one, if permitted.
13696 (when create
13697 (unless (bolp) (insert "\n"))
13698 (let ((beg (point)))
13699 (insert ":" drawer ":\n:END:\n")
13700 (org-indent-region beg (point)))
13701 (end-of-line -1)))))
13703 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13704 (skip-chars-forward " \t\n")
13705 (beginning-of-line)
13706 (unless org-log-states-order-reversed
13707 (org-skip-over-state-notes)
13708 (skip-chars-backward " \t\n")
13709 (forward-line)))))
13710 (if (bolp) (point) (line-beginning-position 2))))
13712 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13713 "Set up the post command hook to take a note.
13714 If this is about to TODO state change, the new state is expected in STATE.
13715 HOW is an indicator what kind of note should be created.
13716 EXTRA is additional text that will be inserted into the notes buffer."
13717 (move-marker org-log-note-marker (point))
13718 (setq org-log-note-purpose purpose
13719 org-log-note-state state
13720 org-log-note-previous-state prev-state
13721 org-log-note-how how
13722 org-log-note-extra extra
13723 org-log-note-effective-time (org-current-effective-time))
13724 (add-hook 'post-command-hook 'org-add-log-note 'append))
13726 (defun org-skip-over-state-notes ()
13727 "Skip past the list of State notes in an entry."
13728 (when (ignore-errors (goto-char (org-in-item-p)))
13729 (let* ((struct (org-list-struct))
13730 (prevs (org-list-prevs-alist struct))
13731 (regexp
13732 (concat "[ \t]*- +"
13733 (replace-regexp-in-string
13734 " +" " +"
13735 (org-replace-escapes
13736 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13737 `(("%d" . ,org-ts-regexp-inactive)
13738 ("%D" . ,org-ts-regexp)
13739 ("%s" . "\"\\S-+\"")
13740 ("%S" . "\"\\S-+\"")
13741 ("%t" . ,org-ts-regexp-inactive)
13742 ("%T" . ,org-ts-regexp)
13743 ("%u" . ".*?")
13744 ("%U" . ".*?")))))))
13745 (while (looking-at-p regexp)
13746 (goto-char (or (org-list-get-next-item (point) struct prevs)
13747 (org-list-get-item-end (point) struct)))))))
13749 (defun org-add-log-note (&optional _purpose)
13750 "Pop up a window for taking a note, and add this note later."
13751 (remove-hook 'post-command-hook 'org-add-log-note)
13752 (setq org-log-note-window-configuration (current-window-configuration))
13753 (delete-other-windows)
13754 (move-marker org-log-note-return-to (point))
13755 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13756 (goto-char org-log-note-marker)
13757 (org-switch-to-buffer-other-window "*Org Note*")
13758 (erase-buffer)
13759 (if (memq org-log-note-how '(time state))
13760 (let (current-prefix-arg) (org-store-log-note))
13761 (let ((org-inhibit-startup t)) (org-mode))
13762 (insert (format "# Insert note for %s.
13763 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13764 (cond
13765 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13766 ((eq org-log-note-purpose 'done) "closed todo item")
13767 ((eq org-log-note-purpose 'state)
13768 (format "state change from \"%s\" to \"%s\""
13769 (or org-log-note-previous-state "")
13770 (or org-log-note-state "")))
13771 ((eq org-log-note-purpose 'reschedule)
13772 "rescheduling")
13773 ((eq org-log-note-purpose 'delschedule)
13774 "no longer scheduled")
13775 ((eq org-log-note-purpose 'redeadline)
13776 "changing deadline")
13777 ((eq org-log-note-purpose 'deldeadline)
13778 "removing deadline")
13779 ((eq org-log-note-purpose 'refile)
13780 "refiling")
13781 ((eq org-log-note-purpose 'note)
13782 "this entry")
13783 (t (error "This should not happen")))))
13784 (when org-log-note-extra (insert org-log-note-extra))
13785 (setq-local org-finish-function 'org-store-log-note)
13786 (run-hooks 'org-log-buffer-setup-hook)))
13788 (defvar org-note-abort nil) ; dynamically scoped
13789 (defun org-store-log-note ()
13790 "Finish taking a log note, and insert it to where it belongs."
13791 (let ((txt (prog1 (buffer-string)
13792 (kill-buffer)))
13793 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13794 lines)
13795 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13796 (setq txt (replace-match "" t t txt)))
13797 (when (string-match "\\s-+\\'" txt)
13798 (setq txt (replace-match "" t t txt)))
13799 (setq lines (org-split-string txt "\n"))
13800 (when (org-string-nw-p note)
13801 (setq note
13802 (org-replace-escapes
13803 note
13804 (list (cons "%u" (user-login-name))
13805 (cons "%U" user-full-name)
13806 (cons "%t" (format-time-string
13807 (org-time-stamp-format 'long 'inactive)
13808 org-log-note-effective-time))
13809 (cons "%T" (format-time-string
13810 (org-time-stamp-format 'long nil)
13811 org-log-note-effective-time))
13812 (cons "%d" (format-time-string
13813 (org-time-stamp-format nil 'inactive)
13814 org-log-note-effective-time))
13815 (cons "%D" (format-time-string
13816 (org-time-stamp-format nil nil)
13817 org-log-note-effective-time))
13818 (cons "%s" (cond
13819 ((not org-log-note-state) "")
13820 ((string-match-p org-ts-regexp
13821 org-log-note-state)
13822 (format "\"[%s]\""
13823 (substring org-log-note-state 1 -1)))
13824 (t (format "\"%s\"" org-log-note-state))))
13825 (cons "%S"
13826 (cond
13827 ((not org-log-note-previous-state) "")
13828 ((string-match-p org-ts-regexp
13829 org-log-note-previous-state)
13830 (format "\"[%s]\""
13831 (substring
13832 org-log-note-previous-state 1 -1)))
13833 (t (format "\"%s\""
13834 org-log-note-previous-state)))))))
13835 (when lines (setq note (concat note " \\\\")))
13836 (push note lines))
13837 (when (and lines (not (or current-prefix-arg org-note-abort)))
13838 (with-current-buffer (marker-buffer org-log-note-marker)
13839 (org-with-wide-buffer
13840 ;; Find location for the new note.
13841 (goto-char org-log-note-marker)
13842 (set-marker org-log-note-marker nil)
13843 (goto-char (org-log-beginning t))
13844 ;; Make sure point is at the beginning of an empty line.
13845 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13846 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13847 ;; In an existing list, add a new item at the top level.
13848 ;; Otherwise, indent line like a regular one.
13849 (let ((itemp (org-in-item-p)))
13850 (if itemp
13851 (indent-line-to
13852 (let ((struct (save-excursion
13853 (goto-char itemp) (org-list-struct))))
13854 (org-list-get-ind (org-list-get-top-point struct) struct)))
13855 (org-indent-line)))
13856 (insert (org-list-bullet-string "-") (pop lines))
13857 (let ((ind (org-list-item-body-column (line-beginning-position))))
13858 (dolist (line lines)
13859 (insert "\n")
13860 (indent-line-to ind)
13861 (insert line)))
13862 (message "Note stored")
13863 (org-back-to-heading t)
13864 (org-cycle-hide-drawers 'children))
13865 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13866 ;; from within `org-add-log-note' because `buffer-undo-list'
13867 ;; is then modified outside of `org-with-remote-undo'.
13868 (when (eq this-command 'org-agenda-todo)
13869 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13870 ;; Don't add undo information when called from `org-agenda-todo'.
13871 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13872 (set-window-configuration org-log-note-window-configuration)
13873 (with-current-buffer (marker-buffer org-log-note-return-to)
13874 (goto-char org-log-note-return-to))
13875 (move-marker org-log-note-return-to nil)
13876 (when org-log-post-message (message "%s" org-log-post-message))))
13878 (defun org-remove-empty-drawer-at (pos)
13879 "Remove an empty drawer at position POS.
13880 POS may also be a marker."
13881 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13882 (org-with-wide-buffer
13883 (goto-char pos)
13884 (let ((drawer (org-element-at-point)))
13885 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13886 (not (org-element-property :contents-begin drawer)))
13887 (delete-region (org-element-property :begin drawer)
13888 (progn (goto-char (org-element-property :end drawer))
13889 (skip-chars-backward " \r\t\n")
13890 (forward-line)
13891 (point))))))))
13893 (defvar org-ts-type nil)
13894 (defun org-sparse-tree (&optional arg type)
13895 "Create a sparse tree, prompt for the details.
13896 This command can create sparse trees. You first need to select the type
13897 of match used to create the tree:
13899 t Show all TODO entries.
13900 T Show entries with a specific TODO keyword.
13901 m Show entries selected by a tags/property match.
13902 p Enter a property name and its value (both with completion on existing
13903 names/values) and show entries with that property.
13904 r Show entries matching a regular expression (`/' can be used as well).
13905 b Show deadlines and scheduled items before a date.
13906 a Show deadlines and scheduled items after a date.
13907 d Show deadlines due within `org-deadline-warning-days'.
13908 D Show deadlines and scheduled items between a date range."
13909 (interactive "P")
13910 (setq type (or type org-sparse-tree-default-date-type))
13911 (setq org-ts-type type)
13912 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13913 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13914 \[c]ycle through date types: %s"
13915 (cl-case type
13916 (all "all timestamps")
13917 (scheduled "only scheduled")
13918 (deadline "only deadline")
13919 (active "only active timestamps")
13920 (inactive "only inactive timestamps")
13921 (closed "with a closed time-stamp")
13922 (otherwise "scheduled/deadline")))
13923 (let ((answer (read-char-exclusive)))
13924 (cl-case answer
13926 (org-sparse-tree
13928 (cadr
13929 (memq type '(nil all scheduled deadline active inactive closed)))))
13930 (?d (call-interactively 'org-check-deadlines))
13931 (?b (call-interactively 'org-check-before-date))
13932 (?a (call-interactively 'org-check-after-date))
13933 (?D (call-interactively 'org-check-dates-range))
13934 (?t (call-interactively 'org-show-todo-tree))
13935 (?T (org-show-todo-tree '(4)))
13936 (?m (call-interactively 'org-match-sparse-tree))
13937 ((?p ?P)
13938 (let* ((kwd (completing-read
13939 "Property: " (mapcar #'list (org-buffer-property-keys))))
13940 (value (completing-read
13941 "Value: " (mapcar #'list (org-property-values kwd)))))
13942 (unless (string-match "\\`{.*}\\'" value)
13943 (setq value (concat "\"" value "\"")))
13944 (org-match-sparse-tree arg (concat kwd "=" value))))
13945 ((?r ?R ?/) (call-interactively 'org-occur))
13946 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13948 (defvar-local org-occur-highlights nil
13949 "List of overlays used for occur matches.")
13950 (defvar-local org-occur-parameters nil
13951 "Parameters of the active org-occur calls.
13952 This is a list, each call to org-occur pushes as cons cell,
13953 containing the regular expression and the callback, onto the list.
13954 The list can contain several entries if `org-occur' has been called
13955 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13956 will only contain one set of parameters. When the highlights are
13957 removed (for example with `C-c C-c', or with the next edit (depending
13958 on `org-remove-highlights-with-change'), this variable is emptied
13959 as well.")
13961 (defun org-occur (regexp &optional keep-previous callback)
13962 "Make a compact tree which shows all matches of REGEXP.
13964 The tree will show the lines where the regexp matches, and any other context
13965 defined in `org-show-context-detail', which see.
13967 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13968 done by a previous call to `org-occur' will be kept, to allow stacking of
13969 calls to this command.
13971 Optional argument CALLBACK can be a function of no argument. In this case,
13972 it is called with point at the end of the match, match data being set
13973 accordingly. Current match is shown only if the return value is non-nil.
13974 The function must neither move point nor alter narrowing."
13975 (interactive "sRegexp: \nP")
13976 (when (equal regexp "")
13977 (user-error "Regexp cannot be empty"))
13978 (unless keep-previous
13979 (org-remove-occur-highlights nil nil t))
13980 (push (cons regexp callback) org-occur-parameters)
13981 (let ((cnt 0))
13982 (save-excursion
13983 (goto-char (point-min))
13984 (when (or (not keep-previous) ; do not want to keep
13985 (not org-occur-highlights)) ; no previous matches
13986 ;; hide everything
13987 (org-overview))
13988 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13989 (isearch-no-upper-case-p regexp t)
13990 org-occur-case-fold-search)))
13991 (while (re-search-forward regexp nil t)
13992 (when (or (not callback)
13993 (save-match-data (funcall callback)))
13994 (setq cnt (1+ cnt))
13995 (when org-highlight-sparse-tree-matches
13996 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13997 (org-show-context 'occur-tree)))))
13998 (when org-remove-highlights-with-change
13999 (add-hook 'before-change-functions 'org-remove-occur-highlights
14000 nil 'local))
14001 (unless org-sparse-tree-open-archived-trees
14002 (org-hide-archived-subtrees (point-min) (point-max)))
14003 (run-hooks 'org-occur-hook)
14004 (when (called-interactively-p 'interactive)
14005 (message "%d match(es) for regexp %s" cnt regexp))
14006 cnt))
14008 (defun org-occur-next-match (&optional n _reset)
14009 "Function for `next-error-function' to find sparse tree matches.
14010 N is the number of matches to move, when negative move backwards.
14011 This function always goes back to the starting point when no
14012 match is found."
14013 (let* ((limit (if (< n 0) (point-min) (point-max)))
14014 (search-func (if (< n 0)
14015 'previous-single-char-property-change
14016 'next-single-char-property-change))
14017 (n (abs n))
14018 (pos (point))
14020 (catch 'exit
14021 (while (setq p1 (funcall search-func (point) 'org-type))
14022 (when (equal p1 limit)
14023 (goto-char pos)
14024 (user-error "No more matches"))
14025 (when (equal (get-char-property p1 'org-type) 'org-occur)
14026 (setq n (1- n))
14027 (when (= n 0)
14028 (goto-char p1)
14029 (throw 'exit (point))))
14030 (goto-char p1))
14031 (goto-char p1)
14032 (user-error "No more matches"))))
14034 (defun org-show-context (&optional key)
14035 "Make sure point and context are visible.
14036 Optional argument KEY, when non-nil, is a symbol. See
14037 `org-show-context-detail' for allowed values and how much is to
14038 be shown."
14039 (org-show-set-visibility
14040 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14041 ((cdr (assq key org-show-context-detail)))
14042 (t (cdr (assq 'default org-show-context-detail))))))
14044 (defun org-show-set-visibility (detail)
14045 "Set visibility around point according to DETAIL.
14046 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14047 `tree', `canonical' or t. See `org-show-context-detail' for more
14048 information."
14049 ;; Show current heading and possibly its entry, following headline
14050 ;; or all children.
14051 (if (and (org-at-heading-p) (not (eq detail 'local)))
14052 (org-flag-heading nil)
14053 (org-show-entry)
14054 ;; If point is hidden within a drawer or a block, make sure to
14055 ;; expose it.
14056 (dolist (o (overlays-at (point)))
14057 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14058 (delete-overlay o)))
14059 (unless (org-before-first-heading-p)
14060 (org-with-limited-levels
14061 (cl-case detail
14062 ((tree canonical t) (org-show-children))
14063 ((nil minimal ancestors))
14064 (t (save-excursion
14065 (outline-next-heading)
14066 (org-flag-heading nil)))))))
14067 ;; Show all siblings.
14068 (when (eq detail 'lineage) (org-show-siblings))
14069 ;; Show ancestors, possibly with their children.
14070 (when (memq detail '(ancestors lineage tree canonical t))
14071 (save-excursion
14072 (while (org-up-heading-safe)
14073 (org-flag-heading nil)
14074 (when (memq detail '(canonical t)) (org-show-entry))
14075 (when (memq detail '(tree canonical t)) (org-show-children))))))
14077 (defvar org-reveal-start-hook nil
14078 "Hook run before revealing a location.")
14080 (defun org-reveal (&optional siblings)
14081 "Show current entry, hierarchy above it, and the following headline.
14083 This can be used to show a consistent set of context around
14084 locations exposed with `org-show-context'.
14086 With optional argument SIBLINGS, on each level of the hierarchy all
14087 siblings are shown. This repairs the tree structure to what it would
14088 look like when opened with hierarchical calls to `org-cycle'.
14090 With double optional argument \\[universal-argument] \\[universal-argument], \
14091 go to the parent and show the
14092 entire tree."
14093 (interactive "P")
14094 (run-hooks 'org-reveal-start-hook)
14095 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14096 ((equal siblings '(16))
14097 (save-excursion
14098 (when (org-up-heading-safe)
14099 (org-show-subtree)
14100 (run-hook-with-args 'org-cycle-hook 'subtree))))
14101 (t (org-show-set-visibility 'lineage))))
14103 (defun org-highlight-new-match (beg end)
14104 "Highlight from BEG to END and mark the highlight is an occur headline."
14105 (let ((ov (make-overlay beg end)))
14106 (overlay-put ov 'face 'secondary-selection)
14107 (overlay-put ov 'org-type 'org-occur)
14108 (push ov org-occur-highlights)))
14110 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14111 "Remove the occur highlights from the buffer.
14112 BEG and END are ignored. If NOREMOVE is nil, remove this function
14113 from the `before-change-functions' in the current buffer."
14114 (interactive)
14115 (unless org-inhibit-highlight-removal
14116 (mapc #'delete-overlay org-occur-highlights)
14117 (setq org-occur-highlights nil)
14118 (setq org-occur-parameters nil)
14119 (unless noremove
14120 (remove-hook 'before-change-functions
14121 'org-remove-occur-highlights 'local))))
14123 ;;;; Priorities
14125 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14126 "Regular expression matching the priority indicator.")
14128 (defvar org-remove-priority-next-time nil)
14130 (defun org-priority-up ()
14131 "Increase the priority of the current item."
14132 (interactive)
14133 (org-priority 'up))
14135 (defun org-priority-down ()
14136 "Decrease the priority of the current item."
14137 (interactive)
14138 (org-priority 'down))
14140 (defun org-priority (&optional action _show)
14141 "Change the priority of an item.
14142 ACTION can be `set', `up', `down', or a character."
14143 (interactive "P")
14144 (if (equal action '(4))
14145 (org-show-priority)
14146 (unless org-enable-priority-commands
14147 (user-error "Priority commands are disabled"))
14148 (setq action (or action 'set))
14149 (let (current new news have remove)
14150 (save-excursion
14151 (org-back-to-heading t)
14152 (when (looking-at org-priority-regexp)
14153 (setq current (string-to-char (match-string 2))
14154 have t))
14155 (cond
14156 ((eq action 'remove)
14157 (setq remove t new ?\ ))
14158 ((or (eq action 'set)
14159 (integerp action))
14160 (if (not (eq action 'set))
14161 (setq new action)
14162 (message "Priority %c-%c, SPC to remove: "
14163 org-highest-priority org-lowest-priority)
14164 (save-match-data
14165 (setq new (read-char-exclusive))))
14166 (when (and (= (upcase org-highest-priority) org-highest-priority)
14167 (= (upcase org-lowest-priority) org-lowest-priority))
14168 (setq new (upcase new)))
14169 (cond ((equal new ?\ ) (setq remove t))
14170 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14171 (user-error "Priority must be between `%c' and `%c'"
14172 org-highest-priority org-lowest-priority))))
14173 ((eq action 'up)
14174 (setq new (if have
14175 (1- current) ; normal cycling
14176 ;; last priority was empty
14177 (if (eq last-command this-command)
14178 org-lowest-priority ; wrap around empty to lowest
14179 ;; default
14180 (if org-priority-start-cycle-with-default
14181 org-default-priority
14182 (1- org-default-priority))))))
14183 ((eq action 'down)
14184 (setq new (if have
14185 (1+ current) ; normal cycling
14186 ;; last priority was empty
14187 (if (eq last-command this-command)
14188 org-highest-priority ; wrap around empty to highest
14189 ;; default
14190 (if org-priority-start-cycle-with-default
14191 org-default-priority
14192 (1+ org-default-priority))))))
14193 (t (user-error "Invalid action")))
14194 (when (or (< (upcase new) org-highest-priority)
14195 (> (upcase new) org-lowest-priority))
14196 (if (and (memq action '(up down))
14197 (not have) (not (eq last-command this-command)))
14198 ;; `new' is from default priority
14199 (error
14200 "The default can not be set, see `org-default-priority' why")
14201 ;; normal cycling: `new' is beyond highest/lowest priority
14202 ;; and is wrapped around to the empty priority
14203 (setq remove t)))
14204 (setq news (format "%c" new))
14205 (if have
14206 (if remove
14207 (replace-match "" t t nil 1)
14208 (replace-match news t t nil 2))
14209 (if remove
14210 (user-error "No priority cookie found in line")
14211 (let ((case-fold-search nil))
14212 (looking-at org-todo-line-regexp))
14213 (if (match-end 2)
14214 (progn
14215 (goto-char (match-end 2))
14216 (insert " [#" news "]"))
14217 (goto-char (match-beginning 3))
14218 (insert "[#" news "] "))))
14219 (org-set-tags nil 'align))
14220 (if remove
14221 (message "Priority removed")
14222 (message "Priority of current item set to %s" news)))))
14224 (defun org-show-priority ()
14225 "Show the priority of the current item.
14226 This priority is composed of the main priority given with the [#A] cookies,
14227 and by additional input from the age of a schedules or deadline entry."
14228 (interactive)
14229 (let ((pri (if (eq major-mode 'org-agenda-mode)
14230 (org-get-at-bol 'priority)
14231 (save-excursion
14232 (save-match-data
14233 (beginning-of-line)
14234 (and (looking-at org-heading-regexp)
14235 (org-get-priority (match-string 0))))))))
14236 (message "Priority is %d" (if pri pri -1000))))
14238 (defun org-get-priority (s)
14239 "Find priority cookie and return priority."
14240 (save-match-data
14241 (if (functionp org-get-priority-function)
14242 (funcall org-get-priority-function)
14243 (if (not (string-match org-priority-regexp s))
14244 (* 1000 (- org-lowest-priority org-default-priority))
14245 (* 1000 (- org-lowest-priority
14246 (string-to-char (match-string 2 s))))))))
14248 ;;;; Tags
14250 (defvar org-agenda-archives-mode)
14251 (defvar org-map-continue-from nil
14252 "Position from where mapping should continue.
14253 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14255 (defvar org-scanner-tags nil
14256 "The current tag list while the tags scanner is running.")
14258 (defvar org-trust-scanner-tags nil
14259 "Should `org-get-tags-at' use the tags for the scanner.
14260 This is for internal dynamical scoping only.
14261 When this is non-nil, the function `org-get-tags-at' will return the value
14262 of `org-scanner-tags' instead of building the list by itself. This
14263 can lead to large speed-ups when the tags scanner is used in a file with
14264 many entries, and when the list of tags is retrieved, for example to
14265 obtain a list of properties. Building the tags list for each entry in such
14266 a file becomes an N^2 operation - but with this variable set, it scales
14267 as N.")
14269 (defvar org--matcher-tags-todo-only nil)
14271 (defun org-scan-tags (action matcher todo-only &optional start-level)
14272 "Scan headline tags with inheritance and produce output ACTION.
14274 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14275 or `agenda' to produce an entry list for an agenda view. It can also be
14276 a Lisp form or a function that should be called at each matched headline, in
14277 this case the return value is a list of all return values from these calls.
14279 MATCHER is a function accepting three arguments, returning
14280 a non-nil value whenever a given set of tags qualifies a headline
14281 for inclusion. See `org-make-tags-matcher' for more information.
14282 As a special case, it can also be set to t (respectively nil) in
14283 order to match all (respectively none) headline.
14285 When TODO-ONLY is non-nil, only lines with a not-done TODO
14286 keyword are included in the output.
14288 START-LEVEL can be a string with asterisks, reducing the scope to
14289 headlines matching this string."
14290 (require 'org-agenda)
14291 (let* ((re (concat "^"
14292 (if start-level
14293 ;; Get the correct level to match
14294 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14295 org-outline-regexp)
14296 " *\\(\\<\\("
14297 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14298 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14299 (props (list 'face 'default
14300 'done-face 'org-agenda-done
14301 'undone-face 'default
14302 'mouse-face 'highlight
14303 'org-not-done-regexp org-not-done-regexp
14304 'org-todo-regexp org-todo-regexp
14305 'org-complex-heading-regexp org-complex-heading-regexp
14306 'help-echo
14307 (format "mouse-2 or RET jump to org file %s"
14308 (abbreviate-file-name
14309 (or (buffer-file-name (buffer-base-buffer))
14310 (buffer-name (buffer-base-buffer)))))))
14311 (org-map-continue-from nil)
14312 lspos tags tags-list
14313 (tags-alist (list (cons 0 org-file-tags)))
14314 (llast 0) rtn rtn1 level category i txt
14315 todo marker entry priority
14316 ts-date ts-date-type ts-date-pair)
14317 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14318 (setq action (list 'lambda nil action)))
14319 (save-excursion
14320 (goto-char (point-min))
14321 (when (eq action 'sparse-tree)
14322 (org-overview)
14323 (org-remove-occur-highlights))
14324 (while (let (case-fold-search)
14325 (re-search-forward re nil t))
14326 (setq org-map-continue-from nil)
14327 (catch :skip
14328 (setq todo
14329 ;; TODO: is the 1-2 difference a bug?
14330 (when (match-end 1) (match-string-no-properties 2))
14331 tags (when (match-end 4) (match-string-no-properties 4)))
14332 (goto-char (setq lspos (match-beginning 0)))
14333 (setq level (org-reduced-level (org-outline-level))
14334 category (org-get-category))
14335 (when (eq action 'agenda)
14336 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14337 ts-date (car ts-date-pair)
14338 ts-date-type (cdr ts-date-pair)))
14339 (setq i llast llast level)
14340 ;; remove tag lists from same and sublevels
14341 (while (>= i level)
14342 (when (setq entry (assoc i tags-alist))
14343 (setq tags-alist (delete entry tags-alist)))
14344 (setq i (1- i)))
14345 ;; add the next tags
14346 (when tags
14347 (setq tags (org-split-string tags ":")
14348 tags-alist
14349 (cons (cons level tags) tags-alist)))
14350 ;; compile tags for current headline
14351 (setq tags-list
14352 (if org-use-tag-inheritance
14353 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14354 tags)
14355 org-scanner-tags tags-list)
14356 (when org-use-tag-inheritance
14357 (setcdr (car tags-alist)
14358 (mapcar (lambda (x)
14359 (setq x (copy-sequence x))
14360 (org-add-prop-inherited x))
14361 (cdar tags-alist))))
14362 (when (and tags org-use-tag-inheritance
14363 (or (not (eq t org-use-tag-inheritance))
14364 org-tags-exclude-from-inheritance))
14365 ;; Selective inheritance, remove uninherited ones.
14366 (setcdr (car tags-alist)
14367 (org-remove-uninherited-tags (cdar tags-alist))))
14368 (when (and
14370 ;; eval matcher only when the todo condition is OK
14371 (and (or (not todo-only) (member todo org-not-done-keywords))
14372 (if (functionp matcher)
14373 (let ((case-fold-search t) (org-trust-scanner-tags t))
14374 (funcall matcher todo tags-list level))
14375 matcher))
14377 ;; Call the skipper, but return t if it does not
14378 ;; skip, so that the `and' form continues evaluating.
14379 (progn
14380 (unless (eq action 'sparse-tree) (org-agenda-skip))
14383 ;; Check if timestamps are deselecting this entry
14384 (or (not todo-only)
14385 (and (member todo org-not-done-keywords)
14386 (or (not org-agenda-tags-todo-honor-ignore-options)
14387 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14389 ;; select this headline
14390 (cond
14391 ((eq action 'sparse-tree)
14392 (and org-highlight-sparse-tree-matches
14393 (org-get-heading) (match-end 0)
14394 (org-highlight-new-match
14395 (match-beginning 1) (match-end 1)))
14396 (org-show-context 'tags-tree))
14397 ((eq action 'agenda)
14398 (setq txt (org-agenda-format-item
14400 (concat
14401 (if (eq org-tags-match-list-sublevels 'indented)
14402 (make-string (1- level) ?.) "")
14403 (org-get-heading))
14404 (make-string level ?\s)
14405 category
14406 tags-list)
14407 priority (org-get-priority txt))
14408 (goto-char lspos)
14409 (setq marker (org-agenda-new-marker))
14410 (org-add-props txt props
14411 'org-marker marker 'org-hd-marker marker 'org-category category
14412 'todo-state todo
14413 'ts-date ts-date
14414 'priority priority
14415 'type (concat "tagsmatch" ts-date-type))
14416 (push txt rtn))
14417 ((functionp action)
14418 (setq org-map-continue-from nil)
14419 (save-excursion
14420 (setq rtn1 (funcall action))
14421 (push rtn1 rtn)))
14422 (t (user-error "Invalid action")))
14424 ;; if we are to skip sublevels, jump to end of subtree
14425 (unless org-tags-match-list-sublevels
14426 (org-end-of-subtree t)
14427 (backward-char 1))))
14428 ;; Get the correct position from where to continue
14429 (if org-map-continue-from
14430 (goto-char org-map-continue-from)
14431 (and (= (point) lspos) (end-of-line 1)))))
14432 (when (and (eq action 'sparse-tree)
14433 (not org-sparse-tree-open-archived-trees))
14434 (org-hide-archived-subtrees (point-min) (point-max)))
14435 (nreverse rtn)))
14437 (defun org-remove-uninherited-tags (tags)
14438 "Remove all tags that are not inherited from the list TAGS."
14439 (cond
14440 ((eq org-use-tag-inheritance t)
14441 (if org-tags-exclude-from-inheritance
14442 (org-delete-all org-tags-exclude-from-inheritance tags)
14443 tags))
14444 ((not org-use-tag-inheritance) nil)
14445 ((stringp org-use-tag-inheritance)
14446 (delq nil (mapcar
14447 (lambda (x)
14448 (if (and (string-match org-use-tag-inheritance x)
14449 (not (member x org-tags-exclude-from-inheritance)))
14450 x nil))
14451 tags)))
14452 ((listp org-use-tag-inheritance)
14453 (delq nil (mapcar
14454 (lambda (x)
14455 (if (member x org-use-tag-inheritance) x nil))
14456 tags)))))
14458 (defun org-match-sparse-tree (&optional todo-only match)
14459 "Create a sparse tree according to tags string MATCH.
14460 MATCH can contain positive and negative selection of tags, like
14461 \"+WORK+URGENT-WITHBOSS\".
14462 If optional argument TODO-ONLY is non-nil, only select lines that are
14463 also TODO lines."
14464 (interactive "P")
14465 (org-agenda-prepare-buffers (list (current-buffer)))
14466 (let ((org--matcher-tags-todo-only todo-only))
14467 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14468 org--matcher-tags-todo-only)))
14470 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14472 (defvar org-cached-props nil)
14473 (defun org-cached-entry-get (pom property)
14474 (if (or (eq t org-use-property-inheritance)
14475 (and (stringp org-use-property-inheritance)
14476 (let ((case-fold-search t))
14477 (string-match-p org-use-property-inheritance property)))
14478 (and (listp org-use-property-inheritance)
14479 (member-ignore-case property org-use-property-inheritance)))
14480 ;; Caching is not possible, check it directly.
14481 (org-entry-get pom property 'inherit)
14482 ;; Get all properties, so we can do complicated checks easily.
14483 (cdr (assoc-string property
14484 (or org-cached-props
14485 (setq org-cached-props (org-entry-properties pom)))
14486 t))))
14488 (defun org-global-tags-completion-table (&optional files)
14489 "Return the list of all tags in all agenda buffer/files.
14490 Optional FILES argument is a list of files which can be used
14491 instead of the agenda files."
14492 (save-excursion
14493 (org-uniquify
14494 (delq nil
14495 (apply #'append
14496 (mapcar
14497 (lambda (file)
14498 (set-buffer (find-file-noselect file))
14499 (mapcar (lambda (x)
14500 (and (stringp (car-safe x))
14501 (list (car-safe x))))
14502 (or org-current-tag-alist (org-get-buffer-tags))))
14503 (if (car-safe files) files
14504 (org-agenda-files))))))))
14506 (defun org-make-tags-matcher (match)
14507 "Create the TAGS/TODO matcher form for the selection string MATCH.
14509 Returns a cons of the selection string MATCH and a function
14510 implementing the matcher.
14512 The matcher is to be called at an Org entry, with point on the
14513 headline, and returns non-nil if the entry matches the selection
14514 string MATCH. It must be called with three arguments: the TODO
14515 keyword at the entry (or nil if none), the list of all tags at
14516 the entry including inherited ones and the reduced level of the
14517 headline. Additionally, the category of the entry, if any, must
14518 be specified as the text property `org-category' on the headline.
14520 This function sets the variable `org--matcher-tags-todo-only' to
14521 a non-nil value if the matcher restricts matching to TODO
14522 entries, otherwise it is not touched.
14524 See also `org-scan-tags'."
14525 (unless match
14526 ;; Get a new match request, with completion against the global
14527 ;; tags table and the local tags in current buffer.
14528 (let ((org-last-tags-completion-table
14529 (org-uniquify
14530 (delq nil (append (org-get-buffer-tags)
14531 (org-global-tags-completion-table))))))
14532 (setq match
14533 (completing-read
14534 "Match: "
14535 'org-tags-completion-function nil nil nil 'org-tags-history))))
14537 (let ((match0 match)
14538 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14539 (start 0)
14540 tagsmatch todomatch tagsmatcher todomatcher)
14542 ;; Expand group tags.
14543 (setq match (org-tags-expand match))
14545 ;; Check if there is a TODO part of this match, which would be the
14546 ;; part after a "/". To make sure that this slash is not part of
14547 ;; a property value to be matched against, we also check that
14548 ;; there is no / after that slash. First, find the last slash.
14549 (let ((s 0))
14550 (while (string-match "/+" match s)
14551 (setq start (match-beginning 0))
14552 (setq s (match-end 0))))
14553 (if (and (string-match "/+" match start)
14554 (not (string-match-p "\"" match start)))
14555 ;; Match contains also a TODO-matching request.
14556 (progn
14557 (setq tagsmatch (substring match 0 (match-beginning 0)))
14558 (setq todomatch (substring match (match-end 0)))
14559 (when (string-prefix-p "!" todomatch)
14560 (setq org--matcher-tags-todo-only t)
14561 (setq todomatch (substring todomatch 1)))
14562 (when (string-match "\\`\\s-*\\'" todomatch)
14563 (setq todomatch nil)))
14564 ;; Only matching tags.
14565 (setq tagsmatch match)
14566 (setq todomatch nil))
14568 ;; Make the tags matcher.
14569 (when (org-string-nw-p tagsmatch)
14570 (let ((orlist nil)
14571 (orterms (org-split-string tagsmatch "|"))
14572 term)
14573 (while (setq term (pop orterms))
14574 (while (and (equal (substring term -1) "\\") orterms)
14575 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14576 (while (string-match re term)
14577 (let* ((rest (substring term (match-end 0)))
14578 (minus (and (match-end 1)
14579 (equal (match-string 1 term) "-")))
14580 (tag (save-match-data
14581 (replace-regexp-in-string
14582 "\\\\-" "-" (match-string 2 term))))
14583 (regexp (eq (string-to-char tag) ?{))
14584 (levelp (match-end 4))
14585 (propp (match-end 5))
14587 (cond
14588 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14589 (levelp
14590 `(,(org-op-to-function (match-string 3 term))
14591 level
14592 ,(string-to-number (match-string 4 term))))
14593 (propp
14594 (let* ((gv (pcase (upcase (match-string 5 term))
14595 ("CATEGORY"
14596 '(get-text-property (point) 'org-category))
14597 ("TODO" 'todo)
14598 (p `(org-cached-entry-get nil ,p))))
14599 (pv (match-string 7 term))
14600 (regexp (eq (string-to-char pv) ?{))
14601 (strp (eq (string-to-char pv) ?\"))
14602 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14603 (po (org-op-to-function (match-string 6 term)
14604 (if timep 'time strp))))
14605 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14606 (when timep (setq pv (org-matcher-time pv)))
14607 (cond ((and regexp (eq po 'org<>))
14608 `(not (string-match ,pv (or ,gv ""))))
14609 (regexp `(string-match ,pv (or ,gv "")))
14610 (strp `(,po (or ,gv "") ,pv))
14612 `(,po
14613 (string-to-number (or ,gv ""))
14614 ,(string-to-number pv))))))
14615 (t `(member ,tag tags-list)))))
14616 (push (if minus `(not ,mm) mm) tagsmatcher)
14617 (setq term rest)))
14618 (push `(and ,@tagsmatcher) orlist)
14619 (setq tagsmatcher nil))
14620 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14622 ;; Make the TODO matcher.
14623 (when (org-string-nw-p todomatch)
14624 (let ((orlist nil))
14625 (dolist (term (org-split-string todomatch "|"))
14626 (while (string-match re term)
14627 (let* ((minus (and (match-end 1)
14628 (equal (match-string 1 term) "-")))
14629 (kwd (match-string 2 term))
14630 (regexp (eq (string-to-char kwd) ?{))
14631 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14632 `(equal todo ,kwd))))
14633 (push (if minus `(not ,mm) mm) todomatcher))
14634 (setq term (substring term (match-end 0))))
14635 (push (if (> (length todomatcher) 1)
14636 (cons 'and todomatcher)
14637 (car todomatcher))
14638 orlist)
14639 (setq todomatcher nil))
14640 (setq todomatcher (cons 'or orlist))))
14642 ;; Return the string and function of the matcher. If no
14643 ;; tags-specific or todo-specific matcher exists, match
14644 ;; everything.
14645 (let ((matcher (if (and tagsmatcher todomatcher)
14646 `(and ,tagsmatcher ,todomatcher)
14647 (or tagsmatcher todomatcher t))))
14648 (when org--matcher-tags-todo-only
14649 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14650 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14652 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14653 "Expand group tags in MATCH.
14655 This replaces every group tag in MATCH with a regexp tag search.
14656 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14657 will be replaced like this:
14659 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14660 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14661 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14663 Replacing by a regexp preserves the structure of the match.
14664 E.g., this expansion
14666 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14668 will match anything tagged with \"Lab\" and \"Home\", or tagged
14669 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14671 A group tag in MATCH can contain regular expressions of its own.
14672 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14673 will be replaced like this:
14675 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14677 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14678 assumed to be a single group tag, and the function will return
14679 the list of tags in this group.
14681 When DOWNCASE is non-nil, expand downcased TAGS."
14682 (if org-group-tags
14683 (let* ((case-fold-search t)
14684 (stable org-mode-syntax-table)
14685 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14686 (taggroups (if downcased
14687 (mapcar (lambda (tg) (mapcar #'downcase tg))
14688 taggroups)
14689 taggroups))
14690 (taggroups-keys (mapcar #'car taggroups))
14691 (return-match (if downcased (downcase match) match))
14692 (count 0)
14693 (work-already-expanded tags-already-expanded)
14694 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14695 ;; @ and _ are allowed as word-components in tags.
14696 (modify-syntax-entry ?@ "w" stable)
14697 (modify-syntax-entry ?_ "w" stable)
14698 ;; Temporarily replace regexp-expressions in the match-expression.
14699 (while (string-match "{.+?}" return-match)
14700 (cl-incf count)
14701 (push (match-string 0 return-match) regexps-in-match)
14702 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14703 (while (and taggroups-keys
14704 (with-syntax-table stable
14705 (string-match
14706 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14707 (regexp-opt taggroups-keys) "\\>\\)")
14708 return-match)))
14709 (let* ((dir (match-string 1 return-match))
14710 (tag (match-string 2 return-match))
14711 (tag (if downcased (downcase tag) tag)))
14712 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14713 (member tag work-already-expanded))
14714 (setq tags-in-group (assoc tag taggroups))
14715 (push tag work-already-expanded)
14716 ;; Recursively expand each tag in the group, if the tag hasn't
14717 ;; already been expanded. Restore the match-data after all recursive calls.
14718 (save-match-data
14719 (let (tags-expanded)
14720 (dolist (x (cdr tags-in-group))
14721 (if (and (member x taggroups-keys)
14722 (not (member x work-already-expanded)))
14723 (setq tags-expanded
14724 (delete-dups
14725 (append
14726 (org-tags-expand x t downcased
14727 work-already-expanded)
14728 tags-expanded)))
14729 (setq tags-expanded
14730 (append (list x) tags-expanded)))
14731 (setq work-already-expanded
14732 (delete-dups
14733 (append tags-expanded
14734 work-already-expanded))))
14735 (setq tags-in-group
14736 (delete-dups (cons (car tags-in-group)
14737 tags-expanded)))))
14738 ;; Filter tag-regexps from tags.
14739 (setq regexp-in-group-escaped
14740 (delq nil (mapcar (lambda (x)
14741 (if (stringp x)
14742 (and (equal "{" (substring x 0 1))
14743 (equal "}" (substring x -1))
14746 tags-in-group))
14747 regexp-in-group
14748 (mapcar (lambda (x)
14749 (substring x 1 -1))
14750 regexp-in-group-escaped)
14751 tags-in-group
14752 (delq nil (mapcar (lambda (x)
14753 (if (stringp x)
14754 (and (not (equal "{" (substring x 0 1)))
14755 (not (equal "}" (substring x -1)))
14758 tags-in-group)))
14759 ;; If single-as-list, do no more in the while-loop.
14760 (if (not single-as-list)
14761 (progn
14762 (when regexp-in-group
14763 (setq regexp-in-group
14764 (concat "\\|"
14765 (mapconcat 'identity regexp-in-group
14766 "\\|"))))
14767 (setq tags-in-group
14768 (concat dir
14769 "{\\<"
14770 (regexp-opt tags-in-group)
14771 "\\>"
14772 regexp-in-group
14773 "}"))
14774 (when (stringp tags-in-group)
14775 (org-add-props tags-in-group '(grouptag t)))
14776 (setq return-match
14777 (replace-match tags-in-group t t return-match)))
14778 (setq tags-in-group
14779 (append regexp-in-group-escaped tags-in-group))))
14780 (setq taggroups-keys (delete tag taggroups-keys))))
14781 ;; Add the regular expressions back into the match-expression again.
14782 (while regexps-in-match
14783 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14784 (pop regexps-in-match)
14785 return-match t t))
14786 (cl-decf count))
14787 (if single-as-list
14788 (if tags-in-group tags-in-group (list return-match))
14789 return-match))
14790 (if single-as-list
14791 (list (if downcased (downcase match) match))
14792 match)))
14794 (defun org-op-to-function (op &optional stringp)
14795 "Turn an operator into the appropriate function."
14796 (setq op
14797 (cond
14798 ((equal op "<" ) '(< string< org-time<))
14799 ((equal op ">" ) '(> org-string> org-time>))
14800 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14801 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14802 ((member op '("=" "==")) '(= string= org-time=))
14803 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14804 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14806 (defun org<> (a b) (not (= a b)))
14807 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14808 (defun org-string>= (a b) (not (string< a b)))
14809 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14810 (defun org-string<> (a b) (not (string= a b)))
14811 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14812 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14813 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14814 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14815 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14816 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14817 (defun org-2ft (s)
14818 "Convert S to a floating point time.
14819 If S is already a number, just return it. If it is a string, parse
14820 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14821 (cond
14822 ((numberp s) s)
14823 ((stringp s)
14824 (condition-case nil
14825 (float-time (apply 'encode-time (org-parse-time-string s)))
14826 (error 0.)))
14827 (t 0.)))
14829 (defun org-time-today ()
14830 "Time in seconds today at 0:00.
14831 Returns the float number of seconds since the beginning of the
14832 epoch to the beginning of today (00:00)."
14833 (float-time (apply 'encode-time
14834 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14836 (defun org-matcher-time (s)
14837 "Interpret a time comparison value."
14838 (save-match-data
14839 (cond
14840 ((string= s "<now>") (float-time))
14841 ((string= s "<today>") (org-time-today))
14842 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14843 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14844 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14845 (+ (org-time-today)
14846 (* (string-to-number (match-string 1 s))
14847 (cdr (assoc (match-string 2 s)
14848 '(("d" . 86400.0) ("w" . 604800.0)
14849 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14850 (t (org-2ft s)))))
14852 (defun org-match-any-p (re list)
14853 "Does re match any element of list?"
14854 (setq list (mapcar (lambda (x) (string-match re x)) list))
14855 (delq nil list))
14857 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14858 (defvar org-tags-overlay (make-overlay 1 1))
14859 (delete-overlay org-tags-overlay)
14861 (defun org-get-local-tags-at (&optional pos)
14862 "Get a list of tags defined in the current headline."
14863 (org-get-tags-at pos 'local))
14865 (defun org-get-local-tags ()
14866 "Get a list of tags defined in the current headline."
14867 (org-get-tags-at nil 'local))
14869 (defun org-get-tags-at (&optional pos local)
14870 "Get a list of all headline tags applicable at POS.
14871 POS defaults to point. If tags are inherited, the list contains
14872 the targets in the same sequence as the headlines appear, i.e.
14873 the tags of the current headline come last.
14874 When LOCAL is non-nil, only return tags from the current headline,
14875 ignore inherited ones."
14876 (interactive)
14877 (if (and org-trust-scanner-tags
14878 (or (not pos) (equal pos (point)))
14879 (not local))
14880 org-scanner-tags
14881 (let (tags ltags lastpos parent)
14882 (save-excursion
14883 (save-restriction
14884 (widen)
14885 (goto-char (or pos (point)))
14886 (save-match-data
14887 (catch 'done
14888 (condition-case nil
14889 (progn
14890 (org-back-to-heading t)
14891 (while (not (equal lastpos (point)))
14892 (setq lastpos (point))
14893 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14894 (setq ltags (org-split-string
14895 (match-string-no-properties 1) ":"))
14896 (when parent
14897 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14898 (setq tags (append
14899 (if parent
14900 (org-remove-uninherited-tags ltags)
14901 ltags)
14902 tags)))
14903 (or org-use-tag-inheritance (throw 'done t))
14904 (when local (throw 'done t))
14905 (or (org-up-heading-safe) (error nil))
14906 (setq parent t)))
14907 (error nil)))))
14908 (if local
14909 tags
14910 (reverse (delete-dups
14911 (reverse (append
14912 (org-remove-uninherited-tags
14913 org-file-tags)
14914 tags)))))))))
14916 (defun org-add-prop-inherited (s)
14917 (add-text-properties 0 (length s) '(inherited t) s)
14920 (defun org-toggle-tag (tag &optional onoff)
14921 "Toggle the tag TAG for the current line.
14922 If ONOFF is `on' or `off', don't toggle but set to this state."
14923 (let (res current)
14924 (save-excursion
14925 (org-back-to-heading t)
14926 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14927 (point-at-eol) t)
14928 (progn
14929 (setq current (match-string 1))
14930 (replace-match ""))
14931 (setq current ""))
14932 (setq current (nreverse (org-split-string current ":")))
14933 (cond
14934 ((eq onoff 'on)
14935 (setq res t)
14936 (or (member tag current) (push tag current)))
14937 ((eq onoff 'off)
14938 (or (not (member tag current)) (setq current (delete tag current))))
14939 (t (if (member tag current)
14940 (setq current (delete tag current))
14941 (setq res t)
14942 (push tag current))))
14943 (end-of-line 1)
14944 (if current
14945 (progn
14946 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14947 (org-set-tags nil t))
14948 (delete-horizontal-space))
14949 (run-hooks 'org-after-tags-change-hook))
14950 res))
14952 (defun org--align-tags-here (to-col)
14953 "Align tags on the current headline to TO-COL.
14954 Assume point is on a headline."
14955 (let ((pos (point)))
14956 (beginning-of-line)
14957 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14958 (>= pos (match-beginning 2)))
14959 ;; No tags or point within tags: do not align.
14960 (goto-char pos)
14961 (goto-char (match-beginning 1))
14962 (let ((shift (max (- (if (>= to-col 0) to-col
14963 (- (abs to-col) (string-width (match-string 2))))
14964 (current-column))
14965 1)))
14966 (replace-match (make-string shift ?\s) nil nil nil 1)
14967 ;; Preserve initial position, if possible. In any case, stop
14968 ;; before tags.
14969 (when (< pos (point)) (goto-char pos))))))
14971 (defun org-set-tags-command (&optional arg just-align)
14972 "Call the set-tags command for the current entry."
14973 (interactive "P")
14974 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14975 (org-set-tags arg just-align)
14976 (save-excursion
14977 (unless (and (org-region-active-p)
14978 org-loop-over-headlines-in-active-region)
14979 (org-back-to-heading t))
14980 (org-set-tags arg just-align))))
14982 (defun org-set-tags-to (data)
14983 "Set the tags of the current entry to DATA, replacing the current tags.
14984 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14985 If DATA is nil or the empty string, any tags will be removed."
14986 (interactive "sTags: ")
14987 (setq data
14988 (cond
14989 ((eq data nil) "")
14990 ((equal data "") "")
14991 ((stringp data)
14992 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14993 ":"))
14994 ((listp data)
14995 (concat ":" (mapconcat 'identity data ":") ":"))))
14996 (when data
14997 (save-excursion
14998 (org-back-to-heading t)
14999 (when (looking-at org-complex-heading-regexp)
15000 (if (match-end 5)
15001 (progn
15002 (goto-char (match-beginning 5))
15003 (insert data)
15004 (delete-region (point) (point-at-eol))
15005 (org-set-tags nil 'align))
15006 (goto-char (point-at-eol))
15007 (insert " " data)
15008 (org-set-tags nil 'align)))
15009 (beginning-of-line 1)
15010 (when (looking-at ".*?\\([ \t]+\\)$")
15011 (delete-region (match-beginning 1) (match-end 1))))))
15013 (defun org-align-all-tags ()
15014 "Align the tags in all headings."
15015 (interactive)
15016 (save-excursion
15017 (or (ignore-errors (org-back-to-heading t))
15018 (outline-next-heading))
15019 (if (org-at-heading-p)
15020 (org-set-tags t)
15021 (message "No headings"))))
15023 (defvar org-indent-indentation-per-level)
15024 (defun org-set-tags (&optional arg just-align)
15025 "Set the tags for the current headline.
15026 With prefix ARG, realign all tags in headings in the current buffer.
15027 When JUST-ALIGN is non-nil, only align tags."
15028 (interactive "P")
15029 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15030 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15031 'region-start-level
15032 'region))
15033 org-loop-over-headlines-in-active-region)
15034 (org-map-entries
15035 ;; We don't use ARG and JUST-ALIGN here because these args
15036 ;; are not useful when looping over headlines.
15037 #'org-set-tags
15038 org-loop-over-headlines-in-active-region
15040 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15041 (let ((org-setting-tags t))
15042 (if arg
15043 (save-excursion
15044 (goto-char (point-min))
15045 (while (re-search-forward org-outline-regexp-bol nil t)
15046 (org-set-tags nil t)
15047 (end-of-line))
15048 (message "All tags realigned to column %d" org-tags-column))
15049 (let* ((current (org-get-tags-string))
15050 (tags
15051 (if just-align current
15052 ;; Get a new set of tags from the user.
15053 (save-excursion
15054 (let* ((seen)
15055 (table
15056 (setq
15057 org-last-tags-completion-table
15058 ;; Uniquify tags in alists, yet preserve
15059 ;; structure (i.e., keywords).
15060 (delq nil
15061 (mapcar
15062 (lambda (pair)
15063 (let ((head (car pair)))
15064 (cond ((symbolp head) pair)
15065 ((member head seen) nil)
15066 (t (push head seen)
15067 pair))))
15068 (append
15069 (or org-current-tag-alist
15070 (org-get-buffer-tags))
15071 (and
15072 org-complete-tags-always-offer-all-agenda-tags
15073 (org-global-tags-completion-table
15074 (org-agenda-files))))))))
15075 (current-tags (org-split-string current ":"))
15076 (inherited-tags
15077 (nreverse (nthcdr (length current-tags)
15078 (nreverse (org-get-tags-at))))))
15079 (replace-regexp-in-string
15080 "\\([-+&]+\\|,\\)"
15082 (if (or (eq t org-use-fast-tag-selection)
15083 (and org-use-fast-tag-selection
15084 (delq nil (mapcar #'cdr table))))
15085 (org-fast-tag-selection
15086 current-tags inherited-tags table
15087 (and org-fast-tag-selection-include-todo
15088 org-todo-key-alist))
15089 (let ((org-add-colon-after-tag-completion
15090 (< 1 (length table))))
15091 (org-trim
15092 (completing-read
15093 "Tags: "
15094 #'org-tags-completion-function
15095 nil nil current 'org-tags-history))))))))))
15097 (when org-tags-sort-function
15098 (setq tags
15099 (mapconcat
15100 #'identity
15101 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15102 org-tags-sort-function)
15103 ":")))
15105 (if (not (org-string-nw-p tags)) (setq tags "")
15106 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15107 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15109 ;; Insert new tags at the correct column.
15110 (unless (equal current tags)
15111 (save-excursion
15112 (beginning-of-line)
15113 (looking-at org-complex-heading-regexp)
15114 ;; Remove current tags, if any.
15115 (when (match-end 5) (replace-match "" nil nil nil 5))
15116 ;; Insert new tags, if any. Otherwise, remove trailing
15117 ;; white spaces.
15118 (end-of-line)
15119 (if (not (equal tags ""))
15120 (insert " " tags)
15121 (skip-chars-backward " \t")
15122 (delete-region (point) (line-end-position)))))
15123 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15124 ;; is on.
15125 (unless (equal tags "")
15126 (let* ((level (save-excursion
15127 (beginning-of-line)
15128 (skip-chars-forward "\\*")))
15129 (offset (if (bound-and-true-p org-indent-mode)
15130 (* (1- org-indent-indentation-per-level)
15131 (1- level))
15133 (tags-column
15134 (+ org-tags-column
15135 (if (> org-tags-column 0) (- offset) offset))))
15136 (org--align-tags-here tags-column))))
15137 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15139 (defun org-change-tag-in-region (beg end tag off)
15140 "Add or remove TAG for each entry in the region.
15141 This works in the agenda, and also in an Org buffer."
15142 (interactive
15143 (list (region-beginning) (region-end)
15144 (let ((org-last-tags-completion-table
15145 (if (derived-mode-p 'org-mode)
15146 (org-uniquify
15147 (delq nil (append (org-get-buffer-tags)
15148 (org-global-tags-completion-table))))
15149 (org-global-tags-completion-table))))
15150 (completing-read
15151 "Tag: " 'org-tags-completion-function nil nil nil
15152 'org-tags-history))
15153 (progn
15154 (message "[s]et or [r]emove? ")
15155 (equal (read-char-exclusive) ?r))))
15156 (when (fboundp 'deactivate-mark) (deactivate-mark))
15157 (let ((agendap (equal major-mode 'org-agenda-mode))
15158 l1 l2 m buf pos newhead (cnt 0))
15159 (goto-char end)
15160 (setq l2 (1- (org-current-line)))
15161 (goto-char beg)
15162 (setq l1 (org-current-line))
15163 (cl-loop for l from l1 to l2 do
15164 (org-goto-line l)
15165 (setq m (get-text-property (point) 'org-hd-marker))
15166 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15167 (and agendap m))
15168 (setq buf (if agendap (marker-buffer m) (current-buffer))
15169 pos (if agendap m (point)))
15170 (with-current-buffer buf
15171 (save-excursion
15172 (save-restriction
15173 (goto-char pos)
15174 (setq cnt (1+ cnt))
15175 (org-toggle-tag tag (if off 'off 'on))
15176 (setq newhead (org-get-heading)))))
15177 (and agendap (org-agenda-change-all-lines newhead m))))
15178 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15180 (defun org-tags-completion-function (string _predicate &optional flag)
15181 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15182 (confirm (lambda (x) (stringp (car x)))))
15183 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15184 (setq s1 (match-string 1 string)
15185 s2 (match-string 2 string))
15186 (setq s1 "" s2 string))
15187 (cond
15188 ((eq flag nil)
15189 ;; try completion
15190 (setq rtn (try-completion s2 ctable confirm))
15191 (when (stringp rtn)
15192 (setq rtn
15193 (concat s1 s2 (substring rtn (length s2))
15194 (if (and org-add-colon-after-tag-completion
15195 (assoc rtn ctable))
15196 ":" ""))))
15197 rtn)
15198 ((eq flag t)
15199 ;; all-completions
15200 (all-completions s2 ctable confirm))
15201 ((eq flag 'lambda)
15202 ;; exact match?
15203 (assoc s2 ctable)))))
15205 (defun org-fast-tag-insert (kwd tags face &optional end)
15206 "Insert KDW, and the TAGS, the latter with face FACE.
15207 Also insert END."
15208 (insert (format "%-12s" (concat kwd ":"))
15209 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15210 (or end "")))
15212 (defun org-fast-tag-show-exit (flag)
15213 (save-excursion
15214 (org-goto-line 3)
15215 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15216 (replace-match ""))
15217 (when flag
15218 (end-of-line 1)
15219 (org-move-to-column (- (window-width) 19) t)
15220 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15222 (defun org-set-current-tags-overlay (current prefix)
15223 "Add an overlay to CURRENT tag with PREFIX."
15224 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15225 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15226 (org-overlay-display org-tags-overlay (concat prefix s))))
15228 (defvar org-last-tag-selection-key nil)
15229 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15230 "Fast tag selection with single keys.
15231 CURRENT is the current list of tags in the headline, INHERITED is the
15232 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15233 possibly with grouping information. TODO-TABLE is a similar table with
15234 TODO keywords, should these have keys assigned to them.
15235 If the keys are nil, a-z are automatically assigned.
15236 Returns the new tags string, or nil to not change the current settings."
15237 (let* ((fulltable (append table todo-table))
15238 (maxlen (apply 'max (mapcar
15239 (lambda (x)
15240 (if (stringp (car x)) (string-width (car x)) 0))
15241 fulltable)))
15242 (buf (current-buffer))
15243 (expert (eq org-fast-tag-selection-single-key 'expert))
15244 (buffer-tags nil)
15245 (fwidth (+ maxlen 3 1 3))
15246 (ncol (/ (- (window-width) 4) fwidth))
15247 (i-face 'org-done)
15248 (c-face 'org-todo)
15249 tg cnt e c char c1 c2 ntable tbl rtn
15250 ov-start ov-end ov-prefix
15251 (exit-after-next org-fast-tag-selection-single-key)
15252 (done-keywords org-done-keywords)
15253 groups ingroup intaggroup)
15254 (save-excursion
15255 (beginning-of-line 1)
15256 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15257 (setq ov-start (match-beginning 1)
15258 ov-end (match-end 1)
15259 ov-prefix "")
15260 (setq ov-start (1- (point-at-eol))
15261 ov-end (1+ ov-start))
15262 (skip-chars-forward "^\n\r")
15263 (setq ov-prefix
15264 (concat
15265 (buffer-substring (1- (point)) (point))
15266 (if (> (current-column) org-tags-column)
15268 (make-string (- org-tags-column (current-column)) ?\ ))))))
15269 (move-overlay org-tags-overlay ov-start ov-end)
15270 (save-window-excursion
15271 (if expert
15272 (set-buffer (get-buffer-create " *Org tags*"))
15273 (delete-other-windows)
15274 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15275 (org-switch-to-buffer-other-window " *Org tags*"))
15276 (erase-buffer)
15277 (setq-local org-done-keywords done-keywords)
15278 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15279 (org-fast-tag-insert "Current" current c-face "\n\n")
15280 (org-fast-tag-show-exit exit-after-next)
15281 (org-set-current-tags-overlay current ov-prefix)
15282 (setq tbl fulltable char ?a cnt 0)
15283 (while (setq e (pop tbl))
15284 (cond
15285 ((eq (car e) :startgroup)
15286 (push '() groups) (setq ingroup t)
15287 (unless (zerop cnt)
15288 (setq cnt 0)
15289 (insert "\n"))
15290 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15291 ((eq (car e) :endgroup)
15292 (setq ingroup nil cnt 0)
15293 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15294 ((eq (car e) :startgrouptag)
15295 (setq intaggroup t)
15296 (unless (zerop cnt)
15297 (setq cnt 0)
15298 (insert "\n"))
15299 (insert "[ "))
15300 ((eq (car e) :endgrouptag)
15301 (setq intaggroup nil cnt 0)
15302 (insert "]\n"))
15303 ((equal e '(:newline))
15304 (unless (zerop cnt)
15305 (setq cnt 0)
15306 (insert "\n")
15307 (setq e (car tbl))
15308 (while (equal (car tbl) '(:newline))
15309 (insert "\n")
15310 (setq tbl (cdr tbl)))))
15311 ((equal e '(:grouptags)) (insert " : "))
15313 (setq tg (copy-sequence (car e)) c2 nil)
15314 (if (cdr e)
15315 (setq c (cdr e))
15316 ;; automatically assign a character.
15317 (setq c1 (string-to-char
15318 (downcase (substring
15319 tg (if (= (string-to-char tg) ?@) 1 0)))))
15320 (if (or (rassoc c1 ntable) (rassoc c1 table))
15321 (while (or (rassoc char ntable) (rassoc char table))
15322 (setq char (1+ char)))
15323 (setq c2 c1))
15324 (setq c (or c2 char)))
15325 (when ingroup (push tg (car groups)))
15326 (setq tg (org-add-props tg nil 'face
15327 (cond
15328 ((not (assoc tg table))
15329 (org-get-todo-face tg))
15330 ((member tg current) c-face)
15331 ((member tg inherited) i-face))))
15332 (when (equal (caar tbl) :grouptags)
15333 (org-add-props tg nil 'face 'org-tag-group))
15334 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15335 (insert "[" c "] " tg (make-string
15336 (- fwidth 4 (length tg)) ?\ ))
15337 (push (cons tg c) ntable)
15338 (when (= (cl-incf cnt) ncol)
15339 (insert "\n")
15340 (when (or ingroup intaggroup) (insert " "))
15341 (setq cnt 0)))))
15342 (setq ntable (nreverse ntable))
15343 (insert "\n")
15344 (goto-char (point-min))
15345 (unless expert (org-fit-window-to-buffer))
15346 (setq rtn
15347 (catch 'exit
15348 (while t
15349 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15350 (if (not groups) "no " "")
15351 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15352 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15353 (setq org-last-tag-selection-key c)
15354 (cond
15355 ((= c ?\r) (throw 'exit t))
15356 ((= c ?!)
15357 (setq groups (not groups))
15358 (goto-char (point-min))
15359 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15360 ((= c ?\C-c)
15361 (if (not expert)
15362 (org-fast-tag-show-exit
15363 (setq exit-after-next (not exit-after-next)))
15364 (setq expert nil)
15365 (delete-other-windows)
15366 (set-window-buffer (split-window-vertically) " *Org tags*")
15367 (org-switch-to-buffer-other-window " *Org tags*")
15368 (org-fit-window-to-buffer)))
15369 ((or (= c ?\C-g)
15370 (and (= c ?q) (not (rassoc c ntable))))
15371 (delete-overlay org-tags-overlay)
15372 (setq quit-flag t))
15373 ((= c ?\ )
15374 (setq current nil)
15375 (when exit-after-next (setq exit-after-next 'now)))
15376 ((= c ?\t)
15377 (condition-case nil
15378 (setq tg (completing-read
15379 "Tag: "
15380 (or buffer-tags
15381 (with-current-buffer buf
15382 (setq buffer-tags
15383 (org-get-buffer-tags))))))
15384 (quit (setq tg "")))
15385 (when (string-match "\\S-" tg)
15386 (cl-pushnew (list tg) buffer-tags :test #'equal)
15387 (if (member tg current)
15388 (setq current (delete tg current))
15389 (push tg current)))
15390 (when exit-after-next (setq exit-after-next 'now)))
15391 ((setq e (rassoc c todo-table) tg (car e))
15392 (with-current-buffer buf
15393 (save-excursion (org-todo tg)))
15394 (when exit-after-next (setq exit-after-next 'now)))
15395 ((setq e (rassoc c ntable) tg (car e))
15396 (if (member tg current)
15397 (setq current (delete tg current))
15398 (cl-loop for g in groups do
15399 (when (member tg g)
15400 (dolist (x g) (setq current (delete x current)))))
15401 (push tg current))
15402 (when exit-after-next (setq exit-after-next 'now))))
15404 ;; Create a sorted list
15405 (setq current
15406 (sort current
15407 (lambda (a b)
15408 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15409 (when (eq exit-after-next 'now) (throw 'exit t))
15410 (goto-char (point-min))
15411 (beginning-of-line 2)
15412 (delete-region (point) (point-at-eol))
15413 (org-fast-tag-insert "Current" current c-face)
15414 (org-set-current-tags-overlay current ov-prefix)
15415 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15416 (setq tg (match-string 1))
15417 (add-text-properties
15418 (match-beginning 1) (match-end 1)
15419 (list 'face
15420 (cond
15421 ((member tg current) c-face)
15422 ((member tg inherited) i-face)
15423 (t (get-text-property (match-beginning 1) 'face))))))
15424 (goto-char (point-min)))))
15425 (delete-overlay org-tags-overlay)
15426 (if rtn
15427 (mapconcat 'identity current ":")
15428 nil))))
15430 (defun org-get-tags-string ()
15431 "Get the TAGS string in the current headline."
15432 (unless (org-at-heading-p t)
15433 (user-error "Not on a heading"))
15434 (save-excursion
15435 (beginning-of-line 1)
15436 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15437 (match-string-no-properties 1)
15438 "")))
15440 (defun org-get-tags ()
15441 "Get the list of tags specified in the current headline."
15442 (org-split-string (org-get-tags-string) ":"))
15444 (defun org-get-buffer-tags ()
15445 "Get a table of all tags used in the buffer, for completion."
15446 (org-with-wide-buffer
15447 (goto-char (point-min))
15448 (let ((tag-re (concat org-outline-regexp-bol
15449 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15450 tags)
15451 (while (re-search-forward tag-re nil t)
15452 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15453 (push tag tags)))
15454 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15456 ;;;; The mapping API
15458 (defvar org-agenda-skip-comment-trees)
15459 (defvar org-agenda-skip-function)
15460 (defun org-map-entries (func &optional match scope &rest skip)
15461 "Call FUNC at each headline selected by MATCH in SCOPE.
15463 FUNC is a function or a lisp form. The function will be called without
15464 arguments, with the cursor positioned at the beginning of the headline.
15465 The return values of all calls to the function will be collected and
15466 returned as a list.
15468 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15469 does not need to preserve point. After evaluation, the cursor will be
15470 moved to the end of the line (presumably of the headline of the
15471 processed entry) and search continues from there. Under some
15472 circumstances, this may not produce the wanted results. For example,
15473 if you have removed (e.g. archived) the current (sub)tree it could
15474 mean that the next entry will be skipped entirely. In such cases, you
15475 can specify the position from where search should continue by making
15476 FUNC set the variable `org-map-continue-from' to the desired buffer
15477 position.
15479 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15480 Only headlines that are matched by this query will be considered during
15481 the iteration. When MATCH is nil or t, all headlines will be
15482 visited by the iteration.
15484 SCOPE determines the scope of this command. It can be any of:
15486 nil The current buffer, respecting the restriction if any
15487 tree The subtree started with the entry at point
15488 region The entries within the active region, if any
15489 region-start-level
15490 The entries within the active region, but only those at
15491 the same level than the first one.
15492 file The current buffer, without restriction
15493 file-with-archives
15494 The current buffer, and any archives associated with it
15495 agenda All agenda files
15496 agenda-with-archives
15497 All agenda files with any archive files associated with them
15498 \(file1 file2 ...)
15499 If this is a list, all files in the list will be scanned
15501 The remaining args are treated as settings for the skipping facilities of
15502 the scanner. The following items can be given here:
15504 archive skip trees with the archive tag
15505 comment skip trees with the COMMENT keyword
15506 function or Emacs Lisp form:
15507 will be used as value for `org-agenda-skip-function', so
15508 whenever the function returns a position, FUNC will not be
15509 called for that entry and search will continue from the
15510 position returned
15512 If your function needs to retrieve the tags including inherited tags
15513 at the *current* entry, you can use the value of the variable
15514 `org-scanner-tags' which will be much faster than getting the value
15515 with `org-get-tags-at'. If your function gets properties with
15516 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15517 to t around the call to `org-entry-properties' to get the same speedup.
15518 Note that if your function moves around to retrieve tags and properties at
15519 a *different* entry, you cannot use these techniques."
15520 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15521 (not (org-region-active-p)))
15522 (let* ((org-agenda-archives-mode nil) ; just to make sure
15523 (org-agenda-skip-archived-trees (memq 'archive skip))
15524 (org-agenda-skip-comment-trees (memq 'comment skip))
15525 (org-agenda-skip-function
15526 (car (org-delete-all '(comment archive) skip)))
15527 (org-tags-match-list-sublevels t)
15528 (start-level (eq scope 'region-start-level))
15529 matcher res
15530 org-todo-keywords-for-agenda
15531 org-done-keywords-for-agenda
15532 org-todo-keyword-alist-for-agenda
15533 org-tag-alist-for-agenda
15534 org--matcher-tags-todo-only)
15536 (cond
15537 ((eq match t) (setq matcher t))
15538 ((eq match nil) (setq matcher t))
15539 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15541 (save-excursion
15542 (save-restriction
15543 (cond ((eq scope 'tree)
15544 (org-back-to-heading t)
15545 (org-narrow-to-subtree)
15546 (setq scope nil))
15547 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15548 (org-region-active-p))
15549 ;; If needed, set start-level to a string like "2"
15550 (when start-level
15551 (save-excursion
15552 (goto-char (region-beginning))
15553 (unless (org-at-heading-p) (outline-next-heading))
15554 (setq start-level (org-current-level))))
15555 (narrow-to-region (region-beginning)
15556 (save-excursion
15557 (goto-char (region-end))
15558 (unless (and (bolp) (org-at-heading-p))
15559 (outline-next-heading))
15560 (point)))
15561 (setq scope nil)))
15563 (if (not scope)
15564 (progn
15565 (org-agenda-prepare-buffers
15566 (and buffer-file-name (list buffer-file-name)))
15567 (setq res
15568 (org-scan-tags
15569 func matcher org--matcher-tags-todo-only start-level)))
15570 ;; Get the right scope
15571 (cond
15572 ((and scope (listp scope) (symbolp (car scope)))
15573 (setq scope (eval scope)))
15574 ((eq scope 'agenda)
15575 (setq scope (org-agenda-files t)))
15576 ((eq scope 'agenda-with-archives)
15577 (setq scope (org-agenda-files t))
15578 (setq scope (org-add-archive-files scope)))
15579 ((eq scope 'file)
15580 (setq scope (and buffer-file-name (list buffer-file-name))))
15581 ((eq scope 'file-with-archives)
15582 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15583 (org-agenda-prepare-buffers scope)
15584 (dolist (file scope)
15585 (with-current-buffer (org-find-base-buffer-visiting file)
15586 (org-with-wide-buffer
15587 (goto-char (point-min))
15588 (setq res
15589 (append
15591 (org-scan-tags
15592 func matcher org--matcher-tags-todo-only)))))))))
15593 res)))
15595 ;;; Properties API
15597 (defconst org-special-properties
15598 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15599 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15600 "The special properties valid in Org mode.
15601 These are properties that are not defined in the property drawer,
15602 but in some other way.")
15604 (defconst org-default-properties
15605 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15606 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15607 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15608 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15609 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15610 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15611 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15612 "Some properties that are used by Org mode for various purposes.
15613 Being in this list makes sure that they are offered for completion.")
15615 (defun org--valid-property-p (property)
15616 "Non nil when string PROPERTY is a valid property name."
15617 (not
15618 (or (equal property "")
15619 (string-match-p "\\s-" property))))
15621 (defun org--update-property-plist (key val props)
15622 "Associate KEY to VAL in alist PROPS.
15623 Modifications are made by side-effect. Return new alist."
15624 (let* ((appending (string= (substring key -1) "+"))
15625 (key (if appending (substring key 0 -1) key))
15626 (old (assoc-string key props t)))
15627 (if (not old) (cons (cons key val) props)
15628 (setcdr old (if appending (concat (cdr old) " " val) val))
15629 props)))
15631 (defun org-get-property-block (&optional beg force)
15632 "Return the (beg . end) range of the body of the property drawer.
15633 BEG is the beginning of the current subtree, or of the part
15634 before the first headline. If it is not given, it will be found.
15635 If the drawer does not exist, create it if FORCE is non-nil, or
15636 return nil."
15637 (org-with-wide-buffer
15638 (when beg (goto-char beg))
15639 (unless (org-before-first-heading-p)
15640 (let ((beg (cond (beg)
15641 ((or (not (featurep 'org-inlinetask))
15642 (org-inlinetask-in-task-p))
15643 (org-back-to-heading t))
15644 (t (org-with-limited-levels (org-back-to-heading t))))))
15645 (forward-line)
15646 (when (looking-at-p org-planning-line-re) (forward-line))
15647 (cond ((looking-at org-property-drawer-re)
15648 (forward-line)
15649 (cons (point) (progn (goto-char (match-end 0))
15650 (line-beginning-position))))
15651 (force
15652 (goto-char beg)
15653 (org-insert-property-drawer)
15654 (let ((pos (save-excursion (search-forward ":END:")
15655 (line-beginning-position))))
15656 (cons pos pos))))))))
15658 (defun org-at-property-p ()
15659 "Non-nil when point is inside a property drawer.
15660 See `org-property-re' for match data, if applicable."
15661 (save-excursion
15662 (beginning-of-line)
15663 (and (looking-at org-property-re)
15664 (let ((property-drawer (save-match-data (org-get-property-block))))
15665 (and property-drawer
15666 (>= (point) (car property-drawer))
15667 (< (point) (cdr property-drawer)))))))
15669 (defun org-property-action ()
15670 "Do an action on properties."
15671 (interactive)
15672 (unless (org-at-property-p) (user-error "Not at a property"))
15673 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15674 (let ((c (read-char-exclusive)))
15675 (cl-case c
15676 (?s (call-interactively #'org-set-property))
15677 (?d (call-interactively #'org-delete-property))
15678 (?D (call-interactively #'org-delete-property-globally))
15679 (?c (call-interactively #'org-compute-property-at-point))
15680 (otherwise (user-error "No such property action %c" c)))))
15682 (defun org-inc-effort ()
15683 "Increment the value of the effort property in the current entry."
15684 (interactive)
15685 (org-set-effort nil t))
15687 (defvar org-clock-effort) ; Defined in org-clock.el.
15688 (defvar org-clock-current-task) ; Defined in org-clock.el.
15689 (defun org-set-effort (&optional value increment)
15690 "Set the effort property of the current entry.
15691 With numerical prefix arg, use the nth allowed value, 0 stands for the
15692 10th allowed value.
15694 When INCREMENT is non-nil, set the property to the next allowed value."
15695 (interactive "P")
15696 (when (equal value 0) (setq value 10))
15697 (let* ((completion-ignore-case t)
15698 (prop org-effort-property)
15699 (cur (org-entry-get nil prop))
15700 (allowed (org-property-get-allowed-values nil prop 'table))
15701 (existing (mapcar 'list (org-property-values prop)))
15702 (heading (nth 4 (org-heading-components)))
15704 (val (cond
15705 ((stringp value) value)
15706 ((and allowed (integerp value))
15707 (or (car (nth (1- value) allowed))
15708 (car (org-last allowed))))
15709 ((and allowed increment)
15710 (or (cl-caadr (member (list cur) allowed))
15711 (user-error "Allowed effort values are not set")))
15712 (allowed
15713 (message "Select 1-9,0, [RET%s]: %s"
15714 (if cur (concat "=" cur) "")
15715 (mapconcat 'car allowed " "))
15716 (setq rpl (read-char-exclusive))
15717 (if (equal rpl ?\r)
15719 (setq rpl (- rpl ?0))
15720 (when (equal rpl 0) (setq rpl 10))
15721 (if (and (> rpl 0) (<= rpl (length allowed)))
15722 (car (nth (1- rpl) allowed))
15723 (org-completing-read "Effort: " allowed nil))))
15725 (org-completing-read
15726 (concat "Effort" (and cur (string-match "\\S-" cur)
15727 (concat " [" cur "]"))
15728 ": ")
15729 existing nil nil "" nil cur)))))
15730 (unless (equal (org-entry-get nil prop) val)
15731 (org-entry-put nil prop val))
15732 (org-refresh-property
15733 '((effort . identity)
15734 (effort-minutes . org-duration-string-to-minutes))
15735 val)
15736 (when (equal heading (bound-and-true-p org-clock-current-task))
15737 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15738 (org-clock-update-mode-line))
15739 (message "%s is now %s" prop val)))
15741 (defun org-entry-properties (&optional pom which)
15742 "Get all properties of the current entry.
15744 When POM is a buffer position, get all properties from the entry
15745 there instead.
15747 This includes the TODO keyword, the tags, time strings for
15748 deadline, scheduled, and clocking, and any additional properties
15749 defined in the entry.
15751 If WHICH is nil or `all', get all properties. If WHICH is
15752 `special' or `standard', only get that subclass. If WHICH is
15753 a string, only get that property.
15755 Return value is an alist. Keys are properties, as upcased
15756 strings."
15757 (org-with-point-at pom
15758 (when (and (derived-mode-p 'org-mode)
15759 (ignore-errors (org-back-to-heading t)))
15760 (catch 'exit
15761 (let* ((beg (point))
15762 (specific (and (stringp which) (upcase which)))
15763 (which (cond ((not specific) which)
15764 ((member specific org-special-properties) 'special)
15765 (t 'standard)))
15766 props)
15767 ;; Get the special properties, like TODO and TAGS.
15768 (when (memq which '(nil all special))
15769 (when (or (not specific) (string= specific "CLOCKSUM"))
15770 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15771 (when clocksum
15772 (push (cons "CLOCKSUM"
15773 (org-minutes-to-clocksum-string clocksum))
15774 props)))
15775 (when specific (throw 'exit props)))
15776 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15777 (let ((clocksumt (get-text-property (point)
15778 :org-clock-minutes-today)))
15779 (when clocksumt
15780 (push (cons "CLOCKSUM_T"
15781 (org-minutes-to-clocksum-string clocksumt))
15782 props)))
15783 (when specific (throw 'exit props)))
15784 (when (or (not specific) (string= specific "ITEM"))
15785 (when (looking-at org-complex-heading-regexp)
15786 (push (cons "ITEM"
15787 (let ((title (match-string-no-properties 4)))
15788 (if (org-string-nw-p title)
15789 (org-remove-tabs title)
15790 "")))
15791 props))
15792 (when specific (throw 'exit props)))
15793 (when (or (not specific) (string= specific "TODO"))
15794 (let ((case-fold-search nil))
15795 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15796 (push (cons "TODO" (match-string-no-properties 2)) props)))
15797 (when specific (throw 'exit props)))
15798 (when (or (not specific) (string= specific "PRIORITY"))
15799 (push (cons "PRIORITY"
15800 (if (looking-at org-priority-regexp)
15801 (match-string-no-properties 2)
15802 (char-to-string org-default-priority)))
15803 props)
15804 (when specific (throw 'exit props)))
15805 (when (or (not specific) (string= specific "FILE"))
15806 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15807 props)
15808 (when specific (throw 'exit props)))
15809 (when (or (not specific) (string= specific "TAGS"))
15810 (let ((value (org-string-nw-p (org-get-tags-string))))
15811 (when value (push (cons "TAGS" value) props)))
15812 (when specific (throw 'exit props)))
15813 (when (or (not specific) (string= specific "ALLTAGS"))
15814 (let ((value (org-get-tags-at)))
15815 (when value
15816 (push (cons "ALLTAGS"
15817 (format ":%s:" (mapconcat #'identity value ":")))
15818 props)))
15819 (when specific (throw 'exit props)))
15820 (when (or (not specific) (string= specific "BLOCKED"))
15821 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15822 (when specific (throw 'exit props)))
15823 (when (or (not specific)
15824 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15825 (forward-line)
15826 (when (looking-at-p org-planning-line-re)
15827 (end-of-line)
15828 (let ((bol (line-beginning-position))
15829 ;; Backward compatibility: time keywords used to
15830 ;; be configurable (before 8.3). Make sure we
15831 ;; get the correct keyword.
15832 (key-assoc `(("CLOSED" . ,org-closed-string)
15833 ("DEADLINE" . ,org-deadline-string)
15834 ("SCHEDULED" . ,org-scheduled-string))))
15835 (dolist (pair (if specific (list (assoc specific key-assoc))
15836 key-assoc))
15837 (save-excursion
15838 (when (search-backward (cdr pair) bol t)
15839 (goto-char (match-end 0))
15840 (skip-chars-forward " \t")
15841 (and (looking-at org-ts-regexp-both)
15842 (push (cons (car pair)
15843 (match-string-no-properties 0))
15844 props)))))))
15845 (when specific (throw 'exit props)))
15846 (when (or (not specific)
15847 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15848 (let ((find-ts
15849 (lambda (end ts)
15850 ;; Fix next time-stamp before END. TS is the
15851 ;; list of time-stamps found so far.
15852 (let ((ts ts)
15853 (regexp (cond
15854 ((string= specific "TIMESTAMP")
15855 org-ts-regexp)
15856 ((string= specific "TIMESTAMP_IA")
15857 org-ts-regexp-inactive)
15858 ((assoc "TIMESTAMP_IA" ts)
15859 org-ts-regexp)
15860 ((assoc "TIMESTAMP" ts)
15861 org-ts-regexp-inactive)
15862 (t org-ts-regexp-both))))
15863 (catch 'next
15864 (while (re-search-forward regexp end t)
15865 (backward-char)
15866 (let ((object (org-element-context)))
15867 ;; Accept to match timestamps in node
15868 ;; properties, too.
15869 (when (memq (org-element-type object)
15870 '(node-property timestamp))
15871 (let ((type
15872 (org-element-property :type object)))
15873 (cond
15874 ((and (memq type '(active active-range))
15875 (not (equal specific "TIMESTAMP_IA")))
15876 (unless (assoc "TIMESTAMP" ts)
15877 (push (cons "TIMESTAMP"
15878 (org-element-property
15879 :raw-value object))
15881 (when specific (throw 'exit ts))))
15882 ((and (memq type '(inactive inactive-range))
15883 (not (string= specific "TIMESTAMP")))
15884 (unless (assoc "TIMESTAMP_IA" ts)
15885 (push (cons "TIMESTAMP_IA"
15886 (org-element-property
15887 :raw-value object))
15889 (when specific (throw 'exit ts))))))
15890 ;; Both timestamp types are found,
15891 ;; move to next part.
15892 (when (= (length ts) 2) (throw 'next ts)))))
15893 ts)))))
15894 (goto-char beg)
15895 ;; First look for timestamps within headline.
15896 (let ((ts (funcall find-ts (line-end-position) nil)))
15897 (if (= (length ts) 2) (setq props (nconc ts props))
15898 (forward-line)
15899 ;; Then find timestamps in the section, skipping
15900 ;; planning line.
15901 (when (looking-at-p org-planning-line-re)
15902 (forward-line))
15903 (let ((end (save-excursion (outline-next-heading))))
15904 (setq props (nconc (funcall find-ts end ts) props))))))))
15905 ;; Get the standard properties, like :PROP:.
15906 (when (memq which '(nil all standard))
15907 ;; If we are looking after a specific property, delegate
15908 ;; to `org-entry-get', which is faster. However, make an
15909 ;; exception for "CATEGORY", since it can be also set
15910 ;; through keywords (i.e. #+CATEGORY).
15911 (if (and specific (not (equal specific "CATEGORY")))
15912 (let ((value (org-entry-get beg specific nil t)))
15913 (throw 'exit (and value (list (cons specific value)))))
15914 (let ((range (org-get-property-block beg)))
15915 (when range
15916 (let ((end (cdr range)) seen-base)
15917 (goto-char (car range))
15918 ;; Unlike to `org--update-property-plist', we
15919 ;; handle the case where base values is found
15920 ;; after its extension. We also forbid standard
15921 ;; properties to be named as special properties.
15922 (while (re-search-forward org-property-re end t)
15923 (let* ((key (upcase (match-string-no-properties 2)))
15924 (extendp (string-match-p "\\+\\'" key))
15925 (key-base (if extendp (substring key 0 -1) key))
15926 (value (match-string-no-properties 3)))
15927 (cond
15928 ((member-ignore-case key-base org-special-properties))
15929 (extendp
15930 (setq props
15931 (org--update-property-plist key value props)))
15932 ((member key seen-base))
15933 (t (push key seen-base)
15934 (let ((p (assoc-string key props t)))
15935 (if p (setcdr p (concat value " " (cdr p)))
15936 (push (cons key value) props))))))))))))
15937 (unless (assoc "CATEGORY" props)
15938 (push (cons "CATEGORY" (org-get-category beg)) props)
15939 (when (string= specific "CATEGORY") (throw 'exit props)))
15940 ;; Return value.
15941 props)))))
15943 (defun org-property--local-values (property literal-nil)
15944 "Return value for PROPERTY in current entry.
15945 Value is a list whose car is the base value for PROPERTY and cdr
15946 a list of accumulated values. Return nil if neither is found in
15947 the entry. Also return nil when PROPERTY is set to \"nil\",
15948 unless LITERAL-NIL is non-nil."
15949 (let ((range (org-get-property-block)))
15950 (when range
15951 (goto-char (car range))
15952 (let* ((case-fold-search t)
15953 (end (cdr range))
15954 (value
15955 ;; Base value.
15956 (save-excursion
15957 (let ((v (and (re-search-forward
15958 (org-re-property property nil t) end t)
15959 (match-string-no-properties 3))))
15960 (list (if literal-nil v (org-not-nil v)))))))
15961 ;; Find additional values.
15962 (let* ((property+ (org-re-property (concat property "+") nil t)))
15963 (while (re-search-forward property+ end t)
15964 (push (match-string-no-properties 3) value)))
15965 ;; Return final values.
15966 (and (not (equal value '(nil))) (nreverse value))))))
15968 (defun org-entry-get (pom property &optional inherit literal-nil)
15969 "Get value of PROPERTY for entry or content at point-or-marker POM.
15971 If INHERIT is non-nil and the entry does not have the property,
15972 then also check higher levels of the hierarchy. If INHERIT is
15973 the symbol `selective', use inheritance only if the setting in
15974 `org-use-property-inheritance' selects PROPERTY for inheritance.
15976 If the property is present but empty, the return value is the
15977 empty string. If the property is not present at all, nil is
15978 returned. In any other case, return the value as a string.
15979 Search is case-insensitive.
15981 If LITERAL-NIL is set, return the string value \"nil\" as
15982 a string, do not interpret it as the list atom nil. This is used
15983 for inheritance when a \"nil\" value can supersede a non-nil
15984 value higher up the hierarchy."
15985 (org-with-point-at pom
15986 (cond
15987 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15988 ;; We need a special property. Use `org-entry-properties' to
15989 ;; retrieve it, but specify the wanted property.
15990 (cdr (assoc-string property (org-entry-properties nil property))))
15991 ((and inherit
15992 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15993 (org-entry-get-with-inheritance property literal-nil))
15995 (let* ((local (org-property--local-values property literal-nil))
15996 (value (and local (mapconcat #'identity (delq nil local) " "))))
15997 (if literal-nil value (org-not-nil value)))))))
15999 (defun org-property-or-variable-value (var &optional inherit)
16000 "Check if there is a property fixing the value of VAR.
16001 If yes, return this value. If not, return the current value of the variable."
16002 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16003 (if (and prop (stringp prop) (string-match "\\S-" prop))
16004 (read prop)
16005 (symbol-value var))))
16007 (defun org-entry-delete (pom property)
16008 "Delete PROPERTY from entry at point-or-marker POM.
16009 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16010 non-nil when a property was removed."
16011 (unless (member property org-special-properties)
16012 (org-with-point-at pom
16013 (let ((range (org-get-property-block)))
16014 (when range
16015 (let* ((begin (car range))
16016 (origin (cdr range))
16017 (end (copy-marker origin))
16018 (re (org-re-property
16019 (concat (regexp-quote property) "\\+?") t t)))
16020 (goto-char begin)
16021 (while (re-search-forward re end t)
16022 (delete-region (match-beginning 0) (line-beginning-position 2)))
16023 ;; If drawer is empty, remove it altogether.
16024 (when (= begin end)
16025 (delete-region (line-beginning-position 0)
16026 (line-beginning-position 2)))
16027 ;; Return non-nil if some property was removed.
16028 (prog1 (/= end origin) (set-marker end nil))))))))
16030 ;; Multi-values properties are properties that contain multiple values
16031 ;; These values are assumed to be single words, separated by whitespace.
16032 (defun org-entry-add-to-multivalued-property (pom property value)
16033 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16034 (let* ((old (org-entry-get pom property))
16035 (values (and old (org-split-string old "[ \t]"))))
16036 (setq value (org-entry-protect-space value))
16037 (unless (member value values)
16038 (setq values (append values (list value)))
16039 (org-entry-put pom property
16040 (mapconcat 'identity values " ")))))
16042 (defun org-entry-remove-from-multivalued-property (pom property value)
16043 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16044 (let* ((old (org-entry-get pom property))
16045 (values (and old (org-split-string old "[ \t]"))))
16046 (setq value (org-entry-protect-space value))
16047 (when (member value values)
16048 (setq values (delete value values))
16049 (org-entry-put pom property
16050 (mapconcat 'identity values " ")))))
16052 (defun org-entry-member-in-multivalued-property (pom property value)
16053 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16054 (let* ((old (org-entry-get pom property))
16055 (values (and old (org-split-string old "[ \t]"))))
16056 (setq value (org-entry-protect-space value))
16057 (member value values)))
16059 (defun org-entry-get-multivalued-property (pom property)
16060 "Return a list of values in a multivalued property."
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-put-multivalued-property (pom property &rest values)
16066 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16067 VALUES should be a list of strings. Spaces will be protected."
16068 (org-entry-put pom property
16069 (mapconcat 'org-entry-protect-space values " "))
16070 (let* ((value (org-entry-get pom property))
16071 (values (and value (org-split-string value "[ \t]"))))
16072 (mapcar 'org-entry-restore-space values)))
16074 (defun org-entry-protect-space (s)
16075 "Protect spaces and newline in string S."
16076 (while (string-match " " s)
16077 (setq s (replace-match "%20" t t s)))
16078 (while (string-match "\n" s)
16079 (setq s (replace-match "%0A" t t s)))
16082 (defun org-entry-restore-space (s)
16083 "Restore spaces and newline in string S."
16084 (while (string-match "%20" s)
16085 (setq s (replace-match " " t t s)))
16086 (while (string-match "%0A" s)
16087 (setq s (replace-match "\n" t t s)))
16090 (defvar org-entry-property-inherited-from (make-marker)
16091 "Marker pointing to the entry from where a property was inherited.
16092 Each call to `org-entry-get-with-inheritance' will set this marker to the
16093 location of the entry where the inheritance search matched. If there was
16094 no match, the marker will point nowhere.
16095 Note that also `org-entry-get' calls this function, if the INHERIT flag
16096 is set.")
16098 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16099 "Get PROPERTY of entry or content at point, search higher levels if needed.
16100 The search will stop at the first ancestor which has the property defined.
16101 If the value found is \"nil\", return nil to show that the property
16102 should be considered as undefined (this is the meaning of nil here).
16103 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16104 (move-marker org-entry-property-inherited-from nil)
16105 (org-with-wide-buffer
16106 (let (value)
16107 (catch 'exit
16108 (while t
16109 (let ((v (org-property--local-values property literal-nil)))
16110 (when v
16111 (setq value
16112 (concat (mapconcat #'identity (delq nil v) " ")
16113 (and value " ")
16114 value)))
16115 (cond
16116 ((car v)
16117 (org-back-to-heading t)
16118 (move-marker org-entry-property-inherited-from (point))
16119 (throw 'exit nil))
16120 ((org-up-heading-safe))
16122 (let ((global
16123 (cdr (or (assoc-string property org-file-properties t)
16124 (assoc-string property org-global-properties t)
16125 (assoc-string property org-global-properties-fixed t)))))
16126 (cond ((not global))
16127 (value (setq value (concat global " " value)))
16128 (t (setq value global))))
16129 (throw 'exit nil))))))
16130 (if literal-nil value (org-not-nil value)))))
16132 (defvar org-property-changed-functions nil
16133 "Hook called when the value of a property has changed.
16134 Each hook function should accept two arguments, the name of the property
16135 and the new value.")
16137 (defun org-entry-put (pom property value)
16138 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16140 If the value is nil, it is converted to the empty string. If it
16141 is not a string, an error is raised. Also raise an error on
16142 invalid property names.
16144 PROPERTY can be any regular property (see
16145 `org-special-properties'). It can also be \"TODO\",
16146 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16148 For the last two properties, VALUE may have any of the special
16149 values \"earlier\" and \"later\". The function then increases or
16150 decreases scheduled or deadline date by one day."
16151 (cond ((null value) (setq value ""))
16152 ((not (stringp value)) (error "Properties values should be strings"))
16153 ((not (org--valid-property-p property))
16154 (user-error "Invalid property name: \"%s\"" property)))
16155 (org-with-point-at pom
16156 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16157 (org-back-to-heading t)
16158 (org-with-limited-levels (org-back-to-heading t)))
16159 (let ((beg (point)))
16160 (cond
16161 ((equal property "TODO")
16162 (cond ((not (org-string-nw-p value)) (setq value 'none))
16163 ((not (member value org-todo-keywords-1))
16164 (user-error "\"%s\" is not a valid TODO state" value)))
16165 (org-todo value)
16166 (org-set-tags nil 'align))
16167 ((equal property "PRIORITY")
16168 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16169 (org-set-tags nil 'align))
16170 ((equal property "SCHEDULED")
16171 (forward-line)
16172 (if (and (looking-at-p org-planning-line-re)
16173 (re-search-forward
16174 org-scheduled-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-schedule '(4)))
16178 (t (org-schedule nil value)))
16179 (if (member value '("earlier" "later" ""))
16180 (call-interactively #'org-schedule)
16181 (org-schedule nil value))))
16182 ((equal property "DEADLINE")
16183 (forward-line)
16184 (if (and (looking-at-p org-planning-line-re)
16185 (re-search-forward
16186 org-deadline-time-regexp (line-end-position) t))
16187 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16188 ((string= value "later") (org-timestamp-change 1 'day))
16189 ((string= value "") (org-deadline '(4)))
16190 (t (org-deadline nil value)))
16191 (if (member value '("earlier" "later" ""))
16192 (call-interactively #'org-deadline)
16193 (org-deadline nil value))))
16194 ((member property org-special-properties)
16195 (error "The %s property cannot be set with `org-entry-put'" property))
16197 (let* ((range (org-get-property-block beg 'force))
16198 (end (cdr range))
16199 (case-fold-search t))
16200 (goto-char (car range))
16201 (if (re-search-forward (org-re-property property nil t) end t)
16202 (progn (delete-region (match-beginning 0) (match-end 0))
16203 (goto-char (match-beginning 0)))
16204 (goto-char end)
16205 (insert "\n")
16206 (backward-char))
16207 (insert ":" property ":")
16208 (when value (insert " " value))
16209 (org-indent-line)))))
16210 (run-hook-with-args 'org-property-changed-functions property value)))
16212 (defun org-buffer-property-keys
16213 (&optional specials defaults columns ignore-malformed)
16214 "Get all property keys in the current buffer.
16216 When SPECIALS is non-nil, also list the special properties that
16217 reflect things like tags and TODO state.
16219 When DEFAULTS is non-nil, also include properties that has
16220 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16221 DESCRIPTION, LOCATION, and LOGGING and others.
16223 When COLUMNS in non-nil, also include property names given in
16224 COLUMN formats in the current buffer.
16226 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16227 automatically performed, such drawers will be silently ignored."
16228 (let ((case-fold-search t)
16229 (props (append
16230 (and specials org-special-properties)
16231 (and defaults (cons org-effort-property org-default-properties))
16232 nil)))
16233 (org-with-wide-buffer
16234 (goto-char (point-min))
16235 (while (re-search-forward org-property-start-re nil t)
16236 (let ((range (org-get-property-block)))
16237 (catch 'skip
16238 (unless range
16239 (when (and (not ignore-malformed)
16240 (not (org-before-first-heading-p))
16241 (y-or-n-p (format "Malformed drawer at %d, repair?"
16242 (line-beginning-position))))
16243 (org-get-property-block nil t))
16244 (throw 'skip nil))
16245 (goto-char (car range))
16246 (let ((begin (car range))
16247 (end (cdr range)))
16248 ;; Make sure that found property block is not located
16249 ;; before current point, as it would generate an infloop.
16250 ;; It can happen, for example, in the following
16251 ;; situation:
16253 ;; * Headline
16254 ;; :PROPERTIES:
16255 ;; ...
16256 ;; :END:
16257 ;; *************** Inlinetask
16258 ;; #+BEGIN_EXAMPLE
16259 ;; :PROPERTIES:
16260 ;; #+END_EXAMPLE
16262 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16263 (while (< (point) end)
16264 (let ((p (progn (looking-at org-property-re)
16265 (match-string-no-properties 2))))
16266 ;; Only add true property name, not extension symbol.
16267 (push (if (not (string-match-p "\\+\\'" p)) p
16268 (substring p 0 -1))
16269 props))
16270 (forward-line))))
16271 (outline-next-heading)))
16272 (when columns
16273 (goto-char (point-min))
16274 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16275 (let ((element (org-element-at-point)))
16276 (when (memq (org-element-type element) '(keyword node-property))
16277 (let ((value (org-element-property :value element))
16278 (start 0))
16279 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16280 (setq start (match-end 0))
16281 (let ((p (match-string-no-properties 1 value)))
16282 (unless (member-ignore-case p org-special-properties)
16283 (push p props))))))))))
16284 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16286 (defun org-property-values (key)
16287 "List all non-nil values of property KEY in current buffer."
16288 (org-with-wide-buffer
16289 (goto-char (point-min))
16290 (let ((case-fold-search t)
16291 (re (org-re-property key))
16292 values)
16293 (while (re-search-forward re nil t)
16294 (push (org-entry-get (point) key) values))
16295 (delete-dups values))))
16297 (defun org-insert-property-drawer ()
16298 "Insert a property drawer into the current entry."
16299 (org-with-wide-buffer
16300 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16301 (org-back-to-heading t)
16302 (org-with-limited-levels (org-back-to-heading t)))
16303 (forward-line)
16304 (when (looking-at-p org-planning-line-re) (forward-line))
16305 (unless (looking-at-p org-property-drawer-re)
16306 ;; Make sure we start editing a line from current entry, not from
16307 ;; next one. It prevents extending text properties or overlays
16308 ;; belonging to the latter.
16309 (when (bolp) (backward-char))
16310 (let ((begin (1+ (point)))
16311 (inhibit-read-only t))
16312 (insert "\n:PROPERTIES:\n:END:")
16313 (when (eobp) (insert "\n"))
16314 (org-indent-region begin (point))))))
16316 (defun org-insert-drawer (&optional arg drawer)
16317 "Insert a drawer at point.
16319 When optional argument ARG is non-nil, insert a property drawer.
16321 Optional argument DRAWER, when non-nil, is a string representing
16322 drawer's name. Otherwise, the user is prompted for a name.
16324 If a region is active, insert the drawer around that region
16325 instead.
16327 Point is left between drawer's boundaries."
16328 (interactive "P")
16329 (let* ((drawer (if arg "PROPERTIES"
16330 (or drawer (read-from-minibuffer "Drawer: ")))))
16331 (cond
16332 ;; With C-u, fall back on `org-insert-property-drawer'
16333 (arg (org-insert-property-drawer))
16334 ;; Check validity of suggested drawer's name.
16335 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16336 (user-error "Invalid drawer name"))
16337 ;; With an active region, insert a drawer at point.
16338 ((not (org-region-active-p))
16339 (progn
16340 (unless (bolp) (insert "\n"))
16341 (insert (format ":%s:\n\n:END:\n" drawer))
16342 (forward-line -2)))
16343 ;; Otherwise, insert the drawer at point
16345 (let ((rbeg (region-beginning))
16346 (rend (copy-marker (region-end))))
16347 (unwind-protect
16348 (progn
16349 (goto-char rbeg)
16350 (beginning-of-line)
16351 (when (save-excursion
16352 (re-search-forward org-outline-regexp-bol rend t))
16353 (user-error "Drawers cannot contain headlines"))
16354 ;; Position point at the beginning of the first
16355 ;; non-blank line in region. Insert drawer's opening
16356 ;; there, then indent it.
16357 (org-skip-whitespace)
16358 (beginning-of-line)
16359 (insert ":" drawer ":\n")
16360 (forward-line -1)
16361 (indent-for-tab-command)
16362 ;; Move point to the beginning of the first blank line
16363 ;; after the last non-blank line in region. Insert
16364 ;; drawer's closing, then indent it.
16365 (goto-char rend)
16366 (skip-chars-backward " \r\t\n")
16367 (insert "\n:END:")
16368 (deactivate-mark t)
16369 (indent-for-tab-command)
16370 (unless (eolp) (insert "\n")))
16371 ;; Clear marker, whatever the outcome of insertion is.
16372 (set-marker rend nil)))))))
16374 (defvar org-property-set-functions-alist nil
16375 "Property set function alist.
16376 Each entry should have the following format:
16378 (PROPERTY . READ-FUNCTION)
16380 The read function will be called with the same argument as
16381 `org-completing-read'.")
16383 (defun org-set-property-function (property)
16384 "Get the function that should be used to set PROPERTY.
16385 This is computed according to `org-property-set-functions-alist'."
16386 (or (cdr (assoc property org-property-set-functions-alist))
16387 'org-completing-read))
16389 (defun org-read-property-value (property)
16390 "Read PROPERTY value from user."
16391 (let* ((completion-ignore-case t)
16392 (allowed (org-property-get-allowed-values nil property 'table))
16393 (cur (org-entry-get nil property))
16394 (prompt (concat property " value"
16395 (if (and cur (string-match "\\S-" cur))
16396 (concat " [" cur "]") "") ": "))
16397 (set-function (org-set-property-function property))
16398 (val (if allowed
16399 (funcall set-function prompt allowed nil
16400 (not (get-text-property 0 'org-unrestricted
16401 (caar allowed))))
16402 (funcall set-function prompt
16403 (mapcar 'list (org-property-values property))
16404 nil nil "" nil cur))))
16405 (org-trim val)))
16407 (defvar org-last-set-property nil)
16408 (defvar org-last-set-property-value nil)
16409 (defun org-read-property-name ()
16410 "Read a property name."
16411 (let ((completion-ignore-case t)
16412 (default-prop (or (and (org-at-property-p)
16413 (match-string-no-properties 2))
16414 org-last-set-property)))
16415 (org-completing-read
16416 (concat "Property"
16417 (if default-prop (concat " [" default-prop "]") "")
16418 ": ")
16419 (mapcar #'list (org-buffer-property-keys nil t t))
16420 nil nil nil nil default-prop)))
16422 (defun org-set-property-and-value (use-last)
16423 "Allow to set [PROPERTY]: [value] direction from prompt.
16424 When use-default, don't even ask, just use the last
16425 \"[PROPERTY]: [value]\" string from the history."
16426 (interactive "P")
16427 (let* ((completion-ignore-case t)
16428 (pv (or (and use-last org-last-set-property-value)
16429 (org-completing-read
16430 "Enter a \"[Property]: [value]\" pair: "
16431 nil nil nil nil nil
16432 org-last-set-property-value)))
16433 prop val)
16434 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16435 (setq prop (match-string 1 pv)
16436 val (match-string 2 pv))
16437 (org-set-property prop val))))
16439 (defun org-set-property (property value)
16440 "In the current entry, set PROPERTY to VALUE.
16442 When called interactively, this will prompt for a property name, offering
16443 completion on existing and default properties. And then it will prompt
16444 for a value, offering completion either on allowed values (via an inherited
16445 xxx_ALL property) or on existing values in other instances of this property
16446 in the current file.
16448 Throw an error when trying to set a property with an invalid name."
16449 (interactive (list nil nil))
16450 (let ((property (or property (org-read-property-name))))
16451 ;; `org-entry-put' also makes the following check, but this one
16452 ;; avoids polluting `org-last-set-property' and
16453 ;; `org-last-set-property-value' needlessly.
16454 (unless (org--valid-property-p property)
16455 (user-error "Invalid property name: \"%s\"" property))
16456 (let ((value (or value (org-read-property-value property)))
16457 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16458 (setq org-last-set-property property)
16459 (setq org-last-set-property-value (concat property ": " value))
16460 ;; Possibly postprocess the inserted value:
16461 (when fn (setq value (funcall fn value)))
16462 (unless (equal (org-entry-get nil property) value)
16463 (org-entry-put nil property value)))))
16465 (defun org-find-property (property &optional value)
16466 "Find first entry in buffer that sets PROPERTY.
16468 When optional argument VALUE is non-nil, only consider an entry
16469 if it contains PROPERTY set to this value. If PROPERTY should be
16470 explicitly set to nil, use string \"nil\" for VALUE.
16472 Return position where the entry begins, or nil if there is no
16473 such entry. If narrowing is in effect, only search the visible
16474 part of the buffer."
16475 (save-excursion
16476 (goto-char (point-min))
16477 (let ((case-fold-search t)
16478 (re (org-re-property property nil (not value) value)))
16479 (catch 'exit
16480 (while (re-search-forward re nil t)
16481 (when (if value (org-at-property-p)
16482 (org-entry-get (point) property nil t))
16483 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16485 (defun org-delete-property (property)
16486 "In the current entry, delete PROPERTY."
16487 (interactive
16488 (let* ((completion-ignore-case t)
16489 (cat (org-entry-get (point) "CATEGORY"))
16490 (props0 (org-entry-properties nil 'standard))
16491 (props (if cat props0
16492 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16493 (prop (if (< 1 (length props))
16494 (completing-read "Property: " props nil t)
16495 (caar props))))
16496 (list prop)))
16497 (if (not property)
16498 (message "No property to delete in this entry")
16499 (org-entry-delete nil property)
16500 (message "Property \"%s\" deleted" property)))
16502 (defun org-delete-property-globally (property)
16503 "Remove PROPERTY globally, from all entries.
16504 This function ignores narrowing, if any."
16505 (interactive
16506 (let* ((completion-ignore-case t)
16507 (prop (completing-read
16508 "Globally remove property: "
16509 (mapcar #'list (org-buffer-property-keys)))))
16510 (list prop)))
16511 (org-with-wide-buffer
16512 (goto-char (point-min))
16513 (let ((count 0)
16514 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16515 (while (re-search-forward re nil t)
16516 (when (org-entry-delete (point) property) (cl-incf count)))
16517 (message "Property \"%s\" removed from %d entries" property count))))
16519 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16521 (defun org-compute-property-at-point ()
16522 "Compute the property at point.
16523 This looks for an enclosing column format, extracts the operator and
16524 then applies it to the property in the column format's scope."
16525 (interactive)
16526 (unless (org-at-property-p)
16527 (user-error "Not at a property"))
16528 (let ((prop (match-string-no-properties 2)))
16529 (org-columns-get-format-and-top-level)
16530 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16531 (user-error "No operator defined for property %s" prop))
16532 (org-columns-compute prop)))
16534 (defvar org-property-allowed-value-functions nil
16535 "Hook for functions supplying allowed values for a specific property.
16536 The functions must take a single argument, the name of the property, and
16537 return a flat list of allowed values. If \":ETC\" is one of
16538 the values, this means that these values are intended as defaults for
16539 completion, but that other values should be allowed too.
16540 The functions must return nil if they are not responsible for this
16541 property.")
16543 (defun org-property-get-allowed-values (pom property &optional table)
16544 "Get allowed values for the property PROPERTY.
16545 When TABLE is non-nil, return an alist that can directly be used for
16546 completion."
16547 (let (vals)
16548 (cond
16549 ((equal property "TODO")
16550 (setq vals (org-with-point-at pom
16551 (append org-todo-keywords-1 '("")))))
16552 ((equal property "PRIORITY")
16553 (let ((n org-lowest-priority))
16554 (while (>= n org-highest-priority)
16555 (push (char-to-string n) vals)
16556 (setq n (1- n)))))
16557 ((equal property "CATEGORY"))
16558 ((member property org-special-properties))
16559 ((setq vals (run-hook-with-args-until-success
16560 'org-property-allowed-value-functions property)))
16562 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16563 (when (and vals (string-match "\\S-" vals))
16564 (setq vals (car (read-from-string (concat "(" vals ")"))))
16565 (setq vals (mapcar (lambda (x)
16566 (cond ((stringp x) x)
16567 ((numberp x) (number-to-string x))
16568 ((symbolp x) (symbol-name x))
16569 (t "???")))
16570 vals)))))
16571 (when (member ":ETC" vals)
16572 (setq vals (remove ":ETC" vals))
16573 (org-add-props (car vals) '(org-unrestricted t)))
16574 (if table (mapcar 'list vals) vals)))
16576 (defun org-property-previous-allowed-value (&optional _previous)
16577 "Switch to the next allowed value for this property."
16578 (interactive)
16579 (org-property-next-allowed-value t))
16581 (defun org-property-next-allowed-value (&optional previous)
16582 "Switch to the next allowed value for this property."
16583 (interactive)
16584 (unless (org-at-property-p)
16585 (user-error "Not at a property"))
16586 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16587 (key (match-string 2))
16588 (value (match-string 3))
16589 (allowed (or (org-property-get-allowed-values (point) key)
16590 (and (member value '("[ ]" "[-]" "[X]"))
16591 '("[ ]" "[X]"))))
16592 (heading (save-match-data (nth 4 (org-heading-components))))
16593 nval)
16594 (unless allowed
16595 (user-error "Allowed values for this property have not been defined"))
16596 (when previous (setq allowed (reverse allowed)))
16597 (when (member value allowed)
16598 (setq nval (car (cdr (member value allowed)))))
16599 (setq nval (or nval (car allowed)))
16600 (when (equal nval value)
16601 (user-error "Only one allowed value for this property"))
16602 (org-at-property-p)
16603 (replace-match (concat " :" key ": " nval) t t)
16604 (org-indent-line)
16605 (beginning-of-line 1)
16606 (skip-chars-forward " \t")
16607 (when (equal prop org-effort-property)
16608 (org-refresh-property
16609 '((effort . identity)
16610 (effort-minutes . org-duration-string-to-minutes))
16611 nval)
16612 (when (string= org-clock-current-task heading)
16613 (setq org-clock-effort nval)
16614 (org-clock-update-mode-line)))
16615 (run-hook-with-args 'org-property-changed-functions key nval)))
16617 (defun org-find-olp (path &optional this-buffer)
16618 "Return a marker pointing to the entry at outline path OLP.
16619 If anything goes wrong, throw an error.
16620 You can wrap this call to catch the error like this:
16622 \(condition-case msg
16623 \(org-mobile-locate-entry (match-string 4))
16624 \(error (nth 1 msg)))
16626 The return value will then be either a string with the error message,
16627 or a marker if everything is OK.
16629 If THIS-BUFFER is set, the outline path does not contain a file,
16630 only headings."
16631 (let* ((file (if this-buffer buffer-file-name (pop path)))
16632 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16633 (level 1)
16634 (lmin 1)
16635 (lmax 1)
16636 end found flevel)
16637 (unless buffer (error "File not found :%s" file))
16638 (with-current-buffer buffer
16639 (org-with-wide-buffer
16640 (goto-char (point-min))
16641 (dolist (heading path)
16642 (let ((re (format org-complex-heading-regexp-format
16643 (regexp-quote heading)))
16644 (cnt 0))
16645 (while (re-search-forward re end t)
16646 (setq level (- (match-end 1) (match-beginning 1)))
16647 (when (and (>= level lmin) (<= level lmax))
16648 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16649 (when (= cnt 0)
16650 (error "Heading not found on level %d: %s" lmax heading))
16651 (when (> cnt 1)
16652 (error "Heading not unique on level %d: %s" lmax heading))
16653 (goto-char found)
16654 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16655 (setq end (save-excursion (org-end-of-subtree t t)))))
16656 (when (org-at-heading-p)
16657 (point-marker))))))
16659 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16660 "Find node HEADING in BUFFER.
16661 Return a marker to the heading if it was found, or nil if not.
16662 If POS-ONLY is set, return just the position instead of a marker.
16664 The heading text must match exact, but it may have a TODO keyword,
16665 a priority cookie and tags in the standard locations."
16666 (with-current-buffer (or buffer (current-buffer))
16667 (org-with-wide-buffer
16668 (goto-char (point-min))
16669 (let (case-fold-search)
16670 (when (re-search-forward
16671 (format org-complex-heading-regexp-format
16672 (regexp-quote heading)) nil t)
16673 (if pos-only
16674 (match-beginning 0)
16675 (move-marker (make-marker) (match-beginning 0))))))))
16677 (defun org-find-exact-heading-in-directory (heading &optional dir)
16678 "Find Org node headline HEADING in all .org files in directory DIR.
16679 When the target headline is found, return a marker to this location."
16680 (let ((files (directory-files (or dir default-directory)
16681 t "\\`[^.#].*\\.org\\'"))
16682 visiting m buffer)
16683 (catch 'found
16684 (dolist (file files)
16685 (message "trying %s" file)
16686 (setq visiting (org-find-base-buffer-visiting file))
16687 (setq buffer (or visiting (find-file-noselect file)))
16688 (setq m (org-find-exact-headline-in-buffer
16689 heading buffer))
16690 (when (and (not m) (not visiting)) (kill-buffer buffer))
16691 (and m (throw 'found m))))))
16693 (defun org-find-entry-with-id (ident)
16694 "Locate the entry that contains the ID property with exact value IDENT.
16695 IDENT can be a string, a symbol or a number, this function will search for
16696 the string representation of it.
16697 Return the position where this entry starts, or nil if there is no such entry."
16698 (interactive "sID: ")
16699 (let ((id (cond
16700 ((stringp ident) ident)
16701 ((symbolp ident) (symbol-name ident))
16702 ((numberp ident) (number-to-string ident))
16703 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16704 (org-with-wide-buffer (org-find-property "ID" id))))
16706 ;;;; Timestamps
16708 (defvar org-last-changed-timestamp nil)
16709 (defvar org-last-inserted-timestamp nil
16710 "The last time stamp inserted with `org-insert-time-stamp'.")
16711 (defvar org-ts-what) ; dynamically scoped parameter
16713 (defun org-time-stamp (arg &optional inactive)
16714 "Prompt for a date/time and insert a time stamp.
16716 If the user specifies a time like HH:MM or if this command is
16717 called with at least one prefix argument, the time stamp contains
16718 the date and the time. Otherwise, only the date is included.
16720 All parts of a date not specified by the user are filled in from
16721 the timestamp at point, if any, or the current date/time
16722 otherwise.
16724 If there is already a timestamp at the cursor, it is replaced.
16726 With two universal prefix arguments, insert an active timestamp
16727 with the current time without prompting the user.
16729 When called from lisp, the timestamp is inactive if INACTIVE is
16730 non-nil."
16731 (interactive "P")
16732 (let* ((ts (cond
16733 ((org-at-date-range-p t)
16734 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16735 ((org-at-timestamp-p t) (match-string 0))))
16736 ;; Default time is either the timestamp at point or today.
16737 ;; When entering a range, only the range start is considered.
16738 (default-time (if (not ts) (current-time)
16739 (apply #'encode-time (org-parse-time-string ts))))
16740 (default-input (and ts (org-get-compact-tod ts)))
16741 (repeater (and ts
16742 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16743 (match-string 0 ts)))
16744 org-time-was-given
16745 org-end-time-was-given
16746 (time
16747 (and (if (equal arg '(16)) (current-time)
16748 ;; Preserve `this-command' and `last-command'.
16749 (let ((this-command this-command)
16750 (last-command last-command))
16751 (org-read-date
16752 arg 'totime nil nil default-time default-input
16753 inactive))))))
16754 (cond
16755 ((and ts
16756 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16757 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16758 (insert "--")
16759 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16761 ;; Make sure we're on a timestamp. When in the middle of a date
16762 ;; range, move arbitrarily to range end.
16763 (unless (org-at-timestamp-p t)
16764 (skip-chars-forward "-")
16765 (org-at-timestamp-p t))
16766 (replace-match "")
16767 (setq org-last-changed-timestamp
16768 (org-insert-time-stamp
16769 time (or org-time-was-given arg)
16770 inactive nil nil (list org-end-time-was-given)))
16771 (when repeater
16772 (backward-char)
16773 (insert " " repeater)
16774 (setq org-last-changed-timestamp
16775 (concat (substring org-last-inserted-timestamp 0 -1)
16776 " " repeater ">")))
16777 (message "Timestamp updated"))
16778 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16779 (t (org-insert-time-stamp
16780 time (or org-time-was-given arg) inactive nil nil
16781 (list org-end-time-was-given))))))
16783 ;; FIXME: can we use this for something else, like computing time differences?
16784 (defun org-get-compact-tod (s)
16785 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16786 (let* ((t1 (match-string 1 s))
16787 (h1 (string-to-number (match-string 2 s)))
16788 (m1 (string-to-number (match-string 3 s)))
16789 (t2 (and (match-end 4) (match-string 5 s)))
16790 (h2 (and t2 (string-to-number (match-string 6 s))))
16791 (m2 (and t2 (string-to-number (match-string 7 s))))
16792 dh dm)
16793 (if (not t2)
16795 (setq dh (- h2 h1) dm (- m2 m1))
16796 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16797 (concat t1 "+" (number-to-string dh)
16798 (and (/= 0 dm) (format ":%02d" dm)))))))
16800 (defun org-time-stamp-inactive (&optional arg)
16801 "Insert an inactive time stamp.
16802 An inactive time stamp is enclosed in square brackets instead of angle
16803 brackets. It is inactive in the sense that it does not trigger agenda entries,
16804 does not link to the calendar and cannot be changed with the S-cursor keys.
16805 So these are more for recording a certain time/date."
16806 (interactive "P")
16807 (org-time-stamp arg 'inactive))
16809 (defvar org-date-ovl (make-overlay 1 1))
16810 (overlay-put org-date-ovl 'face 'org-date-selected)
16811 (delete-overlay org-date-ovl)
16813 (defvar org-ans1) ; dynamically scoped parameter
16814 (defvar org-ans2) ; dynamically scoped parameter
16816 (defvar org-plain-time-of-day-regexp) ; defined below
16818 (defvar org-overriding-default-time nil) ; dynamically scoped
16819 (defvar org-read-date-overlay nil)
16820 (defvar org-dcst nil) ; dynamically scoped
16821 (defvar org-read-date-history nil)
16822 (defvar org-read-date-final-answer nil)
16823 (defvar org-read-date-analyze-futurep nil)
16824 (defvar org-read-date-analyze-forced-year nil)
16825 (defvar org-read-date-inactive)
16827 (defvar org-read-date-minibuffer-local-map
16828 (let* ((map (make-sparse-keymap)))
16829 (set-keymap-parent map minibuffer-local-map)
16830 (org-defkey map (kbd ".")
16831 (lambda () (interactive)
16832 ;; Are we at the beginning of the prompt?
16833 (if (looking-back "^[^:]+: "
16834 (let ((inhibit-field-text-motion t))
16835 (line-beginning-position)))
16836 (org-eval-in-calendar '(calendar-goto-today))
16837 (insert "."))))
16838 (org-defkey map (kbd "C-.")
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-goto-today))))
16841 (org-defkey map [(meta shift left)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-backward-month 1))))
16844 (org-defkey map [(meta shift right)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-forward-month 1))))
16847 (org-defkey map [(meta shift up)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-backward-year 1))))
16850 (org-defkey map [(meta shift down)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-forward-year 1))))
16853 (org-defkey map [?\e (shift left)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-backward-month 1))))
16856 (org-defkey map [?\e (shift right)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-forward-month 1))))
16859 (org-defkey map [?\e (shift up)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-backward-year 1))))
16862 (org-defkey map [?\e (shift down)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-forward-year 1))))
16865 (org-defkey map [(shift up)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-backward-week 1))))
16868 (org-defkey map [(shift down)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-forward-week 1))))
16871 (org-defkey map [(shift left)]
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-backward-day 1))))
16874 (org-defkey map [(shift right)]
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(calendar-forward-day 1))))
16877 (org-defkey map "!"
16878 (lambda () (interactive)
16879 (org-eval-in-calendar '(diary-view-entries))
16880 (message "")))
16881 (org-defkey map ">"
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-scroll-left 1))))
16884 (org-defkey map "<"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-scroll-right 1))))
16887 (org-defkey map "\C-v"
16888 (lambda () (interactive)
16889 (org-eval-in-calendar
16890 '(calendar-scroll-left-three-months 1))))
16891 (org-defkey map "\M-v"
16892 (lambda () (interactive)
16893 (org-eval-in-calendar
16894 '(calendar-scroll-right-three-months 1))))
16895 map)
16896 "Keymap for minibuffer commands when using `org-read-date'.")
16898 (defvar org-def)
16899 (defvar org-defdecode)
16900 (defvar org-with-time)
16902 (defvar calendar-setup) ; Dynamically scoped.
16903 (defun org-read-date (&optional with-time to-time from-string prompt
16904 default-time default-input inactive)
16905 "Read a date, possibly a time, and make things smooth for the user.
16906 The prompt will suggest to enter an ISO date, but you can also enter anything
16907 which will at least partially be understood by `parse-time-string'.
16908 Unrecognized parts of the date will default to the current day, month, year,
16909 hour and minute. If this command is called to replace a timestamp at point,
16910 or to enter the second timestamp of a range, the default time is taken
16911 from the existing stamp. Furthermore, the command prefers the future,
16912 so if you are giving a date where the year is not given, and the day-month
16913 combination is already past in the current year, it will assume you
16914 mean next year. For details, see the manual. A few examples:
16916 3-2-5 --> 2003-02-05
16917 feb 15 --> currentyear-02-15
16918 2/15 --> currentyear-02-15
16919 sep 12 9 --> 2009-09-12
16920 12:45 --> today 12:45
16921 22 sept 0:34 --> currentyear-09-22 0:34
16922 12 --> currentyear-currentmonth-12
16923 Fri --> nearest Friday after today
16924 -Tue --> last Tuesday
16925 etc.
16927 Furthermore you can specify a relative date by giving, as the *first* thing
16928 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16929 change in days weeks, months, years.
16930 With a single plus or minus, the date is relative to today. With a double
16931 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16932 +4d --> four days from today
16933 +4 --> same as above
16934 +2w --> two weeks from today
16935 ++5 --> five days from default date
16937 The function understands only English month and weekday abbreviations.
16939 While prompting, a calendar is popped up - you can also select the
16940 date with the mouse (button 1). The calendar shows a period of three
16941 months. To scroll it to other months, use the keys `>' and `<'.
16942 If you don't like the calendar, turn it off with
16943 (setq org-read-date-popup-calendar nil)
16945 With optional argument TO-TIME, the date will immediately be converted
16946 to an internal time.
16947 With an optional argument WITH-TIME, the prompt will suggest to
16948 also insert a time. Note that when WITH-TIME is not set, you can
16949 still enter a time, and this function will inform the calling routine
16950 about this change. The calling routine may then choose to change the
16951 format used to insert the time stamp into the buffer to include the time.
16952 With optional argument FROM-STRING, read from this string instead from
16953 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16954 the time/date that is used for everything that is not specified by the
16955 user."
16956 (require 'parse-time)
16957 (let* ((org-with-time with-time)
16958 (org-time-stamp-rounding-minutes
16959 (if (equal org-with-time '(16))
16960 '(0 0)
16961 org-time-stamp-rounding-minutes))
16962 (org-dcst org-display-custom-times)
16963 (ct (org-current-time))
16964 (org-def (or org-overriding-default-time default-time ct))
16965 (org-defdecode (decode-time org-def))
16966 (cur-frame (selected-frame))
16967 (mouse-autoselect-window nil) ; Don't let the mouse jump
16968 (calendar-setup
16969 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16970 (calendar-move-hook nil)
16971 (calendar-view-diary-initially-flag nil)
16972 (calendar-view-holidays-initially-flag nil)
16973 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16974 ;; Rationalize `org-def' and `org-defdecode', if required.
16975 (when (< (nth 2 org-defdecode) org-extend-today-until)
16976 (setf (nth 2 org-defdecode) -1)
16977 (setf (nth 1 org-defdecode) 59)
16978 (setq org-def (apply #'encode-time org-defdecode))
16979 (setq org-defdecode (decode-time org-def)))
16980 (let* ((timestr (format-time-string
16981 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16982 org-def))
16983 (prompt (concat (if prompt (concat prompt " ") "")
16984 (format "Date+time [%s]: " timestr))))
16985 (cond
16986 (from-string (setq ans from-string))
16987 (org-read-date-popup-calendar
16988 (save-excursion
16989 (save-window-excursion
16990 (calendar)
16991 (when (eq calendar-setup 'calendar-only)
16992 (setq cal-frame
16993 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16994 (select-frame cal-frame))
16995 (org-eval-in-calendar '(setq cursor-type nil) t)
16996 (unwind-protect
16997 (progn
16998 (calendar-forward-day (- (time-to-days org-def)
16999 (calendar-absolute-from-gregorian
17000 (calendar-current-date))))
17001 (org-eval-in-calendar nil t)
17002 (let* ((old-map (current-local-map))
17003 (map (copy-keymap calendar-mode-map))
17004 (minibuffer-local-map
17005 (copy-keymap org-read-date-minibuffer-local-map)))
17006 (org-defkey map (kbd "RET") 'org-calendar-select)
17007 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17008 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17009 (unwind-protect
17010 (progn
17011 (use-local-map map)
17012 (setq org-read-date-inactive inactive)
17013 (add-hook 'post-command-hook 'org-read-date-display)
17014 (setq org-ans0
17015 (read-string prompt
17016 default-input
17017 'org-read-date-history
17018 nil))
17019 ;; org-ans0: from prompt
17020 ;; org-ans1: from mouse click
17021 ;; org-ans2: from calendar motion
17022 (setq ans
17023 (concat org-ans0 " " (or org-ans1 org-ans2))))
17024 (remove-hook 'post-command-hook 'org-read-date-display)
17025 (use-local-map old-map)
17026 (when org-read-date-overlay
17027 (delete-overlay org-read-date-overlay)
17028 (setq org-read-date-overlay nil)))))
17029 (bury-buffer "*Calendar*")
17030 (when cal-frame
17031 (delete-frame cal-frame)
17032 (select-frame-set-input-focus cur-frame))))))
17034 (t ; Naked prompt only
17035 (unwind-protect
17036 (setq ans (read-string prompt default-input
17037 'org-read-date-history timestr))
17038 (when org-read-date-overlay
17039 (delete-overlay org-read-date-overlay)
17040 (setq org-read-date-overlay nil))))))
17042 (setq final (org-read-date-analyze ans org-def org-defdecode))
17044 (when org-read-date-analyze-forced-year
17045 (message "Year was forced into %s"
17046 (if org-read-date-force-compatible-dates
17047 "compatible range (1970-2037)"
17048 "range representable on this machine"))
17049 (ding))
17051 ;; One round trip to get rid of 34th of August and stuff like that....
17052 (setq final (decode-time (apply 'encode-time final)))
17054 (setq org-read-date-final-answer ans)
17056 (if to-time
17057 (apply 'encode-time final)
17058 (if (and (boundp 'org-time-was-given) org-time-was-given)
17059 (format "%04d-%02d-%02d %02d:%02d"
17060 (nth 5 final) (nth 4 final) (nth 3 final)
17061 (nth 2 final) (nth 1 final))
17062 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17064 (defun org-read-date-display ()
17065 "Display the current date prompt interpretation in the minibuffer."
17066 (when org-read-date-display-live
17067 (when org-read-date-overlay
17068 (delete-overlay org-read-date-overlay))
17069 (when (minibufferp (current-buffer))
17070 (save-excursion
17071 (end-of-line 1)
17072 (while (not (equal (buffer-substring
17073 (max (point-min) (- (point) 4)) (point))
17074 " "))
17075 (insert " ")))
17076 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17077 " " (or org-ans1 org-ans2)))
17078 (org-end-time-was-given nil)
17079 (f (org-read-date-analyze ans org-def org-defdecode))
17080 (fmts (if org-dcst
17081 org-time-stamp-custom-formats
17082 org-time-stamp-formats))
17083 (fmt (if (or org-with-time
17084 (and (boundp 'org-time-was-given) org-time-was-given))
17085 (cdr fmts)
17086 (car fmts)))
17087 (txt (format-time-string fmt (apply 'encode-time f)))
17088 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17089 (txt (concat "=> " txt)))
17090 (when (and org-end-time-was-given
17091 (string-match org-plain-time-of-day-regexp txt))
17092 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17093 org-end-time-was-given
17094 (substring txt (match-end 0)))))
17095 (when org-read-date-analyze-futurep
17096 (setq txt (concat txt " (=>F)")))
17097 (setq org-read-date-overlay
17098 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17099 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17101 (defun org-read-date-analyze (ans def defdecode)
17102 "Analyze the combined answer of the date prompt."
17103 ;; FIXME: cleanup and comment
17104 ;; Pass `current-time' result to `decode-time' (instead of calling
17105 ;; without arguments) so that only `current-time' has to be
17106 ;; overriden in tests.
17107 (let ((org-def def)
17108 (org-defdecode defdecode)
17109 (nowdecode (decode-time (current-time)))
17110 delta deltan deltaw deltadef year month day
17111 hour minute second wday pm h2 m2 tl wday1
17112 iso-year iso-weekday iso-week iso-date futurep kill-year)
17113 (setq org-read-date-analyze-futurep nil
17114 org-read-date-analyze-forced-year nil)
17115 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17116 (setq ans "+0"))
17118 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17119 (setq ans (replace-match "" t t ans)
17120 deltan (car delta)
17121 deltaw (nth 1 delta)
17122 deltadef (nth 2 delta)))
17124 ;; Check if there is an iso week date in there. If yes, store the
17125 ;; info and postpone interpreting it until the rest of the parsing
17126 ;; is done.
17127 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17128 (setq iso-year (when (match-end 1)
17129 (org-small-year-to-year
17130 (string-to-number (match-string 1 ans))))
17131 iso-weekday (when (match-end 3)
17132 (string-to-number (match-string 3 ans)))
17133 iso-week (string-to-number (match-string 2 ans)))
17134 (setq ans (replace-match "" t t ans)))
17136 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17137 (when (string-match
17138 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17139 (setq year (if (match-end 2)
17140 (string-to-number (match-string 2 ans))
17141 (progn (setq kill-year t)
17142 (string-to-number (format-time-string "%Y"))))
17143 month (string-to-number (match-string 3 ans))
17144 day (string-to-number (match-string 4 ans)))
17145 (setq year (org-small-year-to-year year))
17146 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17147 t nil ans)))
17149 ;; Help matching dotted european dates
17150 (when (string-match
17151 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17152 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17153 (setq kill-year t)
17154 (string-to-number (format-time-string "%Y")))
17155 day (string-to-number (match-string 1 ans))
17156 month (string-to-number (match-string 2 ans))
17157 ans (replace-match (format "%04d-%02d-%02d" year month day)
17158 t nil ans)))
17160 ;; Help matching american dates, like 5/30 or 5/30/7
17161 (when (string-match
17162 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17163 (setq year (if (match-end 4)
17164 (string-to-number (match-string 4 ans))
17165 (progn (setq kill-year t)
17166 (string-to-number (format-time-string "%Y"))))
17167 month (string-to-number (match-string 1 ans))
17168 day (string-to-number (match-string 2 ans)))
17169 (setq year (org-small-year-to-year year))
17170 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17171 t nil ans)))
17172 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17173 ;; If there is a time with am/pm, and *no* time without it, we convert
17174 ;; so that matching will be successful.
17175 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17176 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17177 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17178 (setq hour (string-to-number (match-string 1 ans))
17179 minute (if (match-end 3)
17180 (string-to-number (match-string 3 ans))
17182 pm (equal ?p
17183 (string-to-char (downcase (match-string 4 ans)))))
17184 (if (and (= hour 12) (not pm))
17185 (setq hour 0)
17186 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17187 (setq ans (replace-match (format "%02d:%02d" hour minute)
17188 t t ans))))
17190 ;; Check if a time range is given as a duration
17191 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17192 (setq hour (string-to-number (match-string 1 ans))
17193 h2 (+ hour (string-to-number (match-string 3 ans)))
17194 minute (string-to-number (match-string 2 ans))
17195 m2 (+ minute (if (match-end 5) (string-to-number
17196 (match-string 5 ans))0)))
17197 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17198 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17199 t t ans)))
17201 ;; Check if there is a time range
17202 (when (boundp 'org-end-time-was-given)
17203 (setq org-time-was-given nil)
17204 (when (and (string-match org-plain-time-of-day-regexp ans)
17205 (match-end 8))
17206 (setq org-end-time-was-given (match-string 8 ans))
17207 (setq ans (concat (substring ans 0 (match-beginning 7))
17208 (substring ans (match-end 7))))))
17210 (setq tl (parse-time-string ans)
17211 day (or (nth 3 tl) (nth 3 org-defdecode))
17212 month
17213 (cond ((nth 4 tl))
17214 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17215 ;; Day was specified. Make sure DAY+MONTH
17216 ;; combination happens in the future.
17217 ((nth 3 tl)
17218 (setq futurep t)
17219 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17220 (nth 4 nowdecode)))
17221 (t (nth 4 org-defdecode)))
17222 year
17223 (cond ((and (not kill-year) (nth 5 tl)))
17224 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17225 ;; Month was guessed in the future and is at least
17226 ;; equal to NOWDECODE's. Fix year accordingly.
17227 (futurep
17228 (if (or (> month (nth 4 nowdecode))
17229 (>= day (nth 3 nowdecode)))
17230 (nth 5 nowdecode)
17231 (1+ (nth 5 nowdecode))))
17232 ;; Month was specified. Make sure MONTH+YEAR
17233 ;; combination happens in the future.
17234 ((nth 4 tl)
17235 (setq futurep t)
17236 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17237 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17238 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17239 (t (nth 5 nowdecode))))
17240 (t (nth 5 org-defdecode)))
17241 hour (or (nth 2 tl) (nth 2 org-defdecode))
17242 minute (or (nth 1 tl) (nth 1 org-defdecode))
17243 second (or (nth 0 tl) 0)
17244 wday (nth 6 tl))
17246 (when (and (eq org-read-date-prefer-future 'time)
17247 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17248 (equal day (nth 3 nowdecode))
17249 (equal month (nth 4 nowdecode))
17250 (equal year (nth 5 nowdecode))
17251 (nth 2 tl)
17252 (or (< (nth 2 tl) (nth 2 nowdecode))
17253 (and (= (nth 2 tl) (nth 2 nowdecode))
17254 (nth 1 tl)
17255 (< (nth 1 tl) (nth 1 nowdecode)))))
17256 (setq day (1+ day)
17257 futurep t))
17259 ;; Special date definitions below
17260 (cond
17261 (iso-week
17262 ;; There was an iso week
17263 (require 'cal-iso)
17264 (setq futurep nil)
17265 (setq year (or iso-year year)
17266 day (or iso-weekday wday 1)
17267 wday nil ; to make sure that the trigger below does not match
17268 iso-date (calendar-gregorian-from-absolute
17269 (calendar-iso-to-absolute
17270 (list iso-week day year))))
17271 ; FIXME: Should we also push ISO weeks into the future?
17272 ; (when (and org-read-date-prefer-future
17273 ; (not iso-year)
17274 ; (< (calendar-absolute-from-gregorian iso-date)
17275 ; (time-to-days (current-time))))
17276 ; (setq year (1+ year)
17277 ; iso-date (calendar-gregorian-from-absolute
17278 ; (calendar-iso-to-absolute
17279 ; (list iso-week day year)))))
17280 (setq month (car iso-date)
17281 year (nth 2 iso-date)
17282 day (nth 1 iso-date)))
17283 (deltan
17284 (setq futurep nil)
17285 (unless deltadef
17286 ;; Pass `current-time' result to `decode-time' (instead of
17287 ;; calling without arguments) so that only `current-time' has
17288 ;; to be overriden in tests.
17289 (let ((now (decode-time (current-time))))
17290 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17291 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17292 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17293 ((equal deltaw "m") (setq month (+ month deltan)))
17294 ((equal deltaw "y") (setq year (+ year deltan)))))
17295 ((and wday (not (nth 3 tl)))
17296 ;; Weekday was given, but no day, so pick that day in the week
17297 ;; on or after the derived date.
17298 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17299 (unless (equal wday wday1)
17300 (setq day (+ day (% (- wday wday1 -7) 7))))))
17301 (when (and (boundp 'org-time-was-given)
17302 (nth 2 tl))
17303 (setq org-time-was-given t))
17304 (when (< year 100) (setq year (+ 2000 year)))
17305 ;; Check of the date is representable
17306 (if org-read-date-force-compatible-dates
17307 (progn
17308 (when (< year 1970)
17309 (setq year 1970 org-read-date-analyze-forced-year t))
17310 (when (> year 2037)
17311 (setq year 2037 org-read-date-analyze-forced-year t)))
17312 (condition-case nil
17313 (ignore (encode-time second minute hour day month year))
17314 (error
17315 (setq year (nth 5 org-defdecode))
17316 (setq org-read-date-analyze-forced-year t))))
17317 (setq org-read-date-analyze-futurep futurep)
17318 (list second minute hour day month year)))
17320 (defvar parse-time-weekdays)
17321 (defun org-read-date-get-relative (s today default)
17322 "Check string S for special relative date string.
17323 TODAY and DEFAULT are internal times, for today and for a default.
17324 Return shift list (N what def-flag)
17325 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17326 N is the number of WHATs to shift.
17327 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17328 the DEFAULT date rather than TODAY."
17329 (require 'parse-time)
17330 (when (and
17331 (string-match
17332 (concat
17333 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17334 "\\([0-9]+\\)?"
17335 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17336 "\\([ \t]\\|$\\)") s)
17337 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17338 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17339 (string-to-char (substring (match-string 1 s) -1))
17340 ?+))
17341 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17342 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17343 (what (if (match-end 3) (match-string 3 s) "d"))
17344 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17345 (date (if rel default today))
17346 (wday (nth 6 (decode-time date)))
17347 delta)
17348 (if wday1
17349 (progn
17350 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17351 (when (= delta 0) (setq delta 7))
17352 (when (= dir ?-)
17353 (setq delta (- delta 7))
17354 (when (= delta 0) (setq delta -7)))
17355 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17356 (list delta "d" rel))
17357 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17359 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17360 "Turn a user-specified date into the internal representation.
17361 The internal representation needed by the calendar is (month day year).
17362 This is a wrapper to handle the brain-dead convention in calendar that
17363 user function argument order change dependent on argument order."
17364 (pcase calendar-date-style
17365 (`american (list arg1 arg2 arg3))
17366 (`european (list arg2 arg1 arg3))
17367 (`iso (list arg2 arg3 arg1))))
17369 (defun org-eval-in-calendar (form &optional keepdate)
17370 "Eval FORM in the calendar window and return to current window.
17371 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17372 (let ((sf (selected-frame))
17373 (sw (selected-window)))
17374 (select-window (get-buffer-window "*Calendar*" t))
17375 (eval form)
17376 (when (and (not keepdate) (calendar-cursor-to-date))
17377 (let* ((date (calendar-cursor-to-date))
17378 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17379 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17380 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17381 (select-window sw)
17382 (select-frame-set-input-focus sf)))
17384 (defun org-calendar-select ()
17385 "Return to `org-read-date' with the date currently selected.
17386 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17387 (interactive)
17388 (when (calendar-cursor-to-date)
17389 (let* ((date (calendar-cursor-to-date))
17390 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17391 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17392 (when (active-minibuffer-window) (exit-minibuffer))))
17394 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17395 "Insert a date stamp for the date given by the internal TIME.
17396 See `format-time-string' for the format of TIME.
17397 WITH-HM means use the stamp format that includes the time of the day.
17398 INACTIVE means use square brackets instead of angular ones, so that the
17399 stamp will not contribute to the agenda.
17400 PRE and POST are optional strings to be inserted before and after the
17401 stamp.
17402 The command returns the inserted time stamp."
17403 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17404 stamp)
17405 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17406 (insert-before-markers (or pre ""))
17407 (when (listp extra)
17408 (setq extra (car extra))
17409 (if (and (stringp extra)
17410 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17411 (setq extra (format "-%02d:%02d"
17412 (string-to-number (match-string 1 extra))
17413 (string-to-number (match-string 2 extra))))
17414 (setq extra nil)))
17415 (when extra
17416 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17417 (insert-before-markers (setq stamp (format-time-string fmt time)))
17418 (insert-before-markers (or post ""))
17419 (setq org-last-inserted-timestamp stamp)))
17421 (defun org-toggle-time-stamp-overlays ()
17422 "Toggle the use of custom time stamp formats."
17423 (interactive)
17424 (setq org-display-custom-times (not org-display-custom-times))
17425 (unless org-display-custom-times
17426 (let ((p (point-min)) (bmp (buffer-modified-p)))
17427 (while (setq p (next-single-property-change p 'display))
17428 (when (and (get-text-property p 'display)
17429 (eq (get-text-property p 'face) 'org-date))
17430 (remove-text-properties
17431 p (setq p (next-single-property-change p 'display))
17432 '(display t))))
17433 (set-buffer-modified-p bmp)))
17434 (org-restart-font-lock)
17435 (setq org-table-may-need-update t)
17436 (if org-display-custom-times
17437 (message "Time stamps are overlaid with custom format")
17438 (message "Time stamp overlays removed")))
17440 (defun org-display-custom-time (beg end)
17441 "Overlay modified time stamp format over timestamp between BEG and END."
17442 (let* ((ts (buffer-substring beg end))
17443 t1 w1 with-hm tf time str w2 (off 0))
17444 (save-match-data
17445 (setq t1 (org-parse-time-string ts t))
17446 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17447 (setq off (- (match-end 0) (match-beginning 0)))))
17448 (setq end (- end off))
17449 (setq w1 (- end beg)
17450 with-hm (and (nth 1 t1) (nth 2 t1))
17451 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17452 time (org-fix-decoded-time t1)
17453 str (org-add-props
17454 (format-time-string
17455 (substring tf 1 -1) (apply 'encode-time time))
17456 nil 'mouse-face 'highlight)
17457 w2 (length str))
17458 (unless (= w2 w1)
17459 (add-text-properties (1+ beg) (+ 2 beg)
17460 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17461 (put-text-property beg end 'display str)))
17463 (defun org-fix-decoded-time (time)
17464 "Set 0 instead of nil for the first 6 elements of time.
17465 Don't touch the rest."
17466 (let ((n 0))
17467 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17469 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17470 "Difference between TIMESTAMP-STRING and now in days.
17471 If SECONDS is non-nil, return the difference in seconds."
17472 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17473 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17474 (funcall fdiff (current-time)))))
17476 (defun org-deadline-close-p (timestamp-string &optional ndays)
17477 "Is the time in TIMESTAMP-STRING close to the current date?"
17478 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17479 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17480 (not (org-entry-is-done-p))))
17482 (defun org-get-wdays (ts &optional delay zero-delay)
17483 "Get the deadline lead time appropriate for timestring TS.
17484 When DELAY is non-nil, get the delay time for scheduled items
17485 instead of the deadline lead time. When ZERO-DELAY is non-nil
17486 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17487 don't try to find the delay cookie in the scheduled timestamp."
17488 (let ((tv (if delay org-scheduled-delay-days
17489 org-deadline-warning-days)))
17490 (cond
17491 ((or (and delay (< tv 0))
17492 (and delay zero-delay (<= tv 0))
17493 (and (not delay) (<= tv 0)))
17494 ;; Enforce this value no matter what
17495 (- tv))
17496 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17497 ;; lead time is specified.
17498 (floor (* (string-to-number (match-string 1 ts))
17499 (cdr (assoc (match-string 2 ts)
17500 '(("d" . 1) ("w" . 7)
17501 ("m" . 30.4) ("y" . 365.25)
17502 ("h" . 0.041667)))))))
17503 ;; go for the default.
17504 (t tv))))
17506 (defun org-calendar-select-mouse (ev)
17507 "Return to `org-read-date' with the date currently selected.
17508 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17509 (interactive "e")
17510 (mouse-set-point ev)
17511 (when (calendar-cursor-to-date)
17512 (let* ((date (calendar-cursor-to-date))
17513 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17514 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17515 (when (active-minibuffer-window) (exit-minibuffer))))
17517 (defun org-check-deadlines (ndays)
17518 "Check if there are any deadlines due or past due.
17519 A deadline is considered due if it happens within `org-deadline-warning-days'
17520 days from today's date. If the deadline appears in an entry marked DONE,
17521 it is not shown. The prefix arg NDAYS can be used to test that many
17522 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17523 (interactive "P")
17524 (let* ((org-warn-days
17525 (cond
17526 ((equal ndays '(4)) 100000)
17527 (ndays (prefix-numeric-value ndays))
17528 (t (abs org-deadline-warning-days))))
17529 (case-fold-search nil)
17530 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17531 (callback
17532 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17533 (message "%d deadlines past-due or due within %d days"
17534 (org-occur regexp nil callback)
17535 org-warn-days)))
17537 (defsubst org-re-timestamp (type)
17538 "Return a regexp for timestamp TYPE.
17539 Allowed values for TYPE are:
17541 all: all timestamps
17542 active: only active timestamps (<...>)
17543 inactive: only inactive timestamps ([...])
17544 scheduled: only scheduled timestamps
17545 deadline: only deadline timestamps
17546 closed: only closed time-stamps
17548 When TYPE is nil, fall back on returning a regexp that matches
17549 both scheduled and deadline timestamps."
17550 (cl-case type
17551 (all org-ts-regexp-both)
17552 (active org-ts-regexp)
17553 (inactive org-ts-regexp-inactive)
17554 (scheduled org-scheduled-time-regexp)
17555 (deadline org-deadline-time-regexp)
17556 (closed org-closed-time-regexp)
17557 (otherwise
17558 (concat "\\<"
17559 (regexp-opt (list org-deadline-string org-scheduled-string))
17560 " *<\\([^>]+\\)>"))))
17562 (defun org-check-before-date (d)
17563 "Check if there are deadlines or scheduled entries before date D."
17564 (interactive (list (org-read-date)))
17565 (let* ((case-fold-search nil)
17566 (regexp (org-re-timestamp org-ts-type))
17567 (ts-type org-ts-type)
17568 (callback
17569 (lambda ()
17570 (let ((match (match-string 1)))
17571 (and (if (memq ts-type '(active inactive all))
17572 (eq (org-element-type (save-excursion
17573 (backward-char)
17574 (org-element-context)))
17575 'timestamp)
17576 (org-at-planning-p))
17577 (time-less-p
17578 (org-time-string-to-time match)
17579 (org-time-string-to-time d)))))))
17580 (message "%d entries before %s"
17581 (org-occur regexp nil callback)
17582 d)))
17584 (defun org-check-after-date (d)
17585 "Check if there are deadlines or scheduled entries after date D."
17586 (interactive (list (org-read-date)))
17587 (let* ((case-fold-search nil)
17588 (regexp (org-re-timestamp org-ts-type))
17589 (ts-type org-ts-type)
17590 (callback
17591 (lambda ()
17592 (let ((match (match-string 1)))
17593 (and (if (memq ts-type '(active inactive all))
17594 (eq (org-element-type (save-excursion
17595 (backward-char)
17596 (org-element-context)))
17597 'timestamp)
17598 (org-at-planning-p))
17599 (not (time-less-p
17600 (org-time-string-to-time match)
17601 (org-time-string-to-time d))))))))
17602 (message "%d entries after %s"
17603 (org-occur regexp nil callback)
17604 d)))
17606 (defun org-check-dates-range (start-date end-date)
17607 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17608 (interactive (list (org-read-date nil nil nil "Range starts")
17609 (org-read-date nil nil nil "Range end")))
17610 (let ((case-fold-search nil)
17611 (regexp (org-re-timestamp org-ts-type))
17612 (callback
17613 (let ((type org-ts-type))
17614 (lambda ()
17615 (let ((match (match-string 1)))
17616 (and
17617 (if (memq type '(active inactive all))
17618 (eq (org-element-type (save-excursion
17619 (backward-char)
17620 (org-element-context)))
17621 'timestamp)
17622 (org-at-planning-p))
17623 (not (time-less-p
17624 (org-time-string-to-time match)
17625 (org-time-string-to-time start-date)))
17626 (time-less-p
17627 (org-time-string-to-time match)
17628 (org-time-string-to-time end-date))))))))
17629 (message "%d entries between %s and %s"
17630 (org-occur regexp nil callback) start-date end-date)))
17632 (defun org-evaluate-time-range (&optional to-buffer)
17633 "Evaluate a time range by computing the difference between start and end.
17634 Normally the result is just printed in the echo area, but with prefix arg
17635 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17636 If the time range is actually in a table, the result is inserted into the
17637 next column.
17638 For time difference computation, a year is assumed to be exactly 365
17639 days in order to avoid rounding problems."
17640 (interactive "P")
17642 (org-clock-update-time-maybe)
17643 (save-excursion
17644 (unless (org-at-date-range-p t)
17645 (goto-char (point-at-bol))
17646 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17647 (unless (org-at-date-range-p t)
17648 (user-error "Not at a time-stamp range, and none found in current line")))
17649 (let* ((ts1 (match-string 1))
17650 (ts2 (match-string 2))
17651 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17652 (match-end (match-end 0))
17653 (time1 (org-time-string-to-time ts1))
17654 (time2 (org-time-string-to-time ts2))
17655 (t1 (float-time time1))
17656 (t2 (float-time time2))
17657 (diff (abs (- t2 t1)))
17658 (negative (< (- t2 t1) 0))
17659 ;; (ys (floor (* 365 24 60 60)))
17660 (ds (* 24 60 60))
17661 (hs (* 60 60))
17662 (fy "%dy %dd %02d:%02d")
17663 (fy1 "%dy %dd")
17664 (fd "%dd %02d:%02d")
17665 (fd1 "%dd")
17666 (fh "%02d:%02d")
17667 y d h m align)
17668 (if havetime
17669 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17671 d (floor (/ diff ds)) diff (mod diff ds)
17672 h (floor (/ diff hs)) diff (mod diff hs)
17673 m (floor (/ diff 60)))
17674 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17676 d (floor (+ (/ diff ds) 0.5))
17677 h 0 m 0))
17678 (if (not to-buffer)
17679 (message "%s" (org-make-tdiff-string y d h m))
17680 (if (org-at-table-p)
17681 (progn
17682 (goto-char match-end)
17683 (setq align t)
17684 (and (looking-at " *|") (goto-char (match-end 0))))
17685 (goto-char match-end))
17686 (when (looking-at
17687 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17688 (replace-match ""))
17689 (when negative (insert " -"))
17690 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17691 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17692 (insert " " (format fh h m))))
17693 (when align (org-table-align))
17694 (message "Time difference inserted")))))
17696 (defun org-make-tdiff-string (y d h m)
17697 (let ((fmt "")
17698 (l nil))
17699 (when (> y 0)
17700 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17701 (push y l))
17702 (when (> d 0)
17703 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17704 (push d l))
17705 (when (> h 0)
17706 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17707 (push h l))
17708 (when (> m 0)
17709 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17710 (push m l))
17711 (apply 'format fmt (nreverse l))))
17713 (defun org-time-string-to-time (s &optional buffer pos)
17714 "Convert a timestamp string into internal time."
17715 (condition-case errdata
17716 (apply 'encode-time (org-parse-time-string s))
17717 (error (error "Bad timestamp `%s'%s\nError was: %s"
17718 s (if (not (and buffer pos))
17720 (format-message " at %d in buffer `%s'" pos buffer))
17721 (cdr errdata)))))
17723 (defun org-time-string-to-seconds (s)
17724 "Convert a timestamp string to a number of seconds."
17725 (float-time (org-time-string-to-time s)))
17727 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17729 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17730 "Convert time stamp S to an absolute day number.
17732 If DAYNR in non-nil, and there is a specifier for a cyclic time
17733 stamp, get the closest date to DAYNR. If PREFER is
17734 `past' (respectively `future') return a date past (respectively
17735 after) or equal to DAYNR.
17737 POS is the location of time stamp S, as a buffer position in
17738 BUFFER.
17740 Diary sexp timestamps are matched against DAYNR, when non-nil.
17741 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17742 signalled."
17743 (cond
17744 ((string-match "\\`%%\\((.*)\\)" s)
17745 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17746 ;; only able to match individual dates. If it fails, raise an
17747 ;; error.
17748 (if (and daynr
17749 (org-diary-sexp-entry
17750 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17751 daynr
17752 (signal 'org-diary-sexp-no-match (list s))))
17753 ((and daynr show-all) (org-closest-date s daynr prefer))
17754 (t (time-to-days
17755 (condition-case errdata
17756 (apply #'encode-time (org-parse-time-string s))
17757 (error (error "Bad timestamp `%s'%s\nError was: %s"
17759 (if (not (and buffer pos)) ""
17760 (format-message " at %d in buffer `%s'" pos buffer))
17761 (cdr errdata))))))))
17763 (defun org-days-to-iso-week (days)
17764 "Return the iso week number."
17765 (require 'cal-iso)
17766 (car (calendar-iso-from-absolute days)))
17768 (defun org-small-year-to-year (year)
17769 "Convert 2-digit years into 4-digit years.
17770 YEAR is expanded into one of the 30 next years, if possible, or
17771 into a past one. Any year larger than 99 is returned unchanged."
17772 (if (>= year 100) year
17773 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17774 (century (/ current 100))
17775 (offset (- year (% current 100))))
17776 (cond ((> offset 30) (+ (* (1- century) 100) year))
17777 ((> offset -70) (+ (* century 100) year))
17778 (t (+ (* (1+ century) 100) year))))))
17780 (defun org-time-from-absolute (d)
17781 "Return the time corresponding to date D.
17782 D may be an absolute day number, or a calendar-type list (month day year)."
17783 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17784 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17786 (defvar org-agenda-current-date)
17787 (defun org-calendar-holiday ()
17788 "List of holidays, for Diary display in Org mode."
17789 (require 'holidays)
17790 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17791 (and hl (mapconcat #'identity hl "; "))))
17793 (defun org-diary-sexp-entry (sexp entry d)
17794 "Process a SEXP diary ENTRY for date D."
17795 (require 'diary-lib)
17796 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17797 ;; dynamically.
17798 (let* ((sexp `(let ((entry ,entry)
17799 (date ',d))
17800 ,(car (read-from-string sexp))))
17801 (result (if calendar-debug-sexp (eval sexp)
17802 (condition-case nil
17803 (eval sexp)
17804 (error
17805 (beep)
17806 (message "Bad sexp at line %d in %s: %s"
17807 (org-current-line)
17808 (buffer-file-name) sexp)
17809 (sleep-for 2))))))
17810 (cond ((stringp result) (split-string result "; "))
17811 ((and (consp result)
17812 (not (consp (cdr result)))
17813 (stringp (cdr result))) (cdr result))
17814 ((and (consp result)
17815 (stringp (car result))) result)
17816 (result entry))))
17818 (defun org-diary-to-ical-string (frombuf)
17819 "Get iCalendar entries from diary entries in buffer FROMBUF.
17820 This uses the icalendar.el library."
17821 (let* ((tmpdir temporary-file-directory)
17822 (tmpfile (make-temp-name
17823 (expand-file-name "orgics" tmpdir)))
17824 buf rtn b e)
17825 (with-current-buffer frombuf
17826 (icalendar-export-region (point-min) (point-max) tmpfile)
17827 (setq buf (find-buffer-visiting tmpfile))
17828 (set-buffer buf)
17829 (goto-char (point-min))
17830 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17831 (setq b (match-beginning 0)))
17832 (goto-char (point-max))
17833 (when (re-search-backward "^END:VEVENT" nil t)
17834 (setq e (match-end 0)))
17835 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17836 (kill-buffer buf)
17837 (delete-file tmpfile)
17838 rtn))
17840 (defun org-closest-date (start current prefer)
17841 "Return closest date to CURRENT starting from START.
17843 CURRENT and START are both time stamps.
17845 When PREFER is `past', return a date that is either CURRENT or
17846 past. When PREFER is `future', return a date that is either
17847 CURRENT or future.
17849 Only time stamps with a repeater are modified. Any other time
17850 stamp stay unchanged. In any case, return value is an absolute
17851 day number."
17852 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17853 ;; No repeater. Do not shift time stamp.
17854 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17855 (let ((value (string-to-number (match-string 1 start)))
17856 (type (match-string 2 start)))
17857 (if (= 0 value)
17858 ;; Repeater with a 0-value is considered as void.
17859 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17860 (let* ((base (org-date-to-gregorian start))
17861 (target (org-date-to-gregorian current))
17862 (sday (calendar-absolute-from-gregorian base))
17863 (cday (calendar-absolute-from-gregorian target))
17864 n1 n2)
17865 ;; If START is already past CURRENT, just return START.
17866 (if (<= cday sday) sday
17867 ;; Compute closest date before (N1) and closest date past
17868 ;; (N2) CURRENT.
17869 (pcase type
17870 ("h"
17871 (let ((missing-hours
17872 (mod (+ (- (* 24 (- cday sday))
17873 (nth 2 (org-parse-time-string start)))
17874 org-extend-today-until)
17875 value)))
17876 (setf n1 (if (= missing-hours 0) cday
17877 (- cday (1+ (/ missing-hours 24)))))
17878 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17879 ((or "d" "w")
17880 (let ((value (if (equal type "w") (* 7 value) value)))
17881 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17882 (setf n2 (+ n1 value))))
17883 ("m"
17884 (let* ((add-months
17885 (lambda (d n)
17886 ;; Add N months to gregorian date D, i.e.,
17887 ;; a list (MONTH DAY YEAR). Return a valid
17888 ;; gregorian date.
17889 (let ((m (+ (nth 0 d) n)))
17890 (list (mod m 12)
17891 (nth 1 d)
17892 (+ (/ m 12) (nth 2 d))))))
17893 (months ; Complete months to TARGET.
17894 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17895 (- (nth 0 target) (nth 0 base))
17896 ;; If START's day is greater than
17897 ;; TARGET's, remove incomplete month.
17898 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17899 value)
17900 value))
17901 (before (funcall add-months base months)))
17902 (setf n1 (calendar-absolute-from-gregorian before))
17903 (setf n2
17904 (calendar-absolute-from-gregorian
17905 (funcall add-months before value)))))
17907 (let* ((d (nth 1 base))
17908 (m (nth 0 base))
17909 (y (nth 2 base))
17910 (years ; Complete years to TARGET.
17911 (* (/ (- (nth 2 target)
17913 ;; If START's month and day are
17914 ;; greater than TARGET's, remove
17915 ;; incomplete year.
17916 (if (or (> (nth 0 target) m)
17917 (and (= (nth 0 target) m)
17918 (> (nth 1 target) d)))
17921 value)
17922 value))
17923 (before (list m d (+ y years))))
17924 (setf n1 (calendar-absolute-from-gregorian before))
17925 (setf n2 (calendar-absolute-from-gregorian
17926 (list m d (+ (nth 2 before) value)))))))
17927 ;; Handle PREFER parameter, if any.
17928 (cond
17929 ((eq prefer 'past) (if (= cday n2) n2 n1))
17930 ((eq prefer 'future) (if (= cday n1) n1 n2))
17931 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17933 (defun org-date-to-gregorian (d)
17934 "Turn any specification of date D into a Gregorian date for the calendar."
17935 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17936 ((and (listp d) (= (length d) 3)) d)
17937 ((stringp d)
17938 (let ((d (org-parse-time-string d)))
17939 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17940 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17942 (defun org-parse-time-string (s &optional nodefault)
17943 "Parse the standard Org time string.
17944 This should be a lot faster than the normal `parse-time-string'.
17945 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17946 hour and minute fields will be nil if not given."
17947 (cond ((string-match org-ts-regexp0 s)
17948 (list 0
17949 (when (or (match-beginning 8) (not nodefault))
17950 (string-to-number (or (match-string 8 s) "0")))
17951 (when (or (match-beginning 7) (not nodefault))
17952 (string-to-number (or (match-string 7 s) "0")))
17953 (string-to-number (match-string 4 s))
17954 (string-to-number (match-string 3 s))
17955 (string-to-number (match-string 2 s))
17956 nil nil nil))
17957 ((string-match "^<[^>]+>$" s)
17958 (decode-time (seconds-to-time (org-matcher-time s))))
17959 (t (error "Not a standard Org time string: %s" s))))
17961 (defun org-timestamp-up (&optional arg)
17962 "Increase the date item at the cursor by one.
17963 If the cursor is on the year, change the year. If it is on the month,
17964 the day or the time, change that.
17965 With prefix ARG, change by that many units."
17966 (interactive "p")
17967 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17969 (defun org-timestamp-down (&optional arg)
17970 "Decrease the date item at the cursor by one.
17971 If the cursor is on the year, change the year. If it is on the month,
17972 the day or the time, change that.
17973 With prefix ARG, change by that many units."
17974 (interactive "p")
17975 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17977 (defun org-timestamp-up-day (&optional arg)
17978 "Increase the date in the time stamp by one day.
17979 With prefix ARG, change that many days."
17980 (interactive "p")
17981 (if (and (not (org-at-timestamp-p t))
17982 (org-at-heading-p))
17983 (org-todo 'up)
17984 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17986 (defun org-timestamp-down-day (&optional arg)
17987 "Decrease the date in the time stamp by one day.
17988 With prefix ARG, change that many days."
17989 (interactive "p")
17990 (if (and (not (org-at-timestamp-p t))
17991 (org-at-heading-p))
17992 (org-todo 'down)
17993 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17995 (defun org-at-timestamp-p (&optional inactive-ok)
17996 "Non-nil if point is inside a timestamp.
17998 When optional argument INACTIVE-OK is non-nil, also consider
17999 inactive timestamps.
18001 When this function returns a non-nil value, match data is set
18002 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18003 INACTIVE-OK."
18004 (interactive)
18005 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18006 (pos (point))
18007 (ans (or (looking-at tsr)
18008 (save-excursion
18009 (skip-chars-backward "^[<\n\r\t")
18010 (when (> (point) (point-min)) (backward-char 1))
18011 (and (looking-at tsr)
18012 (> (- (match-end 0) pos) -1))))))
18013 (and ans
18014 (boundp 'org-ts-what)
18015 (setq org-ts-what
18016 (cond
18017 ((= pos (match-beginning 0)) 'bracket)
18018 ;; Point is considered to be "on the bracket" whether
18019 ;; it's really on it or right after it.
18020 ((= pos (1- (match-end 0))) 'bracket)
18021 ((= pos (match-end 0)) 'after)
18022 ((org-pos-in-match-range pos 2) 'year)
18023 ((org-pos-in-match-range pos 3) 'month)
18024 ((org-pos-in-match-range pos 7) 'hour)
18025 ((org-pos-in-match-range pos 8) 'minute)
18026 ((or (org-pos-in-match-range pos 4)
18027 (org-pos-in-match-range pos 5)) 'day)
18028 ((and (> pos (or (match-end 8) (match-end 5)))
18029 (< pos (match-end 0)))
18030 (- pos (or (match-end 8) (match-end 5))))
18031 (t 'day))))
18032 ans))
18034 (defun org-toggle-timestamp-type ()
18035 "Toggle the type (<active> or [inactive]) of a time stamp."
18036 (interactive)
18037 (when (org-at-timestamp-p t)
18038 (let ((beg (match-beginning 0)) (end (match-end 0))
18039 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18040 (save-excursion
18041 (goto-char beg)
18042 (while (re-search-forward "[][<>]" end t)
18043 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18044 t t)))
18045 (message "Timestamp is now %sactive"
18046 (if (equal (char-after beg) ?<) "" "in")))))
18048 (defun org-at-clock-log-p nil
18049 "Is the cursor on the clock log line?"
18050 (save-excursion
18051 (move-beginning-of-line 1)
18052 (looking-at org-clock-line-re)))
18054 (defvar org-clock-history) ; defined in org-clock.el
18055 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18056 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18057 "Change the date in the time stamp at point.
18058 The date will be changed by N times WHAT. WHAT can be `day', `month',
18059 `year', `minute', `second'. If WHAT is not given, the cursor position
18060 in the timestamp determines what will be changed.
18061 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18062 (let ((origin (point)) origin-cat
18063 with-hm inactive
18064 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18065 org-ts-what
18066 extra rem
18067 ts time time0 fixnext clrgx)
18068 (unless (org-at-timestamp-p t)
18069 (user-error "Not at a timestamp"))
18070 (if (and (not what) (eq org-ts-what 'bracket))
18071 (org-toggle-timestamp-type)
18072 ;; Point isn't on brackets. Remember the part of the time-stamp
18073 ;; the point was in. Indeed, size of time-stamps may change,
18074 ;; but point must be kept in the same category nonetheless.
18075 (setq origin-cat org-ts-what)
18076 (when (and (not what) (not (eq org-ts-what 'day))
18077 org-display-custom-times
18078 (get-text-property (point) 'display)
18079 (not (get-text-property (1- (point)) 'display)))
18080 (setq org-ts-what 'day))
18081 (setq org-ts-what (or what org-ts-what)
18082 inactive (= (char-after (match-beginning 0)) ?\[)
18083 ts (match-string 0))
18084 (replace-match "")
18085 (when (string-match
18086 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18088 (setq extra (match-string 1 ts))
18089 (when suppress-tmp-delay
18090 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18091 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18092 (setq with-hm t))
18093 (setq time0 (org-parse-time-string ts))
18094 (when (and updown
18095 (eq org-ts-what 'minute)
18096 (not current-prefix-arg))
18097 ;; This looks like s-up and s-down. Change by one rounding step.
18098 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18099 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18100 (setcar (cdr time0) (+ (nth 1 time0)
18101 (if (> n 0) (- rem) (- dm rem))))))
18102 (setq time
18103 (apply #'encode-time
18104 (or (car time0) 0)
18105 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18106 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18107 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18108 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18109 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18110 (nthcdr 6 time0)))
18111 (when (and (member org-ts-what '(hour minute))
18112 extra
18113 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18114 (setq extra (org-modify-ts-extra
18115 extra
18116 (if (eq org-ts-what 'hour) 2 5)
18117 n dm)))
18118 (when (integerp org-ts-what)
18119 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18120 (when (eq what 'calendar)
18121 (let ((cal-date (org-get-date-from-calendar)))
18122 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18123 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18124 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18125 (setcar time0 (or (car time0) 0))
18126 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18127 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18128 (setq time (apply 'encode-time time0))))
18129 ;; Insert the new time-stamp, and ensure point stays in the same
18130 ;; category as before (i.e. not after the last position in that
18131 ;; category).
18132 (let ((pos (point)))
18133 ;; Stay before inserted string. `save-excursion' is of no use.
18134 (setq org-last-changed-timestamp
18135 (org-insert-time-stamp time with-hm inactive nil nil extra))
18136 (goto-char pos))
18137 (save-match-data
18138 (looking-at org-ts-regexp3)
18139 (goto-char (cond
18140 ;; `day' category ends before `hour' if any, or at
18141 ;; the end of the day name.
18142 ((eq origin-cat 'day)
18143 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18144 ((eq origin-cat 'hour) (min (match-end 7) origin))
18145 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18146 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18147 ;; `year' and `month' have both fixed size: point
18148 ;; couldn't have moved into another part.
18149 (t origin))))
18150 ;; Update clock if on a CLOCK line.
18151 (org-clock-update-time-maybe)
18152 ;; Maybe adjust the closest clock in `org-clock-history'
18153 (when org-clock-adjust-closest
18154 (if (not (and (org-at-clock-log-p)
18155 (< 1 (length (delq nil (mapcar 'marker-position
18156 org-clock-history))))))
18157 (message "No clock to adjust")
18158 (cond ((save-excursion ; fix previous clock?
18159 (re-search-backward org-ts-regexp0 nil t)
18160 (looking-back (concat org-clock-string " \\[")
18161 (line-beginning-position)))
18162 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18163 ((save-excursion ; fix next clock?
18164 (re-search-backward org-ts-regexp0 nil t)
18165 (looking-at (concat org-ts-regexp0 "\\] =>")))
18166 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18167 (save-window-excursion
18168 ;; Find closest clock to point, adjust the previous/next one in history
18169 (let* ((p (save-excursion (org-back-to-heading t)))
18170 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18171 (clfixnth
18172 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18173 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18174 (if (not clfixpos)
18175 (message "No clock to adjust")
18176 (save-excursion
18177 (org-goto-marker-or-bmk clfixpos)
18178 (org-show-subtree)
18179 (when (re-search-forward clrgx nil t)
18180 (goto-char (match-beginning 1))
18181 (let (org-clock-adjust-closest)
18182 (org-timestamp-change n org-ts-what updown))
18183 (message "Clock adjusted in %s for heading: %s"
18184 (file-name-nondirectory (buffer-file-name))
18185 (org-get-heading t t)))))))))
18186 ;; Try to recenter the calendar window, if any.
18187 (when (and org-calendar-follow-timestamp-change
18188 (get-buffer-window "*Calendar*" t)
18189 (memq org-ts-what '(day month year)))
18190 (org-recenter-calendar (time-to-days time))))))
18192 (defun org-modify-ts-extra (s pos n dm)
18193 "Change the different parts of the lead-time and repeat fields in timestamp."
18194 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18195 ng h m new rem)
18196 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18197 (cond
18198 ((or (org-pos-in-match-range pos 2)
18199 (org-pos-in-match-range pos 3))
18200 (setq m (string-to-number (match-string 3 s))
18201 h (string-to-number (match-string 2 s)))
18202 (if (org-pos-in-match-range pos 2)
18203 (setq h (+ h n))
18204 (setq n (* dm (with-no-warnings (signum n))))
18205 (unless (= 0 (setq rem (% m dm)))
18206 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18207 (setq m (+ m n)))
18208 (when (< m 0) (setq m (+ m 60) h (1- h)))
18209 (when (> m 59) (setq m (- m 60) h (1+ h)))
18210 (setq h (mod h 24))
18211 (setq ng 1 new (format "-%02d:%02d" h m)))
18212 ((org-pos-in-match-range pos 6)
18213 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18214 ((org-pos-in-match-range pos 5)
18215 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18217 ((org-pos-in-match-range pos 9)
18218 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18219 ((org-pos-in-match-range pos 8)
18220 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18222 (when ng
18223 (setq s (concat
18224 (substring s 0 (match-beginning ng))
18226 (substring s (match-end ng))))))
18229 (defun org-recenter-calendar (d)
18230 "If the calendar is visible, recenter it to date D."
18231 (let ((cwin (get-buffer-window "*Calendar*" t)))
18232 (when cwin
18233 (let ((calendar-move-hook nil))
18234 (with-selected-window cwin
18235 (calendar-goto-date
18236 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18238 (defun org-goto-calendar (&optional arg)
18239 "Go to the Emacs calendar at the current date.
18240 If there is a time stamp in the current line, go to that date.
18241 A prefix ARG can be used to force the current date."
18242 (interactive "P")
18243 (let ((tsr org-ts-regexp) diff
18244 (calendar-move-hook nil)
18245 (calendar-view-holidays-initially-flag nil)
18246 (calendar-view-diary-initially-flag nil))
18247 (when (or (org-at-timestamp-p)
18248 (save-excursion
18249 (beginning-of-line 1)
18250 (looking-at (concat ".*" tsr))))
18251 (let ((d1 (time-to-days (current-time)))
18252 (d2 (time-to-days
18253 (org-time-string-to-time (match-string 1)))))
18254 (setq diff (- d2 d1))))
18255 (calendar)
18256 (calendar-goto-today)
18257 (when (and diff (not arg)) (calendar-forward-day diff))))
18259 (defun org-get-date-from-calendar ()
18260 "Return a list (month day year) of date at point in calendar."
18261 (with-current-buffer "*Calendar*"
18262 (save-match-data
18263 (calendar-cursor-to-date))))
18265 (defun org-date-from-calendar ()
18266 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18267 If there is already a time stamp at the cursor position, update it."
18268 (interactive)
18269 (if (org-at-timestamp-p t)
18270 (org-timestamp-change 0 'calendar)
18271 (let ((cal-date (org-get-date-from-calendar)))
18272 (org-insert-time-stamp
18273 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18275 (defcustom org-effort-durations
18276 `(("min" . 1)
18277 ("h" . 60)
18278 ("d" . ,(* 60 8))
18279 ("w" . ,(* 60 8 5))
18280 ("m" . ,(* 60 8 5 4))
18281 ("y" . ,(* 60 8 5 40)))
18282 "Conversion factor to minutes for an effort modifier.
18284 Each entry has the form (MODIFIER . MINUTES).
18286 In an effort string, a number followed by MODIFIER is multiplied
18287 by the specified number of MINUTES to obtain an effort in
18288 minutes.
18290 For example, if the value of this variable is ((\"hours\" . 60)), then an
18291 effort string \"2hours\" is equivalent to 120 minutes."
18292 :group 'org-agenda
18293 :version "25.2"
18294 :package-version '(Org . "8.3")
18295 :type '(alist :key-type (string :tag "Modifier")
18296 :value-type (number :tag "Minutes")))
18298 (defun org-minutes-to-clocksum-string (m)
18299 "Format number of minutes as a clocksum string.
18300 The format is determined by `org-time-clocksum-format',
18301 `org-time-clocksum-use-fractional' and
18302 `org-time-clocksum-fractional-format' and
18303 `org-time-clocksum-use-effort-durations'."
18304 (let ((clocksum "")
18305 (m (round m)) ; Don't allow fractions of minutes
18306 h d w mo y fmt n)
18307 (setq h (if org-time-clocksum-use-effort-durations
18308 (cdr (assoc "h" org-effort-durations)) 60)
18309 d (if org-time-clocksum-use-effort-durations
18310 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18311 w (if org-time-clocksum-use-effort-durations
18312 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18313 mo (if org-time-clocksum-use-effort-durations
18314 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18315 y (if org-time-clocksum-use-effort-durations
18316 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18317 ;; fractional format
18318 (if org-time-clocksum-use-fractional
18319 (cond
18320 ;; single format string
18321 ((stringp org-time-clocksum-fractional-format)
18322 (format org-time-clocksum-fractional-format (/ m (float h))))
18323 ;; choice of fractional formats for different time units
18324 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18325 (> (/ (truncate m) (* y d h)) 0))
18326 (format fmt (/ m (* y d (float h)))))
18327 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18328 (> (/ (truncate m) (* mo d h)) 0))
18329 (format fmt (/ m (* mo d (float h)))))
18330 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18331 (> (/ (truncate m) (* w d h)) 0))
18332 (format fmt (/ m (* w d (float h)))))
18333 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18334 (> (/ (truncate m) (* d h)) 0))
18335 (format fmt (/ m (* d (float h)))))
18336 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18337 (> (/ (truncate m) h) 0))
18338 (format fmt (/ m (float h))))
18339 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18340 (format fmt m))
18341 ;; fall back to smallest time unit with a format
18342 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18343 (format fmt (/ m (float h))))
18344 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18345 (format fmt (/ m (* d (float h)))))
18346 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18347 (format fmt (/ m (* w d (float h)))))
18348 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18349 (format fmt (/ m (* mo d (float h)))))
18350 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18351 (format fmt (/ m (* y d (float h))))))
18352 ;; standard (non-fractional) format, with single format string
18353 (if (stringp org-time-clocksum-format)
18354 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18355 ;; separate formats components
18356 (and (setq fmt (plist-get org-time-clocksum-format :years))
18357 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18358 (plist-get org-time-clocksum-format :require-years))
18359 (setq clocksum (concat clocksum (format fmt n))
18360 m (- m (* n y d h))))
18361 (and (setq fmt (plist-get org-time-clocksum-format :months))
18362 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18363 (plist-get org-time-clocksum-format :require-months))
18364 (setq clocksum (concat clocksum (format fmt n))
18365 m (- m (* n mo d h))))
18366 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18367 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18368 (plist-get org-time-clocksum-format :require-weeks))
18369 (setq clocksum (concat clocksum (format fmt n))
18370 m (- m (* n w d h))))
18371 (and (setq fmt (plist-get org-time-clocksum-format :days))
18372 (or (> (setq n (/ (truncate m) (* d h))) 0)
18373 (plist-get org-time-clocksum-format :require-days))
18374 (setq clocksum (concat clocksum (format fmt n))
18375 m (- m (* n d h))))
18376 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18377 (or (> (setq n (/ (truncate m) h)) 0)
18378 (plist-get org-time-clocksum-format :require-hours))
18379 (setq clocksum (concat clocksum (format fmt n))
18380 m (- m (* n h))))
18381 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18382 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18383 (setq clocksum (concat clocksum (format fmt m))))
18384 ;; return formatted time duration
18385 clocksum))))
18387 (defun org-hours-to-clocksum-string (n)
18388 (org-minutes-to-clocksum-string (* n 60)))
18390 (defun org-hh:mm-string-to-minutes (s)
18391 "Convert a string H:MM to a number of minutes.
18392 If the string is just a number, interpret it as minutes.
18393 In fact, the first hh:mm or number in the string will be taken,
18394 there can be extra stuff in the string.
18395 If no number is found, the return value is 0."
18396 (cond
18397 ((integerp s) s)
18398 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18399 (+ (* (string-to-number (match-string 1 s)) 60)
18400 (string-to-number (match-string 2 s))))
18401 ((string-match "\\([0-9]+\\)" s)
18402 (string-to-number (match-string 1 s)))
18403 (t 0)))
18405 (defcustom org-image-actual-width t
18406 "Should we use the actual width of images when inlining them?
18408 When set to t, always use the image width.
18410 When set to a number, use imagemagick (when available) to set
18411 the image's width to this value.
18413 When set to a number in a list, try to get the width from any
18414 #+ATTR.* keyword if it matches a width specification like
18416 #+ATTR_HTML: :width 300px
18418 and fall back on that number if none is found.
18420 When set to nil, try to get the width from an #+ATTR.* keyword
18421 and fall back on the original width if none is found.
18423 This requires Emacs >= 24.1, build with imagemagick support."
18424 :group 'org-appearance
18425 :version "24.4"
18426 :package-version '(Org . "8.0")
18427 :type '(choice
18428 (const :tag "Use the image width" t)
18429 (integer :tag "Use a number of pixels")
18430 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18431 (const :tag "Use #+ATTR* or don't resize" nil)))
18433 (defcustom org-agenda-inhibit-startup nil
18434 "Inhibit startup when preparing agenda buffers.
18435 When this variable is t, the initialization of the Org agenda
18436 buffers is inhibited: e.g. the visibility state is not set, the
18437 tables are not re-aligned, etc."
18438 :type 'boolean
18439 :version "24.3"
18440 :group 'org-agenda)
18442 (defcustom org-agenda-ignore-properties nil
18443 "Avoid updating text properties when building the agenda.
18444 Properties are used to prepare buffers for effort estimates,
18445 appointments, statistics and subtree-local categories.
18446 If you don't use these in the agenda, you can add them to this
18447 list and agenda building will be a bit faster.
18448 The value is a list, with zero or more of the symbols `effort', `appt',
18449 `stats' or `category'."
18450 :type '(set :greedy t
18451 (const effort)
18452 (const appt)
18453 (const stats)
18454 (const category))
18455 :version "25.2"
18456 :package-version '(Org . "8.3")
18457 :group 'org-agenda)
18459 (defun org-duration-string-to-minutes (s &optional output-to-string)
18460 "Convert a duration string S to minutes.
18462 A bare number is interpreted as minutes, modifiers can be set by
18463 customizing `org-effort-durations' (which see).
18465 Entries containing a colon are interpreted as H:MM by
18466 `org-hh:mm-string-to-minutes'."
18467 (let ((result 0)
18468 (re (concat "\\([0-9.]+\\) *\\("
18469 (regexp-opt (mapcar 'car org-effort-durations))
18470 "\\)")))
18471 (while (string-match re s)
18472 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18473 (string-to-number (match-string 1 s))))
18474 (setq s (replace-match "" nil t s)))
18475 (setq result (floor result))
18476 (cl-incf result (org-hh:mm-string-to-minutes s))
18477 (if output-to-string (number-to-string result) result)))
18479 ;;;; Files
18481 (defun org-save-all-org-buffers ()
18482 "Save all Org buffers without user confirmation."
18483 (interactive)
18484 (message "Saving all Org buffers...")
18485 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18486 (when (featurep 'org-id) (org-id-locations-save))
18487 (message "Saving all Org buffers... done"))
18489 (defun org-revert-all-org-buffers ()
18490 "Revert all Org buffers.
18491 Prompt for confirmation when there are unsaved changes.
18492 Be sure you know what you are doing before letting this function
18493 overwrite your changes.
18495 This function is useful in a setup where one tracks org files
18496 with a version control system, to revert on one machine after pulling
18497 changes from another. I believe the procedure must be like this:
18499 1. M-x org-save-all-org-buffers
18500 2. Pull changes from the other machine, resolve conflicts
18501 3. M-x org-revert-all-org-buffers"
18502 (interactive)
18503 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18504 (user-error "Abort"))
18505 (save-excursion
18506 (save-window-excursion
18507 (dolist (b (buffer-list))
18508 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18509 (with-current-buffer b buffer-file-name))
18510 (pop-to-buffer-same-window b)
18511 (revert-buffer t 'no-confirm)))
18512 (when (and (featurep 'org-id) org-id-track-globally)
18513 (org-id-locations-load)))))
18515 ;;;; Agenda files
18517 ;;;###autoload
18518 (defun org-switchb (&optional arg)
18519 "Switch between Org buffers.
18521 With \\[universal-argument] prefix, restrict available buffers to files.
18523 With \\[universal-argument] \\[universal-argument] \
18524 prefix, restrict available buffers to agenda files."
18525 (interactive "P")
18526 (let ((blist (org-buffer-list
18527 (cond ((equal arg '(4)) 'files)
18528 ((equal arg '(16)) 'agenda)))))
18529 (pop-to-buffer-same-window
18530 (completing-read "Org buffer: "
18531 (mapcar #'list (mapcar #'buffer-name blist))
18532 nil t))))
18534 (defun org-buffer-list (&optional predicate exclude-tmp)
18535 "Return a list of Org buffers.
18536 PREDICATE can be `export', `files' or `agenda'.
18538 export restrict the list to Export buffers.
18539 files restrict the list to buffers visiting Org files.
18540 agenda restrict the list to buffers visiting agenda files.
18542 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18543 (let* ((bfn nil)
18544 (agenda-files (and (eq predicate 'agenda)
18545 (mapcar 'file-truename (org-agenda-files t))))
18546 (filter
18547 (cond
18548 ((eq predicate 'files)
18549 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18550 ((eq predicate 'export)
18551 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18552 ((eq predicate 'agenda)
18553 (lambda (b)
18554 (with-current-buffer b
18555 (and (derived-mode-p 'org-mode)
18556 (setq bfn (buffer-file-name b))
18557 (member (file-truename bfn) agenda-files)))))
18558 (t (lambda (b) (with-current-buffer b
18559 (or (derived-mode-p 'org-mode)
18560 (string-match "\\*Org .*Export"
18561 (buffer-name b)))))))))
18562 (delq nil
18563 (mapcar
18564 (lambda(b)
18565 (if (and (funcall filter b)
18566 (or (not exclude-tmp)
18567 (not (string-match "tmp" (buffer-name b)))))
18569 nil))
18570 (buffer-list)))))
18572 (defun org-agenda-files (&optional unrestricted archives)
18573 "Get the list of agenda files.
18574 Optional UNRESTRICTED means return the full list even if a restriction
18575 is currently in place.
18576 When ARCHIVES is t, include all archive files that are really being
18577 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18578 `org-agenda-archives-mode' is t."
18579 (let ((files
18580 (cond
18581 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18582 ((stringp org-agenda-files) (org-read-agenda-file-list))
18583 ((listp org-agenda-files) org-agenda-files)
18584 (t (error "Invalid value of `org-agenda-files'")))))
18585 (setq files (apply 'append
18586 (mapcar (lambda (f)
18587 (if (file-directory-p f)
18588 (directory-files
18589 f t org-agenda-file-regexp)
18590 (list f)))
18591 files)))
18592 (when org-agenda-skip-unavailable-files
18593 (setq files (delq nil
18594 (mapcar (function
18595 (lambda (file)
18596 (and (file-readable-p file) file)))
18597 files))))
18598 (when (or (eq archives t)
18599 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18600 (setq files (org-add-archive-files files)))
18601 files))
18603 (defun org-agenda-file-p (&optional file)
18604 "Return non-nil, if FILE is an agenda file.
18605 If FILE is omitted, use the file associated with the current
18606 buffer."
18607 (let ((fname (or file (buffer-file-name))))
18608 (and fname
18609 (member (file-truename fname)
18610 (mapcar #'file-truename (org-agenda-files t))))))
18612 (defun org-edit-agenda-file-list ()
18613 "Edit the list of agenda files.
18614 Depending on setup, this either uses customize to edit the variable
18615 `org-agenda-files', or it visits the file that is holding the list. In the
18616 latter case, the buffer is set up in a way that saving it automatically kills
18617 the buffer and restores the previous window configuration."
18618 (interactive)
18619 (if (stringp org-agenda-files)
18620 (let ((cw (current-window-configuration)))
18621 (find-file org-agenda-files)
18622 (setq-local org-window-configuration cw)
18623 (add-hook 'after-save-hook
18624 (lambda ()
18625 (set-window-configuration
18626 (prog1 org-window-configuration
18627 (kill-buffer (current-buffer))))
18628 (org-install-agenda-files-menu)
18629 (message "New agenda file list installed"))
18630 nil 'local)
18631 (message "%s" (substitute-command-keys
18632 "Edit list and finish with \\[save-buffer]")))
18633 (customize-variable 'org-agenda-files)))
18635 (defun org-store-new-agenda-file-list (list)
18636 "Set new value for the agenda file list and save it correctly."
18637 (if (stringp org-agenda-files)
18638 (let ((fe (org-read-agenda-file-list t)) b u)
18639 (while (setq b (find-buffer-visiting org-agenda-files))
18640 (kill-buffer b))
18641 (with-temp-file org-agenda-files
18642 (insert
18643 (mapconcat
18644 (lambda (f) ;; Keep un-expanded entries.
18645 (if (setq u (assoc f fe))
18646 (cdr u)
18648 list "\n")
18649 "\n")))
18650 (let ((org-mode-hook nil) (org-inhibit-startup t)
18651 (org-insert-mode-line-in-empty-file nil))
18652 (setq org-agenda-files list)
18653 (customize-save-variable 'org-agenda-files org-agenda-files))))
18655 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18656 "Read the list of agenda files from a file.
18657 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18658 filenames, used by `org-store-new-agenda-file-list' to write back
18659 un-expanded file names."
18660 (when (file-directory-p org-agenda-files)
18661 (error "`org-agenda-files' cannot be a single directory"))
18662 (when (stringp org-agenda-files)
18663 (with-temp-buffer
18664 (insert-file-contents org-agenda-files)
18665 (mapcar
18666 (lambda (f)
18667 (let ((e (expand-file-name (substitute-in-file-name f)
18668 org-directory)))
18669 (if pair-with-expansion
18670 (cons e f)
18671 e)))
18672 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18674 ;;;###autoload
18675 (defun org-cycle-agenda-files ()
18676 "Cycle through the files in `org-agenda-files'.
18677 If the current buffer visits an agenda file, find the next one in the list.
18678 If the current buffer does not, find the first agenda file."
18679 (interactive)
18680 (let* ((fs (or (org-agenda-files t)
18681 (user-error "No agenda files")))
18682 (files (copy-sequence fs))
18683 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18684 file)
18685 (when tcf
18686 (while (and (setq file (pop files))
18687 (not (equal (file-truename file) tcf)))))
18688 (find-file (car (or files fs)))
18689 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18691 (defun org-agenda-file-to-front (&optional to-end)
18692 "Move/add the current file to the top of the agenda file list.
18693 If the file is not present in the list, it is added to the front. If it is
18694 present, it is moved there. With optional argument TO-END, add/move to the
18695 end of the list."
18696 (interactive "P")
18697 (let ((org-agenda-skip-unavailable-files nil)
18698 (file-alist (mapcar (lambda (x)
18699 (cons (file-truename x) x))
18700 (org-agenda-files t)))
18701 (ctf (file-truename
18702 (or buffer-file-name
18703 (user-error "Please save the current buffer to a file"))))
18704 x had)
18705 (setq x (assoc ctf file-alist) had x)
18707 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18708 (if to-end
18709 (setq file-alist (append (delq x file-alist) (list x)))
18710 (setq file-alist (cons x (delq x file-alist))))
18711 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18712 (org-install-agenda-files-menu)
18713 (message "File %s to %s of agenda file list"
18714 (if had "moved" "added") (if to-end "end" "front"))))
18716 (defun org-remove-file (&optional file)
18717 "Remove current file from the list of files in variable `org-agenda-files'.
18718 These are the files which are being checked for agenda entries.
18719 Optional argument FILE means use this file instead of the current."
18720 (interactive)
18721 (let* ((org-agenda-skip-unavailable-files nil)
18722 (file (or file buffer-file-name
18723 (user-error "Current buffer does not visit a file")))
18724 (true-file (file-truename file))
18725 (afile (abbreviate-file-name file))
18726 (files (delq nil (mapcar
18727 (lambda (x)
18728 (unless (equal true-file
18729 (file-truename x))
18731 (org-agenda-files t)))))
18732 (if (not (= (length files) (length (org-agenda-files t))))
18733 (progn
18734 (org-store-new-agenda-file-list files)
18735 (org-install-agenda-files-menu)
18736 (message "Removed from Org Agenda list: %s" afile))
18737 (message "File was not in list: %s (not removed)" afile))))
18739 (defun org-file-menu-entry (file)
18740 (vector file (list 'find-file file) t))
18742 (defun org-check-agenda-file (file)
18743 "Make sure FILE exists. If not, ask user what to do."
18744 (unless (file-exists-p file)
18745 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18746 (abbreviate-file-name file))
18747 (let ((r (downcase (read-char-exclusive))))
18748 (cond
18749 ((equal r ?r)
18750 (org-remove-file file)
18751 (throw 'nextfile t))
18752 (t (user-error "Abort"))))))
18754 (defun org-get-agenda-file-buffer (file)
18755 "Get an agenda buffer visiting FILE.
18756 If the buffer needs to be created, add it to the list of buffers
18757 which might be released later."
18758 (let ((buf (org-find-base-buffer-visiting file)))
18759 (if buf
18760 buf ; just return it
18761 ;; Make a new buffer and remember it
18762 (setq buf (find-file-noselect file))
18763 (when buf (push buf org-agenda-new-buffers))
18764 buf)))
18766 (defun org-release-buffers (blist)
18767 "Release all buffers in list, asking the user for confirmation when needed.
18768 When a buffer is unmodified, it is just killed. When modified, it is saved
18769 \(if the user agrees) and then killed."
18770 (let (file)
18771 (dolist (buf blist)
18772 (setq file (buffer-file-name buf))
18773 (when (and (buffer-modified-p buf)
18774 file
18775 (y-or-n-p (format "Save file %s? " file)))
18776 (with-current-buffer buf (save-buffer)))
18777 (kill-buffer buf))))
18779 (defun org-agenda-prepare-buffers (files)
18780 "Create buffers for all agenda files, protect archived trees and comments."
18781 (interactive)
18782 (let ((pa '(:org-archived t))
18783 (pc '(:org-comment t))
18784 (pall '(:org-archived t :org-comment t))
18785 (inhibit-read-only t)
18786 (org-inhibit-startup org-agenda-inhibit-startup)
18787 (rea (concat ":" org-archive-tag ":"))
18788 re pos)
18789 (setq org-tag-alist-for-agenda nil
18790 org-tag-groups-alist-for-agenda nil)
18791 (save-excursion
18792 (save-restriction
18793 (dolist (file files)
18794 (catch 'nextfile
18795 (if (bufferp file)
18796 (set-buffer file)
18797 (org-check-agenda-file file)
18798 (set-buffer (org-get-agenda-file-buffer file)))
18799 (widen)
18800 (org-set-regexps-and-options 'tags-only)
18801 (setq pos (point))
18802 (or (memq 'category org-agenda-ignore-properties)
18803 (org-refresh-category-properties))
18804 (or (memq 'stats org-agenda-ignore-properties)
18805 (org-refresh-stats-properties))
18806 (or (memq 'effort org-agenda-ignore-properties)
18807 (org-refresh-effort-properties))
18808 (or (memq 'appt org-agenda-ignore-properties)
18809 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18810 (setq org-todo-keywords-for-agenda
18811 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18812 (setq org-done-keywords-for-agenda
18813 (append org-done-keywords-for-agenda org-done-keywords))
18814 (setq org-todo-keyword-alist-for-agenda
18815 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18816 (setq org-tag-alist-for-agenda
18817 (org-uniquify
18818 (append org-tag-alist-for-agenda
18819 org-current-tag-alist)))
18820 ;; Merge current file's tag groups into global
18821 ;; `org-tag-groups-alist-for-agenda'.
18822 (when org-group-tags
18823 (dolist (alist org-tag-groups-alist)
18824 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18825 (if old
18826 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18827 (push alist org-tag-groups-alist-for-agenda)))))
18828 (org-with-silent-modifications
18829 (save-excursion
18830 (remove-text-properties (point-min) (point-max) pall)
18831 (when org-agenda-skip-archived-trees
18832 (goto-char (point-min))
18833 (while (re-search-forward rea nil t)
18834 (when (org-at-heading-p t)
18835 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18836 (goto-char (point-min))
18837 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18838 (while (re-search-forward re nil t)
18839 (when (save-match-data (org-in-commented-heading-p t))
18840 (add-text-properties
18841 (match-beginning 0) (org-end-of-subtree t) pc)))))
18842 (goto-char pos)))))
18843 (setq org-todo-keywords-for-agenda
18844 (org-uniquify org-todo-keywords-for-agenda))
18845 (setq org-todo-keyword-alist-for-agenda
18846 (org-uniquify org-todo-keyword-alist-for-agenda))))
18849 ;;;; CDLaTeX minor mode
18851 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18852 "Keymap for the minor `org-cdlatex-mode'.")
18854 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18855 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18856 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18857 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18858 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18860 (defvar org-cdlatex-texmathp-advice-is-done nil
18861 "Flag remembering if we have applied the advice to texmathp already.")
18863 (define-minor-mode org-cdlatex-mode
18864 "Toggle the minor `org-cdlatex-mode'.
18865 This mode supports entering LaTeX environment and math in LaTeX fragments
18866 in Org mode.
18867 \\{org-cdlatex-mode-map}"
18868 nil " OCDL" nil
18869 (when org-cdlatex-mode
18870 (require 'cdlatex)
18871 (run-hooks 'cdlatex-mode-hook)
18872 (cdlatex-compute-tables))
18873 (unless org-cdlatex-texmathp-advice-is-done
18874 (setq org-cdlatex-texmathp-advice-is-done t)
18875 (defadvice texmathp (around org-math-always-on activate)
18876 "Always return t in Org buffers.
18877 This is because we want to insert math symbols without dollars even outside
18878 the LaTeX math segments. If Orgmode thinks that point is actually inside
18879 an embedded LaTeX fragment, let texmathp do its job.
18880 \\[org-cdlatex-mode-map]"
18881 (interactive)
18882 (let (p)
18883 (cond
18884 ((not (derived-mode-p 'org-mode)) ad-do-it)
18885 ((eq this-command 'cdlatex-math-symbol)
18886 (setq ad-return-value t
18887 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18889 (let ((p (org-inside-LaTeX-fragment-p)))
18890 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18891 (setq ad-return-value t
18892 texmathp-why '("Org mode embedded math" . 0))
18893 (when p ad-do-it)))))))))
18895 (defun turn-on-org-cdlatex ()
18896 "Unconditionally turn on `org-cdlatex-mode'."
18897 (org-cdlatex-mode 1))
18899 (defun org-try-cdlatex-tab ()
18900 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18901 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18902 - inside a LaTeX fragment, or
18903 - after the first word in a line, where an abbreviation expansion could
18904 insert a LaTeX environment."
18905 (when org-cdlatex-mode
18906 (cond
18907 ;; Before any word on the line: No expansion possible.
18908 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18909 ;; Just after first word on the line: Expand it. Make sure it
18910 ;; cannot happen on headlines, though.
18911 ((save-excursion
18912 (skip-chars-backward "a-zA-Z0-9*")
18913 (skip-chars-backward " \t")
18914 (and (bolp) (not (org-at-heading-p))))
18915 (cdlatex-tab) t)
18916 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18918 (defun org-cdlatex-underscore-caret (&optional _arg)
18919 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18920 Revert to the normal definition outside of these fragments."
18921 (interactive "P")
18922 (if (org-inside-LaTeX-fragment-p)
18923 (call-interactively 'cdlatex-sub-superscript)
18924 (let (org-cdlatex-mode)
18925 (call-interactively (key-binding (vector last-input-event))))))
18927 (defun org-cdlatex-math-modify (&optional _arg)
18928 "Execute `cdlatex-math-modify' 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-math-modify)
18933 (let (org-cdlatex-mode)
18934 (call-interactively (key-binding (vector last-input-event))))))
18936 (defun org-cdlatex-environment-indent (&optional environment item)
18937 "Execute `cdlatex-environment' and indent the inserted environment.
18939 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18941 The inserted environment is indented to current indentation
18942 unless point is at the beginning of the line, in which the
18943 environment remains unintended."
18944 (interactive)
18945 ;; cdlatex-environment always return nil. Therefore, capture output
18946 ;; first and determine if an environment was selected.
18947 (let* ((beg (point-marker))
18948 (end (copy-marker (point) t))
18949 (inserted (progn
18950 (ignore-errors (cdlatex-environment environment item))
18951 (< beg end)))
18952 ;; Figure out how many lines to move forward after the
18953 ;; environment has been inserted.
18954 (lines (when inserted
18955 (save-excursion
18956 (- (cl-loop while (< beg (point))
18957 with x = 0
18958 do (forward-line -1)
18959 (cl-incf x)
18960 finally return x)
18961 (if (progn (goto-char beg)
18962 (and (progn (skip-chars-forward " \t") (eolp))
18963 (progn (skip-chars-backward " \t") (bolp))))
18964 1 0)))))
18965 (env (org-trim (delete-and-extract-region beg end))))
18966 (when inserted
18967 ;; Get indentation of next line unless at column 0.
18968 (let ((ind (if (bolp) 0
18969 (save-excursion
18970 (org-return-indent)
18971 (prog1 (org-get-indentation)
18972 (when (progn (skip-chars-forward " \t") (eolp))
18973 (delete-region beg (point)))))))
18974 (bol (progn (skip-chars-backward " \t") (bolp))))
18975 ;; Insert a newline before environment unless at column zero
18976 ;; to "escape" the current line. Insert a newline if
18977 ;; something is one the same line as \end{ENVIRONMENT}.
18978 (insert
18979 (concat (unless bol "\n") env
18980 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18981 (unless (zerop ind)
18982 (save-excursion
18983 (goto-char beg)
18984 (while (< (point) end)
18985 (unless (eolp) (indent-line-to ind))
18986 (forward-line))))
18987 (goto-char beg)
18988 (forward-line lines)
18989 (indent-line-to ind)))
18990 (set-marker beg nil)
18991 (set-marker end nil)))
18994 ;;;; LaTeX fragments
18996 (defun org-inside-LaTeX-fragment-p ()
18997 "Test if point is inside a LaTeX fragment.
18998 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18999 sequence appearing also before point.
19000 Even though the matchers for math are configurable, this function assumes
19001 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19002 delimiters are skipped when they have been removed by customization.
19003 The return value is nil, or a cons cell with the delimiter and the
19004 position of this delimiter.
19006 This function does a reasonably good job, but can locally be fooled by
19007 for example currency specifications. For example it will assume being in
19008 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19009 fragments that are properly closed, but during editing, we have to live
19010 with the uncertainty caused by missing closing delimiters. This function
19011 looks only before point, not after."
19012 (catch 'exit
19013 (let ((pos (point))
19014 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19015 (lim (progn
19016 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19017 (point)))
19018 dd-on str (start 0) m re)
19019 (goto-char pos)
19020 (when dodollar
19021 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19022 re (nth 1 (assoc "$" org-latex-regexps)))
19023 (while (string-match re str start)
19024 (cond
19025 ((= (match-end 0) (length str))
19026 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19027 ((= (match-end 0) (- (length str) 5))
19028 (throw 'exit nil))
19029 (t (setq start (match-end 0))))))
19030 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19031 (goto-char pos)
19032 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19033 (and (match-beginning 2) (throw 'exit nil))
19034 ;; count $$
19035 (while (re-search-backward "\\$\\$" lim t)
19036 (setq dd-on (not dd-on)))
19037 (goto-char pos)
19038 (when dd-on (cons "$$" m))))))
19040 (defun org-inside-latex-macro-p ()
19041 "Is point inside a LaTeX macro or its arguments?"
19042 (save-match-data
19043 (org-in-regexp
19044 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19046 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19047 "Build an overlay between BEG and END using IMAGE file.
19048 Argument IMAGETYPE is the extension of the displayed image,
19049 as a string. It defaults to \"png\"."
19050 (let ((ov (make-overlay beg end))
19051 (imagetype (or (intern imagetype) 'png)))
19052 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19053 (overlay-put ov 'evaporate t)
19054 (overlay-put ov
19055 'modification-hooks
19056 (list (lambda (o _flag _beg _end &optional _l)
19057 (delete-overlay o))))
19058 (overlay-put ov
19059 'display
19060 (list 'image :type imagetype :file image :ascent 'center))))
19062 (defun org--list-latex-overlays (&optional beg end)
19063 "List all Org LaTeX overlays in current buffer.
19064 Limit to overlays between BEG and END when those are provided."
19065 (cl-remove-if-not
19066 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19067 (overlays-in (or beg (point-min)) (or end (point-max)))))
19069 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19070 "Remove all overlays with LaTeX fragment images in current buffer.
19071 When optional arguments BEG and END are non-nil, remove all
19072 overlays between them instead. Return a non-nil value when some
19073 overlays were removed, nil otherwise."
19074 (let ((overlays (org--list-latex-overlays beg end)))
19075 (mapc #'delete-overlay overlays)
19076 overlays))
19078 (defun org-toggle-latex-fragment (&optional arg)
19079 "Preview the LaTeX fragment at point, or all locally or globally.
19081 If the cursor is on a LaTeX fragment, create the image and overlay
19082 it over the source code, if there is none. Remove it otherwise.
19083 If there is no fragment at point, display all fragments in the
19084 current section.
19086 With prefix ARG, preview or clear image for all fragments in the
19087 current subtree or in the whole buffer when used before the first
19088 headline. With a double prefix ARG \\[universal-argument] \
19089 \\[universal-argument] preview or clear images
19090 for all fragments in the buffer."
19091 (interactive "P")
19092 (when (display-graphic-p)
19093 (catch 'exit
19094 (save-excursion
19095 (let (beg end msg)
19096 (cond
19097 ((or (equal arg '(16))
19098 (and (equal arg '(4))
19099 (org-with-limited-levels (org-before-first-heading-p))))
19100 (if (org-remove-latex-fragment-image-overlays)
19101 (progn (message "LaTeX fragments images removed from buffer")
19102 (throw 'exit nil))
19103 (setq msg "Creating images for buffer...")))
19104 ((equal arg '(4))
19105 (org-with-limited-levels (org-back-to-heading t))
19106 (setq beg (point))
19107 (setq end (progn (org-end-of-subtree t) (point)))
19108 (if (org-remove-latex-fragment-image-overlays beg end)
19109 (progn
19110 (message "LaTeX fragment images removed from subtree")
19111 (throw 'exit nil))
19112 (setq msg "Creating images for subtree...")))
19113 ((let ((datum (org-element-context)))
19114 (when (memq (org-element-type datum)
19115 '(latex-environment latex-fragment))
19116 (setq beg (org-element-property :begin datum))
19117 (setq end (org-element-property :end datum))
19118 (if (org-remove-latex-fragment-image-overlays beg end)
19119 (progn (message "LaTeX fragment image removed")
19120 (throw 'exit nil))
19121 (setq msg "Creating image...")))))
19123 (org-with-limited-levels
19124 (setq beg (if (org-at-heading-p) (line-beginning-position)
19125 (outline-previous-heading)
19126 (point)))
19127 (setq end (progn (outline-next-heading) (point)))
19128 (if (org-remove-latex-fragment-image-overlays beg end)
19129 (progn
19130 (message "LaTeX fragment images removed from section")
19131 (throw 'exit nil))
19132 (setq msg "Creating images for section...")))))
19133 (let ((file (buffer-file-name (buffer-base-buffer))))
19134 (org-format-latex
19135 (concat org-preview-latex-image-directory "org-ltximg")
19136 beg end
19137 ;; Emacs cannot overlay images from remote hosts. Create
19138 ;; it in `temporary-file-directory' instead.
19139 (if (or (not file) (file-remote-p file))
19140 temporary-file-directory
19141 default-directory)
19142 'overlays msg 'forbuffer org-preview-latex-default-process))
19143 (message (concat msg "done")))))))
19145 (defun org-format-latex
19146 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19147 "Replace LaTeX fragments with links to an image.
19149 The function takes care of creating the replacement image.
19151 Only consider fragments between BEG and END when those are
19152 provided.
19154 When optional argument OVERLAYS is non-nil, display the image on
19155 top of the fragment instead of replacing it.
19157 PROCESSING-TYPE is the conversion method to use, as a symbol.
19159 Some of the options can be changed using the variable
19160 `org-format-latex-options', which see."
19161 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19162 (unless (eq processing-type 'verbatim)
19163 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19164 (cnt 0)
19165 checkdir-flag)
19166 (goto-char (or beg (point-min)))
19167 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19168 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19169 (overlay-recenter (or end (point-max))))
19170 (while (re-search-forward math-regexp end t)
19171 (unless (and overlays
19172 (eq (get-char-property (point) 'org-overlay-type)
19173 'org-latex-overlay))
19174 (let* ((context (org-element-context))
19175 (type (org-element-type context)))
19176 (when (memq type '(latex-environment latex-fragment))
19177 (let ((block-type (eq type 'latex-environment))
19178 (value (org-element-property :value context))
19179 (beg (org-element-property :begin context))
19180 (end (save-excursion
19181 (goto-char (org-element-property :end context))
19182 (skip-chars-backward " \r\t\n")
19183 (point))))
19184 (cond
19185 ((eq processing-type 'mathjax)
19186 ;; Prepare for MathJax processing.
19187 (if (not (string-match "\\`\\$\\$?" value))
19188 (goto-char end)
19189 (delete-region beg end)
19190 (if (string= (match-string 0 value) "$$")
19191 (insert "\\[" (substring value 2 -2) "\\]")
19192 (insert "\\(" (substring value 1 -1) "\\)"))))
19193 ((assq processing-type org-preview-latex-process-alist)
19194 ;; Process to an image.
19195 (cl-incf cnt)
19196 (goto-char beg)
19197 (let* ((processing-info
19198 (cdr (assq processing-type org-preview-latex-process-alist)))
19199 (face (face-at-point))
19200 ;; Get the colors from the face at point.
19202 (let ((color (plist-get org-format-latex-options
19203 :foreground)))
19204 (if (and forbuffer (eq color 'auto))
19205 (face-attribute face :foreground nil 'default)
19206 color)))
19208 (let ((color (plist-get org-format-latex-options
19209 :background)))
19210 (if (and forbuffer (eq color 'auto))
19211 (face-attribute face :background nil 'default)
19212 color)))
19213 (hash (sha1 (prin1-to-string
19214 (list org-format-latex-header
19215 org-latex-default-packages-alist
19216 org-latex-packages-alist
19217 org-format-latex-options
19218 forbuffer value fg bg))))
19219 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19220 (absprefix (expand-file-name prefix dir))
19221 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19222 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19223 (sep (and block-type "\n\n"))
19224 (link (concat sep "[[file:" linkfile "]]" sep))
19225 (options
19226 (org-combine-plists
19227 org-format-latex-options
19228 `(:foreground ,fg :background ,bg))))
19229 (when msg (message msg cnt))
19230 (unless checkdir-flag ; Ensure the directory exists.
19231 (setq checkdir-flag t)
19232 (let ((todir (file-name-directory absprefix)))
19233 (unless (file-directory-p todir)
19234 (make-directory todir t))))
19235 (unless (file-exists-p movefile)
19236 (org-create-formula-image
19237 value movefile options forbuffer processing-type))
19238 (if overlays
19239 (progn
19240 (dolist (o (overlays-in beg end))
19241 (when (eq (overlay-get o 'org-overlay-type)
19242 'org-latex-overlay)
19243 (delete-overlay o)))
19244 (org--format-latex-make-overlay beg end movefile imagetype)
19245 (goto-char end))
19246 (delete-region beg end)
19247 (insert
19248 (org-add-props link
19249 (list 'org-latex-src
19250 (replace-regexp-in-string "\"" "" value)
19251 'org-latex-src-embed-type
19252 (if block-type 'paragraph 'character)))))))
19253 ((eq processing-type 'mathml)
19254 ;; Process to MathML.
19255 (unless (org-format-latex-mathml-available-p)
19256 (user-error "LaTeX to MathML converter not configured"))
19257 (cl-incf cnt)
19258 (when msg (message msg cnt))
19259 (goto-char beg)
19260 (delete-region beg end)
19261 (insert (org-format-latex-as-mathml
19262 value block-type prefix dir)))
19264 (error "Unknown conversion process %s for LaTeX fragments"
19265 processing-type)))))))))))
19267 (defun org-create-math-formula (latex-frag &optional mathml-file)
19268 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19269 Use `org-latex-to-mathml-convert-command'. If the conversion is
19270 sucessful, return the portion between \"<math...> </math>\"
19271 elements otherwise return nil. When MATHML-FILE is specified,
19272 write the results in to that file. When invoked as an
19273 interactive command, prompt for LATEX-FRAG, with initial value
19274 set to the current active region and echo the results for user
19275 inspection."
19276 (interactive (list (let ((frag (when (org-region-active-p)
19277 (buffer-substring-no-properties
19278 (region-beginning) (region-end)))))
19279 (read-string "LaTeX Fragment: " frag nil frag))))
19280 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19281 (let* ((tmp-in-file
19282 (let ((file (file-relative-name
19283 (make-temp-name (expand-file-name "ltxmathml-in")))))
19284 (write-region latex-frag nil file)
19285 file))
19286 (tmp-out-file (file-relative-name
19287 (make-temp-name (expand-file-name "ltxmathml-out"))))
19288 (cmd (format-spec
19289 org-latex-to-mathml-convert-command
19290 `((?j . ,(and org-latex-to-mathml-jar-file
19291 (shell-quote-argument
19292 (expand-file-name
19293 org-latex-to-mathml-jar-file))))
19294 (?I . ,(shell-quote-argument tmp-in-file))
19295 (?i . ,latex-frag)
19296 (?o . ,(shell-quote-argument tmp-out-file)))))
19297 mathml shell-command-output)
19298 (when (called-interactively-p 'any)
19299 (unless (org-format-latex-mathml-available-p)
19300 (user-error "LaTeX to MathML converter not configured")))
19301 (message "Running %s" cmd)
19302 (setq shell-command-output (shell-command-to-string cmd))
19303 (setq mathml
19304 (when (file-readable-p tmp-out-file)
19305 (with-current-buffer (find-file-noselect tmp-out-file t)
19306 (goto-char (point-min))
19307 (when (re-search-forward
19308 (concat
19309 (regexp-quote
19310 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19311 "[^>]*?>"
19312 "\\(.\\|\n\\)*"
19313 "</math>")
19314 nil t)
19315 (prog1 (match-string 0) (kill-buffer))))))
19316 (cond
19317 (mathml
19318 (setq mathml
19319 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19320 (when mathml-file
19321 (write-region mathml nil mathml-file))
19322 (when (called-interactively-p 'any)
19323 (message mathml)))
19324 ((message "LaTeX to MathML conversion failed")
19325 (message shell-command-output)))
19326 (delete-file tmp-in-file)
19327 (when (file-exists-p tmp-out-file)
19328 (delete-file tmp-out-file))
19329 mathml))
19331 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19332 prefix &optional dir)
19333 "Use `org-create-math-formula' but check local cache first."
19334 (let* ((absprefix (expand-file-name prefix dir))
19335 (print-length nil) (print-level nil)
19336 (formula-id (concat
19337 "formula-"
19338 (sha1
19339 (prin1-to-string
19340 (list latex-frag
19341 org-latex-to-mathml-convert-command)))))
19342 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19343 (formula-cache-dir (file-name-directory formula-cache)))
19345 (unless (file-directory-p formula-cache-dir)
19346 (make-directory formula-cache-dir t))
19348 (unless (file-exists-p formula-cache)
19349 (org-create-math-formula latex-frag formula-cache))
19351 (if (file-exists-p formula-cache)
19352 ;; Successful conversion. Return the link to MathML file.
19353 (org-add-props
19354 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19355 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19356 'org-latex-src-embed-type (if latex-frag-type
19357 'paragraph 'character)))
19358 ;; Failed conversion. Return the LaTeX fragment verbatim
19359 latex-frag)))
19361 (declare-function org-export-get-backend "ox" (name))
19362 (declare-function org-export--get-global-options "ox" (&optional backend))
19363 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19364 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19365 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19366 (defun org-create-formula--latex-header ()
19367 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19368 (let ((info (org-combine-plists (org-export--get-global-options
19369 (org-export-get-backend 'latex))
19370 (org-export--get-inbuffer-options
19371 (org-export-get-backend 'latex)))))
19372 (org-latex-guess-babel-language
19373 (org-latex-guess-inputenc
19374 (org-splice-latex-header
19375 org-format-latex-header
19376 org-latex-default-packages-alist
19377 org-latex-packages-alist t
19378 (plist-get info :latex-header)))
19379 info)))
19381 (defun org--get-display-dpi ()
19382 "Get the DPI of the display.
19384 Assumes that the display has the same pixel width in the
19385 horizontal and vertical directions."
19386 (if (display-graphic-p)
19387 (round (/ (display-pixel-height)
19388 (/ (display-mm-height) 25.4)))
19389 (error "Attempt to calculate the dpi of a non-graphic display")))
19391 (defun org-create-formula-image
19392 (string tofile options buffer &optional processing-type)
19393 "Create an image from LaTeX source using external processes.
19395 The LaTeX STRING is saved to a temporary LaTeX file, then
19396 converted to an image file by process PROCESSING-TYPE defined in
19397 `org-preview-latex-process-alist'. A nil value defaults to
19398 `org-preview-latex-default-process'.
19400 The generated image file is eventually moved to TOFILE.
19402 The OPTIONS argument controls the size, foreground color and
19403 background color of the generated image.
19405 When BUFFER non-nil, this function is used for LaTeX previewing.
19406 Otherwise, it is used to deal with LaTeX snippets showed in
19407 a HTML file."
19408 (let* ((processing-type (or processing-type
19409 org-preview-latex-default-process))
19410 (processing-info
19411 (cdr (assq processing-type org-preview-latex-process-alist)))
19412 (programs (plist-get processing-info :programs))
19413 (error-message (or (plist-get processing-info :message) ""))
19414 (use-xcolor (plist-get processing-info :use-xcolor))
19415 (image-input-type (plist-get processing-info :image-input-type))
19416 (image-output-type (plist-get processing-info :image-output-type))
19417 (post-clean (or (plist-get processing-info :post-clean)
19418 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19419 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19420 (latex-header (or (plist-get processing-info :latex-header)
19421 (org-create-formula--latex-header)))
19422 (latex-compiler (plist-get processing-info :latex-compiler))
19423 (image-converter (plist-get processing-info :image-converter))
19424 (tmpdir temporary-file-directory)
19425 (texfilebase (make-temp-name
19426 (expand-file-name "orgtex" tmpdir)))
19427 (texfile (concat texfilebase ".tex"))
19428 (font-height (face-attribute 'default :height nil))
19429 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19430 '(1.0 . 1.0)))
19431 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19432 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19433 (dpi (* scale (floor (if buffer font-height 140.0))))
19434 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19435 "Black"))
19436 (bg (or (plist-get options (if buffer :background :html-background))
19437 "Transparent"))
19438 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19439 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19440 (dolist (program programs)
19441 (org-check-external-command program error-message))
19442 (if use-xcolor
19443 (progn (if (eq fg 'default)
19444 (setq fg (org-latex-color :foreground))
19445 (setq fg (org-latex-color-format fg)))
19446 (if (eq bg 'default)
19447 (setq bg (org-latex-color :background))
19448 (setq bg (org-latex-color-format
19449 (if (string= bg "Transparent") "white" bg))))
19450 (with-temp-file texfile
19451 (insert latex-header)
19452 (insert "\n\\begin{document}\n"
19453 "\\definecolor{fg}{rgb}{" fg "}\n"
19454 "\\definecolor{bg}{rgb}{" bg "}\n"
19455 "\n\\pagecolor{bg}\n"
19456 "\n{\\color{fg}\n"
19457 string
19458 "\n}\n"
19459 "\n\\end{document}\n")))
19460 (if (eq fg 'default)
19461 (setq fg (org-dvipng-color :foreground))
19462 (unless (string= fg "Transparent")
19463 (setq fg (org-dvipng-color-format fg))))
19464 (if (eq bg 'default)
19465 (setq bg (org-dvipng-color :background))
19466 (unless (string= bg "Transparent")
19467 (setq bg (org-dvipng-color-format bg))))
19468 (with-temp-file texfile
19469 (insert latex-header)
19470 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19472 (let* ((err-msg (format "Please adjust '%s' part of \
19473 `org-preview-latex-process-alist'."
19474 processing-type))
19475 (image-input-file
19476 (org-compile-file
19477 texfile latex-compiler image-input-type err-msg log-buf))
19478 (image-output-file
19479 (org-compile-file
19480 image-input-file image-converter image-output-type err-msg log-buf
19481 `((?F . ,(shell-quote-argument fg))
19482 (?B . ,(shell-quote-argument bg))
19483 (?D . ,(shell-quote-argument (format "%s" dpi)))
19484 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19485 (copy-file image-output-file tofile 'replace)
19486 (dolist (e post-clean)
19487 (when (file-exists-p (concat texfilebase e))
19488 (delete-file (concat texfilebase e))))
19489 image-output-file)))
19491 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19492 "Fill a LaTeX header template TPL.
19493 In the template, the following place holders will be recognized:
19495 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19496 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19497 [PACKAGES] \\usepackage statements for PKG
19498 [NO-PACKAGES] do not include PKG
19499 [EXTRA] the string EXTRA
19500 [NO-EXTRA] do not include EXTRA
19502 For backward compatibility, if both the positive and the negative place
19503 holder is missing, the positive one (without the \"NO-\") will be
19504 assumed to be present at the end of the template.
19505 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19506 EXTRA is a string.
19507 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19508 (let (rpl (end ""))
19509 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19510 (setq rpl (if (or (match-end 1) (not def-pkg))
19511 "" (org-latex-packages-to-string def-pkg snippets-p t))
19512 tpl (replace-match rpl t t tpl))
19513 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19515 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19516 (setq rpl (if (or (match-end 1) (not pkg))
19517 "" (org-latex-packages-to-string pkg snippets-p t))
19518 tpl (replace-match rpl t t tpl))
19519 (when pkg (setq end
19520 (concat end "\n"
19521 (org-latex-packages-to-string pkg snippets-p)))))
19523 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19524 (setq rpl (if (or (match-end 1) (not extra))
19525 "" (concat extra "\n"))
19526 tpl (replace-match rpl t t tpl))
19527 (when (and extra (string-match "\\S-" extra))
19528 (setq end (concat end "\n" extra))))
19530 (if (string-match "\\S-" end)
19531 (concat tpl "\n" end)
19532 tpl)))
19534 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19535 "Turn an alist of packages into a string with the \\usepackage macros."
19536 (setq pkg (mapconcat (lambda(p)
19537 (cond
19538 ((stringp p) p)
19539 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19540 (format "%% Package %s omitted" (cadr p)))
19541 ((equal "" (car p))
19542 (format "\\usepackage{%s}" (cadr p)))
19544 (format "\\usepackage[%s]{%s}"
19545 (car p) (cadr p)))))
19547 "\n"))
19548 (if newline (concat pkg "\n") pkg))
19550 (defun org-dvipng-color (attr)
19551 "Return a RGB color specification for dvipng."
19552 (org-dvipng-color-format (face-attribute 'default attr nil)))
19554 (defun org-dvipng-color-format (color-name)
19555 "Convert COLOR-NAME to a RGB color value for dvipng."
19556 (apply #'format "rgb %s %s %s"
19557 (mapcar 'org-normalize-color
19558 (color-values color-name))))
19560 (defun org-latex-color (attr)
19561 "Return a RGB color for the LaTeX color package."
19562 (org-latex-color-format (face-attribute 'default attr nil)))
19564 (defun org-latex-color-format (color-name)
19565 "Convert COLOR-NAME to a RGB color value."
19566 (apply #'format "%s,%s,%s"
19567 (mapcar 'org-normalize-color
19568 (color-values color-name))))
19570 (defun org-normalize-color (value)
19571 "Return string to be used as color value for an RGB component."
19572 (format "%g" (/ value 65535.0)))
19576 ;; Image display
19578 (defvar-local org-inline-image-overlays nil)
19580 (defun org-toggle-inline-images (&optional include-linked)
19581 "Toggle the display of inline images.
19582 INCLUDE-LINKED is passed to `org-display-inline-images'."
19583 (interactive "P")
19584 (if org-inline-image-overlays
19585 (progn
19586 (org-remove-inline-images)
19587 (when (called-interactively-p 'interactive)
19588 (message "Inline image display turned off")))
19589 (org-display-inline-images include-linked)
19590 (when (called-interactively-p 'interactive)
19591 (message (if org-inline-image-overlays
19592 (format "%d images displayed inline"
19593 (length org-inline-image-overlays))
19594 "No images to display inline")))))
19596 (defun org-redisplay-inline-images ()
19597 "Refresh the display of inline images."
19598 (interactive)
19599 (if (not org-inline-image-overlays)
19600 (org-toggle-inline-images)
19601 (org-toggle-inline-images)
19602 (org-toggle-inline-images)))
19604 (defun org-display-inline-images (&optional include-linked refresh beg end)
19605 "Display inline images.
19607 An inline image is a link which follows either of these
19608 conventions:
19610 1. Its path is a file with an extension matching return value
19611 from `image-file-name-regexp' and it has no contents.
19613 2. Its description consists in a single link of the previous
19614 type.
19616 When optional argument INCLUDE-LINKED is non-nil, also links with
19617 a text description part will be inlined. This can be nice for
19618 a quick look at those images, but it does not reflect what
19619 exported files will look like.
19621 When optional argument REFRESH is non-nil, refresh existing
19622 images between BEG and END. This will create new image displays
19623 only if necessary. BEG and END default to the buffer
19624 boundaries."
19625 (interactive "P")
19626 (when (display-graphic-p)
19627 (unless refresh
19628 (org-remove-inline-images)
19629 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19630 (org-with-wide-buffer
19631 (goto-char (or beg (point-min)))
19632 (let ((case-fold-search t)
19633 (file-extension-re (image-file-name-regexp)))
19634 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19635 (let ((link (save-match-data (org-element-context))))
19636 ;; Check if we're at an inline image.
19637 (when (and (equal (org-element-property :type link) "file")
19638 (or include-linked
19639 (not (org-element-property :contents-begin link)))
19640 (let ((parent (org-element-property :parent link)))
19641 (or (not (eq (org-element-type parent) 'link))
19642 (not (cdr (org-element-contents parent)))))
19643 (string-match-p file-extension-re
19644 (org-element-property :path link)))
19645 (let ((file (expand-file-name
19646 (org-link-unescape
19647 (org-element-property :path link)))))
19648 (when (file-exists-p file)
19649 (let ((width
19650 ;; Apply `org-image-actual-width' specifications.
19651 (cond
19652 ((not (image-type-available-p 'imagemagick)) nil)
19653 ((eq org-image-actual-width t) nil)
19654 ((listp org-image-actual-width)
19656 ;; First try to find a width among
19657 ;; attributes associated to the paragraph
19658 ;; containing link.
19659 (let ((paragraph
19660 (let ((e link))
19661 (while (and (setq e (org-element-property
19662 :parent e))
19663 (not (eq (org-element-type e)
19664 'paragraph))))
19665 e)))
19666 (when paragraph
19667 (save-excursion
19668 (goto-char (org-element-property :begin paragraph))
19669 (when
19670 (re-search-forward
19671 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19672 (org-element-property
19673 :post-affiliated paragraph)
19675 (string-to-number (match-string 1))))))
19676 ;; Otherwise, fall-back to provided number.
19677 (car org-image-actual-width)))
19678 ((numberp org-image-actual-width)
19679 org-image-actual-width)))
19680 (old (get-char-property-and-overlay
19681 (org-element-property :begin link)
19682 'org-image-overlay)))
19683 (if (and (car-safe old) refresh)
19684 (image-refresh (overlay-get (cdr old) 'display))
19685 (let ((image (create-image file
19686 (and width 'imagemagick)
19688 :width width)))
19689 (when image
19690 (let* ((link
19691 ;; If inline image is the description
19692 ;; of another link, be sure to
19693 ;; consider the latter as the one to
19694 ;; apply the overlay on.
19695 (let ((parent
19696 (org-element-property :parent link)))
19697 (if (eq (org-element-type parent) 'link)
19698 parent
19699 link)))
19700 (ov (make-overlay
19701 (org-element-property :begin link)
19702 (progn
19703 (goto-char
19704 (org-element-property :end link))
19705 (skip-chars-backward " \t")
19706 (point)))))
19707 (overlay-put ov 'display image)
19708 (overlay-put ov 'face 'default)
19709 (overlay-put ov 'org-image-overlay t)
19710 (overlay-put
19711 ov 'modification-hooks
19712 (list 'org-display-inline-remove-overlay))
19713 (push ov org-inline-image-overlays)))))))))))))))
19715 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19716 "Remove inline-display overlay if a corresponding region is modified."
19717 (let ((inhibit-modification-hooks t))
19718 (when (and ov after)
19719 (delete ov org-inline-image-overlays)
19720 (delete-overlay ov))))
19722 (defun org-remove-inline-images ()
19723 "Remove inline display of images."
19724 (interactive)
19725 (mapc #'delete-overlay org-inline-image-overlays)
19726 (setq org-inline-image-overlays nil))
19728 ;;;; Key bindings
19730 ;; Outline functions from `outline-mode-prefix-map'
19731 ;; that can be remapped in Org:
19732 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19733 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19734 (define-key org-mode-map [remap outline-forward-same-level]
19735 'org-forward-heading-same-level)
19736 (define-key org-mode-map [remap outline-backward-same-level]
19737 'org-backward-heading-same-level)
19738 (define-key org-mode-map [remap outline-show-branches]
19739 'org-kill-note-or-show-branches)
19740 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19741 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19742 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19743 (define-key org-mode-map [remap outline-next-visible-heading]
19744 'org-next-visible-heading)
19745 (define-key org-mode-map [remap outline-previous-visible-heading]
19746 'org-previous-visible-heading)
19747 (define-key org-mode-map [remap show-children] 'org-show-children)
19749 ;; Outline functions from `outline-mode-prefix-map' that can not
19750 ;; be remapped in Org:
19752 ;; - the column "key binding" shows whether the Outline function is still
19753 ;; available in Org mode on the same key that it has been bound to in
19754 ;; Outline mode:
19755 ;; - "overridden": key used for a different functionality in Org mode
19756 ;; - else: key still bound to the same Outline function in Org mode
19758 ;; | Outline function | key binding | Org replacement |
19759 ;; |------------------------------------+-------------+--------------------------|
19760 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19761 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19762 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19763 ;; | `show-entry' | overridden | no replacement |
19764 ;; | `show-branches' | `C-c C-k' | still same function |
19765 ;; | `show-subtree' | overridden | visibility cycling |
19766 ;; | `show-all' | overridden | no replacement |
19767 ;; | `hide-subtree' | overridden | visibility cycling |
19768 ;; | `hide-body' | overridden | no replacement |
19769 ;; | `hide-entry' | overridden | visibility cycling |
19770 ;; | `hide-leaves' | overridden | no replacement |
19771 ;; | `hide-sublevels' | overridden | no replacement |
19772 ;; | `hide-other' | overridden | no replacement |
19774 ;; Make `C-c C-x' a prefix key
19775 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19777 ;; TAB key with modifiers
19778 (org-defkey org-mode-map "\C-i" 'org-cycle)
19779 (org-defkey org-mode-map [(tab)] 'org-cycle)
19780 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19781 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19782 ;; The following line is necessary under Suse GNU/Linux
19783 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19784 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19785 (define-key org-mode-map [backtab] 'org-shifttab)
19787 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19788 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19789 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19791 ;; Cursor keys with modifiers
19792 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19793 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19794 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19795 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19797 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19798 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19799 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19800 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19801 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19802 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19804 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19805 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19806 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19807 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19809 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19810 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19811 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19812 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19814 ;; Babel keys
19815 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19816 (dolist (pair org-babel-key-bindings)
19817 (define-key org-babel-map (car pair) (cdr pair)))
19819 ;;; Extra keys for tty access.
19820 ;; We only set them when really needed because otherwise the
19821 ;; menus don't show the simple keys
19823 (when (or org-use-extra-keys (not window-system))
19824 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19825 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19826 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19827 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19828 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19829 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19830 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19831 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19832 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19833 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19834 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19835 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19836 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19837 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19838 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19839 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19840 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19841 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19842 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19843 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19844 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19845 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19846 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19847 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19848 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19849 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19850 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19851 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19853 ;; All the other keys
19855 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19856 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19857 (if (boundp 'narrow-map)
19858 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19859 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19860 (if (boundp 'narrow-map)
19861 (org-defkey narrow-map "b" 'org-narrow-to-block)
19862 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19863 (if (boundp 'narrow-map)
19864 (org-defkey narrow-map "e" 'org-narrow-to-element)
19865 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19866 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19867 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19868 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19869 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19870 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19871 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19872 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19873 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19874 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19875 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19876 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19877 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19878 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19879 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19880 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19881 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19882 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19883 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19884 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19885 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19886 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19887 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19888 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19889 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19890 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19891 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19892 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19893 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19894 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19895 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19896 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19897 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19898 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19899 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19900 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19901 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19902 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19903 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19904 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19905 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19906 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19907 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19908 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19909 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19910 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19911 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19912 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19913 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19914 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19915 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19916 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19917 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19918 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19919 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19920 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19921 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19922 (org-defkey org-mode-map "\C-c^" 'org-sort)
19923 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19924 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19925 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19926 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19927 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19928 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19929 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19930 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19931 (org-defkey org-mode-map "\C-m" 'org-return)
19932 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19933 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19934 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19935 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19936 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19937 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19938 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19939 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19940 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19941 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19942 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19943 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19944 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19945 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19946 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19947 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19948 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19949 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19950 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19951 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19952 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19953 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19954 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19955 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19956 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19958 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19959 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19960 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19962 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19963 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19964 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19965 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19966 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19967 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19968 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19969 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19970 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19971 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19972 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19973 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19974 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19975 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19976 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19977 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19978 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19979 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19980 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19981 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19982 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19983 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19985 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19986 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19987 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19988 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19989 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19991 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19993 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19995 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19996 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19998 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20001 (defconst org-speed-commands-default
20003 ("Outline Navigation")
20004 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20005 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20006 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20007 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20008 ("F" . org-next-block)
20009 ("B" . org-previous-block)
20010 ("u" . (org-speed-move-safe 'outline-up-heading))
20011 ("j" . org-goto)
20012 ("g" . (org-refile t))
20013 ("Outline Visibility")
20014 ("c" . org-cycle)
20015 ("C" . org-shifttab)
20016 (" " . org-display-outline-path)
20017 ("s" . org-narrow-to-subtree)
20018 ("=" . org-columns)
20019 ("Outline Structure Editing")
20020 ("U" . org-metaup)
20021 ("D" . org-metadown)
20022 ("r" . org-metaright)
20023 ("l" . org-metaleft)
20024 ("R" . org-shiftmetaright)
20025 ("L" . org-shiftmetaleft)
20026 ("i" . (progn (forward-char 1) (call-interactively
20027 'org-insert-heading-respect-content)))
20028 ("^" . org-sort)
20029 ("w" . org-refile)
20030 ("a" . org-archive-subtree-default-with-confirmation)
20031 ("@" . org-mark-subtree)
20032 ("#" . org-toggle-comment)
20033 ("Clock Commands")
20034 ("I" . org-clock-in)
20035 ("O" . org-clock-out)
20036 ("Meta Data Editing")
20037 ("t" . org-todo)
20038 ("," . (org-priority))
20039 ("0" . (org-priority ?\ ))
20040 ("1" . (org-priority ?A))
20041 ("2" . (org-priority ?B))
20042 ("3" . (org-priority ?C))
20043 (":" . org-set-tags-command)
20044 ("e" . org-set-effort)
20045 ("E" . org-inc-effort)
20046 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20047 (org-entry-put (point) "APPT_WARNTIME" m)))
20048 ("Agenda Views etc")
20049 ("v" . org-agenda)
20050 ("/" . org-sparse-tree)
20051 ("Misc")
20052 ("o" . org-open-at-point)
20053 ("?" . org-speed-command-help)
20054 ("<" . (org-agenda-set-restriction-lock 'subtree))
20055 (">" . (org-agenda-remove-restriction-lock))
20057 "The default speed commands.")
20059 (defun org-print-speed-command (e)
20060 (if (> (length (car e)) 1)
20061 (progn
20062 (princ "\n")
20063 (princ (car e))
20064 (princ "\n")
20065 (princ (make-string (length (car e)) ?-))
20066 (princ "\n"))
20067 (princ (car e))
20068 (princ " ")
20069 (if (symbolp (cdr e))
20070 (princ (symbol-name (cdr e)))
20071 (prin1 (cdr e)))
20072 (princ "\n")))
20074 (defun org-speed-command-help ()
20075 "Show the available speed commands."
20076 (interactive)
20077 (if (not org-use-speed-commands)
20078 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20079 (with-output-to-temp-buffer "*Help*"
20080 (princ "User-defined Speed commands\n===========================\n")
20081 (mapc #'org-print-speed-command org-speed-commands-user)
20082 (princ "\n")
20083 (princ "Built-in Speed commands\n=======================\n")
20084 (mapc #'org-print-speed-command org-speed-commands-default))
20085 (with-current-buffer "*Help*"
20086 (setq truncate-lines t))))
20088 (defun org-speed-move-safe (cmd)
20089 "Execute CMD, but make sure that the cursor always ends up in a headline.
20090 If not, return to the original position and throw an error."
20091 (interactive)
20092 (let ((pos (point)))
20093 (call-interactively cmd)
20094 (unless (and (bolp) (org-at-heading-p))
20095 (goto-char pos)
20096 (error "Boundary reached while executing %s" cmd))))
20098 (defvar org-self-insert-command-undo-counter 0)
20100 (defvar org-table-auto-blank-field) ; defined in org-table.el
20101 (defvar org-speed-command nil)
20103 (defun org-speed-command-activate (keys)
20104 "Hook for activating single-letter speed commands.
20105 `org-speed-commands-default' specifies a minimal command set.
20106 Use `org-speed-commands-user' for further customization."
20107 (when (or (and (bolp) (looking-at org-outline-regexp))
20108 (and (functionp org-use-speed-commands)
20109 (funcall org-use-speed-commands)))
20110 (cdr (assoc keys (append org-speed-commands-user
20111 org-speed-commands-default)))))
20113 (defun org-babel-speed-command-activate (keys)
20114 "Hook for activating single-letter code block commands."
20115 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20116 (cdr (assoc keys org-babel-key-bindings))))
20118 (defcustom org-speed-command-hook
20119 '(org-speed-command-default-hook org-babel-speed-command-hook)
20120 "Hook for activating speed commands at strategic locations.
20121 Hook functions are called in sequence until a valid handler is
20122 found.
20124 Each hook takes a single argument, a user-pressed command key
20125 which is also a `self-insert-command' from the global map.
20127 Within the hook, examine the cursor position and the command key
20128 and return nil or a valid handler as appropriate. Handler could
20129 be one of an interactive command, a function, or a form.
20131 Set `org-use-speed-commands' to non-nil value to enable this
20132 hook. The default setting is `org-speed-command-activate'."
20133 :group 'org-structure
20134 :version "24.1"
20135 :type 'hook)
20137 (defun org-self-insert-command (N)
20138 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20139 If the cursor is in a table looking at whitespace, the whitespace is
20140 overwritten, and the table is not marked as requiring realignment."
20141 (interactive "p")
20142 (org-check-before-invisible-edit 'insert)
20143 (cond
20144 ((and org-use-speed-commands
20145 (let ((kv (this-command-keys-vector)))
20146 (setq org-speed-command
20147 (run-hook-with-args-until-success
20148 'org-speed-command-hook
20149 (make-string 1 (aref kv (1- (length kv))))))))
20150 (cond
20151 ((commandp org-speed-command)
20152 (setq this-command org-speed-command)
20153 (call-interactively org-speed-command))
20154 ((functionp org-speed-command)
20155 (funcall org-speed-command))
20156 ((and org-speed-command (listp org-speed-command))
20157 (eval org-speed-command))
20158 (t (let (org-use-speed-commands)
20159 (call-interactively 'org-self-insert-command)))))
20160 ((and
20161 (org-at-table-p)
20162 (progn
20163 ;; Check if we blank the field, and if that triggers align.
20164 (and (featurep 'org-table) org-table-auto-blank-field
20165 (memq last-command
20166 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20167 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20168 ;; Got extra space, this field does not determine
20169 ;; column width.
20170 (let (org-table-may-need-update) (org-table-blank-field))
20171 ;; No extra space, this field may determine column
20172 ;; width.
20173 (org-table-blank-field)))
20175 (eq N 1)
20176 (looking-at "[^|\n]* \\( \\)|"))
20177 ;; There is room for insertion without re-aligning the table.
20178 (delete-region (match-beginning 1) (match-end 1))
20179 (self-insert-command N))
20181 (setq org-table-may-need-update t)
20182 (self-insert-command N)
20183 (org-fix-tags-on-the-fly)
20184 (when org-self-insert-cluster-for-undo
20185 (if (not (eq last-command 'org-self-insert-command))
20186 (setq org-self-insert-command-undo-counter 1)
20187 (if (>= org-self-insert-command-undo-counter 20)
20188 (setq org-self-insert-command-undo-counter 1)
20189 (and (> org-self-insert-command-undo-counter 0)
20190 buffer-undo-list (listp buffer-undo-list)
20191 (not (cadr buffer-undo-list)) ; remove nil entry
20192 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20193 (setq org-self-insert-command-undo-counter
20194 (1+ org-self-insert-command-undo-counter))))))))
20196 (defun org-check-before-invisible-edit (kind)
20197 "Check is editing if kind KIND would be dangerous with invisible text around.
20198 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20199 ;; First, try to get out of here as quickly as possible, to reduce overhead
20200 (when (and org-catch-invisible-edits
20201 (or (not (boundp 'visible-mode)) (not visible-mode))
20202 (or (get-char-property (point) 'invisible)
20203 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20204 ;; OK, we need to take a closer look
20205 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20206 (invisible-before-point (unless (bobp) (get-char-property
20207 (1- (point)) 'invisible)))
20208 (border-and-ok-direction
20210 ;; Check if we are acting predictably before invisible text
20211 (and invisible-at-point (not invisible-before-point)
20212 (memq kind '(insert delete-backward)))
20213 ;; Check if we are acting predictably after invisible text
20214 ;; This works not well, and I have turned it off. It seems
20215 ;; better to always show and stop after invisible text.
20216 ;; (and (not invisible-at-point) invisible-before-point
20217 ;; (memq kind '(insert delete)))
20219 (when (or (memq invisible-at-point '(outline org-hide-block t))
20220 (memq invisible-before-point '(outline org-hide-block t)))
20221 (when (eq org-catch-invisible-edits 'error)
20222 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20223 (if (and org-custom-properties-overlays
20224 (y-or-n-p "Display invisible properties in this buffer? "))
20225 (org-toggle-custom-properties-visibility)
20226 ;; Make the area visible
20227 (save-excursion
20228 (when invisible-before-point
20229 (goto-char (previous-single-char-property-change
20230 (point) 'invisible)))
20231 (outline-show-subtree))
20232 (cond
20233 ((eq org-catch-invisible-edits 'show)
20234 ;; That's it, we do the edit after showing
20235 (message
20236 "Unfolding invisible region around point before editing")
20237 (sit-for 1))
20238 ((and (eq org-catch-invisible-edits 'smart)
20239 border-and-ok-direction)
20240 (message "Unfolding invisible region around point before editing"))
20242 ;; Don't do the edit, make the user repeat it in full visibility
20243 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20245 (defun org-fix-tags-on-the-fly ()
20246 "Align tags in headline at point.
20247 Unlike to `org-set-tags', it ignores region and sorting."
20248 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20249 (org-at-heading-p))
20250 (let ((org-ignore-region t)
20251 (org-tags-sort-function nil))
20252 (org-set-tags nil t))))
20254 (defun org-delete-backward-char (N)
20255 "Like `delete-backward-char', insert whitespace at field end in tables.
20256 When deleting backwards, in tables this function will insert whitespace in
20257 front of the next \"|\" separator, to keep the table aligned. The table will
20258 still be marked for re-alignment if the field did fill the entire column,
20259 because, in this case the deletion might narrow the column."
20260 (interactive "p")
20261 (save-match-data
20262 (org-check-before-invisible-edit 'delete-backward)
20263 (if (and (org-at-table-p)
20264 (eq N 1)
20265 (string-match "|" (buffer-substring (point-at-bol) (point)))
20266 (looking-at ".*?|"))
20267 (let ((pos (point))
20268 (noalign (looking-at "[^|\n\r]* |"))
20269 (c org-table-may-need-update))
20270 (backward-delete-char N)
20271 (unless overwrite-mode
20272 (skip-chars-forward "^|")
20273 (insert " ")
20274 (goto-char (1- pos)))
20275 ;; noalign: if there were two spaces at the end, this field
20276 ;; does not determine the width of the column.
20277 (when noalign (setq org-table-may-need-update c)))
20278 (backward-delete-char N)
20279 (org-fix-tags-on-the-fly))))
20281 (defun org-delete-char (N)
20282 "Like `delete-char', but insert whitespace at field end in tables.
20283 When deleting characters, in tables this function will insert whitespace in
20284 front of the next \"|\" separator, to keep the table aligned. The table will
20285 still be marked for re-alignment if the field did fill the entire column,
20286 because, in this case the deletion might narrow the column."
20287 (interactive "p")
20288 (save-match-data
20289 (org-check-before-invisible-edit 'delete)
20290 (if (and (org-at-table-p)
20291 (not (bolp))
20292 (not (= (char-after) ?|))
20293 (eq N 1))
20294 (if (looking-at ".*?|")
20295 (let ((pos (point))
20296 (noalign (looking-at "[^|\n\r]* |"))
20297 (c org-table-may-need-update))
20298 (replace-match
20299 (concat (substring (match-string 0) 1 -1) " |") nil t)
20300 (goto-char pos)
20301 ;; noalign: if there were two spaces at the end, this field
20302 ;; does not determine the width of the column.
20303 (when noalign (setq org-table-may-need-update c)))
20304 (delete-char N))
20305 (delete-char N)
20306 (org-fix-tags-on-the-fly))))
20308 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20309 (put 'org-self-insert-command 'delete-selection
20310 (lambda ()
20311 (not (run-hook-with-args-until-success
20312 'self-insert-uses-region-functions))))
20313 (put 'orgtbl-self-insert-command 'delete-selection
20314 (lambda ()
20315 (not (run-hook-with-args-until-success
20316 'self-insert-uses-region-functions))))
20317 (put 'org-delete-char 'delete-selection 'supersede)
20318 (put 'org-delete-backward-char 'delete-selection 'supersede)
20319 (put 'org-yank 'delete-selection 'yank)
20321 ;; Make `flyspell-mode' delay after some commands
20322 (put 'org-self-insert-command 'flyspell-delayed t)
20323 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20324 (put 'org-delete-char 'flyspell-delayed t)
20325 (put 'org-delete-backward-char 'flyspell-delayed t)
20327 ;; Make pabbrev-mode expand after Org mode commands
20328 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20329 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20331 (defun org-remap (map &rest commands)
20332 "In MAP, remap the functions given in COMMANDS.
20333 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20334 (let (new old)
20335 (while commands
20336 (setq old (pop commands) new (pop commands))
20337 (org-defkey map (vector 'remap old) new))))
20339 (defun org-transpose-words ()
20340 "Transpose words for Org.
20341 This uses the `org-mode-transpose-word-syntax-table' syntax
20342 table, which interprets characters in `org-emphasis-alist' as
20343 word constituents."
20344 (interactive)
20345 (with-syntax-table org-mode-transpose-word-syntax-table
20346 (call-interactively 'transpose-words)))
20347 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20349 (when (eq org-enable-table-editor 'optimized)
20350 ;; If the user wants maximum table support, we need to hijack
20351 ;; some standard editing functions
20352 (org-remap org-mode-map
20353 'self-insert-command 'org-self-insert-command
20354 'delete-char 'org-delete-char
20355 'delete-backward-char 'org-delete-backward-char)
20356 (org-defkey org-mode-map "|" 'org-force-self-insert))
20358 (defvar org-ctrl-c-ctrl-c-hook nil
20359 "Hook for functions attaching themselves to `C-c C-c'.
20361 This can be used to add additional functionality to the C-c C-c
20362 key which executes context-dependent commands. This hook is run
20363 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20364 run after the last test.
20366 Each function will be called with no arguments. The function
20367 must check if the context is appropriate for it to act. If yes,
20368 it should do its thing and then return a non-nil value. If the
20369 context is wrong, just do nothing and return nil.")
20371 (defvar org-ctrl-c-ctrl-c-final-hook nil
20372 "Hook for functions attaching themselves to `C-c C-c'.
20374 This can be used to add additional functionality to the C-c C-c
20375 key which executes context-dependent commands. This hook is run
20376 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20377 before the first test.
20379 Each function will be called with no arguments. The function
20380 must check if the context is appropriate for it to act. If yes,
20381 it should do its thing and then return a non-nil value. If the
20382 context is wrong, just do nothing and return nil.")
20384 (defvar org-tab-first-hook nil
20385 "Hook for functions to attach themselves to TAB.
20386 See `org-ctrl-c-ctrl-c-hook' for more information.
20387 This hook runs as the first action when TAB is pressed, even before
20388 `org-cycle' messes around with the `outline-regexp' to cater for
20389 inline tasks and plain list item folding.
20390 If any function in this hook returns t, any other actions that
20391 would have been caused by TAB (such as table field motion or visibility
20392 cycling) will not occur.")
20394 (defvar org-tab-after-check-for-table-hook nil
20395 "Hook for functions to attach themselves to TAB.
20396 See `org-ctrl-c-ctrl-c-hook' for more information.
20397 This hook runs after it has been established that the cursor is not in a
20398 table, but before checking if the cursor is in a headline or if global cycling
20399 should be done.
20400 If any function in this hook returns t, not other actions like visibility
20401 cycling will be done.")
20403 (defvar org-tab-after-check-for-cycling-hook nil
20404 "Hook for functions to attach themselves to TAB.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.
20406 This hook runs after it has been established that not table field motion and
20407 not visibility should be done because of current context. This is probably
20408 the place where a package like yasnippets can hook in.")
20410 (defvar org-tab-before-tab-emulation-hook nil
20411 "Hook for functions to attach themselves to TAB.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.
20413 This hook runs after every other options for TAB have been exhausted, but
20414 before indentation and \t insertion takes place.")
20416 (defvar org-metaleft-hook nil
20417 "Hook for functions attaching themselves to `M-left'.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.")
20419 (defvar org-metaright-hook nil
20420 "Hook for functions attaching themselves to `M-right'.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.")
20422 (defvar org-metaup-hook nil
20423 "Hook for functions attaching themselves to `M-up'.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.")
20425 (defvar org-metadown-hook nil
20426 "Hook for functions attaching themselves to `M-down'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-shiftmetaleft-hook nil
20429 "Hook for functions attaching themselves to `M-S-left'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftmetaright-hook nil
20432 "Hook for functions attaching themselves to `M-S-right'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftmetaup-hook nil
20435 "Hook for functions attaching themselves to `M-S-up'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-shiftmetadown-hook nil
20438 "Hook for functions attaching themselves to `M-S-down'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-metareturn-hook nil
20441 "Hook for functions attaching themselves to `M-RET'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftup-hook nil
20444 "Hook for functions attaching themselves to `S-up'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftup-final-hook nil
20447 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
20451 "Hook for functions attaching themselves to `S-down'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftdown-final-hook nil
20454 "Hook for functions attaching themselves to `S-down'.
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.")
20457 (defvar org-shiftleft-hook nil
20458 "Hook for functions attaching themselves to `S-left'.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-shiftleft-final-hook nil
20461 "Hook for functions attaching themselves to `S-left'.
20462 This one runs after all other options except shift-select have been excluded.
20463 See `org-ctrl-c-ctrl-c-hook' for more information.")
20464 (defvar org-shiftright-hook nil
20465 "Hook for functions attaching themselves to `S-right'.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.")
20467 (defvar org-shiftright-final-hook nil
20468 "Hook for functions attaching themselves to `S-right'.
20469 This one runs after all other options except shift-select have been excluded.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defun org-modifier-cursor-error ()
20473 "Throw an error, a modified cursor command was applied in wrong context."
20474 (user-error "This command is active in special context like tables, headlines or items"))
20476 (defun org-shiftselect-error ()
20477 "Throw an error because Shift-Cursor command was applied in wrong context."
20478 (if (and (boundp 'shift-select-mode) shift-select-mode)
20479 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20480 (user-error "This command works only in special context like headlines or timestamps")))
20482 (defun org-call-for-shift-select (cmd)
20483 (let ((this-command-keys-shift-translated t))
20484 (call-interactively cmd)))
20486 (defun org-shifttab (&optional arg)
20487 "Global visibility cycling or move to previous table field.
20488 Call `org-table-previous-field' within a table.
20489 When ARG is nil, cycle globally through visibility states.
20490 When ARG is a numeric prefix, show contents of this level."
20491 (interactive "P")
20492 (cond
20493 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20494 ((integerp arg)
20495 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20496 (message "Content view to level: %d" arg)
20497 (org-content (prefix-numeric-value arg2))
20498 (org-cycle-show-empty-lines t)
20499 (setq org-cycle-global-status 'overview)))
20500 (t (call-interactively 'org-global-cycle))))
20502 (defun org-shiftmetaleft ()
20503 "Promote subtree or delete table column.
20504 Calls `org-promote-subtree', `org-outdent-item-tree', or
20505 `org-table-delete-column', depending on context. See the
20506 individual commands for more information."
20507 (interactive)
20508 (cond
20509 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20510 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20511 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20512 ((if (not (org-region-active-p)) (org-at-item-p)
20513 (save-excursion (goto-char (region-beginning))
20514 (org-at-item-p)))
20515 (call-interactively 'org-outdent-item-tree))
20516 (t (org-modifier-cursor-error))))
20518 (defun org-shiftmetaright ()
20519 "Demote subtree or insert table column.
20520 Calls `org-demote-subtree', `org-indent-item-tree', or
20521 `org-table-insert-column', depending on context. See the
20522 individual commands for more information."
20523 (interactive)
20524 (cond
20525 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20526 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20527 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20528 ((if (not (org-region-active-p)) (org-at-item-p)
20529 (save-excursion (goto-char (region-beginning))
20530 (org-at-item-p)))
20531 (call-interactively 'org-indent-item-tree))
20532 (t (org-modifier-cursor-error))))
20534 (defun org-shiftmetaup (&optional _arg)
20535 "Drag the line at point up.
20536 In a table, kill the current row.
20537 On a clock timestamp, update the value of the timestamp like `S-<up>'
20538 but also adjust the previous clocked item in the clock history.
20539 Everywhere else, drag the line at point up."
20540 (interactive "P")
20541 (cond
20542 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20543 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20544 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20545 (call-interactively 'org-timestamp-up)))
20546 (t (call-interactively 'org-drag-line-backward))))
20548 (defun org-shiftmetadown (&optional _arg)
20549 "Drag the line at point down.
20550 In a table, insert an empty row at the current line.
20551 On a clock timestamp, update the value of the timestamp like `S-<down>'
20552 but also adjust the previous clocked item in the clock history.
20553 Everywhere else, drag the line at point down."
20554 (interactive "P")
20555 (cond
20556 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20557 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20558 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20559 (call-interactively 'org-timestamp-down)))
20560 (t (call-interactively 'org-drag-line-forward))))
20562 (defsubst org-hidden-tree-error ()
20563 (user-error
20564 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20566 (defun org-metaleft (&optional _arg)
20567 "Promote heading, list item at point or move table column left.
20569 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20570 depending on context. With no specific context, calls the Emacs
20571 default `backward-word'. See the individual commands for more
20572 information.
20574 This function runs the hook `org-metaleft-hook' as a first step,
20575 and returns at first non-nil value."
20576 (interactive "P")
20577 (cond
20578 ((run-hook-with-args-until-success 'org-metaleft-hook))
20579 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20580 ((org-with-limited-levels
20581 (or (org-at-heading-p)
20582 (and (org-region-active-p)
20583 (save-excursion
20584 (goto-char (region-beginning))
20585 (org-at-heading-p)))))
20586 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20587 (call-interactively 'org-do-promote))
20588 ;; At an inline task.
20589 ((org-at-heading-p)
20590 (call-interactively 'org-inlinetask-promote))
20591 ((or (org-at-item-p)
20592 (and (org-region-active-p)
20593 (save-excursion
20594 (goto-char (region-beginning))
20595 (org-at-item-p))))
20596 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20597 (call-interactively 'org-outdent-item))
20598 (t (call-interactively 'backward-word))))
20600 (defun org-metaright (&optional _arg)
20601 "Demote heading, list item at point or move table column right.
20603 In front of a drawer or a block keyword, indent it correctly.
20605 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20606 `org-indent-drawer' or `org-indent-block' depending on context.
20607 With no specific context, calls the Emacs default `forward-word'.
20608 See the individual commands for more information.
20610 This function runs the hook `org-metaright-hook' as a first step,
20611 and returns at first non-nil value."
20612 (interactive "P")
20613 (cond
20614 ((run-hook-with-args-until-success 'org-metaright-hook))
20615 ((org-at-table-p) (call-interactively 'org-table-move-column))
20616 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20617 ((org-at-block-p) (call-interactively 'org-indent-block))
20618 ((org-with-limited-levels
20619 (or (org-at-heading-p)
20620 (and (org-region-active-p)
20621 (save-excursion
20622 (goto-char (region-beginning))
20623 (org-at-heading-p)))))
20624 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20625 (call-interactively 'org-do-demote))
20626 ;; At an inline task.
20627 ((org-at-heading-p)
20628 (call-interactively 'org-inlinetask-demote))
20629 ((or (org-at-item-p)
20630 (and (org-region-active-p)
20631 (save-excursion
20632 (goto-char (region-beginning))
20633 (org-at-item-p))))
20634 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20635 (call-interactively 'org-indent-item))
20636 (t (call-interactively 'forward-word))))
20638 (defun org-check-for-hidden (what)
20639 "Check if there are hidden headlines/items in the current visual line.
20640 WHAT can be either `headlines' or `items'. If the current line is
20641 an outline or item heading and it has a folded subtree below it,
20642 this function returns t, nil otherwise."
20643 (let ((re (cond
20644 ((eq what 'headlines) org-outline-regexp-bol)
20645 ((eq what 'items) (org-item-beginning-re))
20646 (t (error "This should not happen"))))
20647 beg end)
20648 (save-excursion
20649 (catch 'exit
20650 (unless (org-region-active-p)
20651 (setq beg (point-at-bol))
20652 (beginning-of-line 2)
20653 (while (and (not (eobp)) ;; this is like `next-line'
20654 (get-char-property (1- (point)) 'invisible))
20655 (beginning-of-line 2))
20656 (setq end (point))
20657 (goto-char beg)
20658 (goto-char (point-at-eol))
20659 (setq end (max end (point)))
20660 (while (re-search-forward re end t)
20661 (when (get-char-property (match-beginning 0) 'invisible)
20662 (throw 'exit t))))
20663 nil))))
20665 (defun org-metaup (&optional _arg)
20666 "Move subtree up or move table row up.
20667 Calls `org-move-subtree-up' or `org-table-move-row' or
20668 `org-move-item-up', depending on context. See the individual commands
20669 for more information."
20670 (interactive "P")
20671 (cond
20672 ((run-hook-with-args-until-success 'org-metaup-hook))
20673 ((org-region-active-p)
20674 (let* ((a (min (region-beginning) (region-end)))
20675 (b (1- (max (region-beginning) (region-end))))
20676 (c (save-excursion (goto-char a)
20677 (move-beginning-of-line 0)))
20678 (d (save-excursion (goto-char a)
20679 (move-end-of-line 0) (point))))
20680 (transpose-regions a b c d)
20681 (goto-char c)))
20682 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20683 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20684 ((org-at-item-p) (call-interactively 'org-move-item-up))
20685 (t (org-drag-element-backward))))
20687 (defun org-metadown (&optional _arg)
20688 "Move subtree down or move table row down.
20689 Calls `org-move-subtree-down' or `org-table-move-row' or
20690 `org-move-item-down', depending on context. See the individual
20691 commands for more information."
20692 (interactive "P")
20693 (cond
20694 ((run-hook-with-args-until-success 'org-metadown-hook))
20695 ((org-region-active-p)
20696 (let* ((a (min (region-beginning) (region-end)))
20697 (b (max (region-beginning) (region-end)))
20698 (c (save-excursion (goto-char b)
20699 (move-beginning-of-line 1)))
20700 (d (save-excursion (goto-char b)
20701 (move-end-of-line 1) (1+ (point)))))
20702 (transpose-regions a b c d)
20703 (goto-char d)))
20704 ((org-at-table-p) (call-interactively 'org-table-move-row))
20705 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20706 ((org-at-item-p) (call-interactively 'org-move-item-down))
20707 (t (org-drag-element-forward))))
20709 (defun org-shiftup (&optional arg)
20710 "Increase item in timestamp or increase priority of current headline.
20711 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20712 depending on context. See the individual commands for more information."
20713 (interactive "P")
20714 (cond
20715 ((run-hook-with-args-until-success 'org-shiftup-hook))
20716 ((and org-support-shift-select (org-region-active-p))
20717 (org-call-for-shift-select 'previous-line))
20718 ((org-at-timestamp-p t)
20719 (call-interactively (if org-edit-timestamp-down-means-later
20720 'org-timestamp-down 'org-timestamp-up)))
20721 ((and (not (eq org-support-shift-select 'always))
20722 org-enable-priority-commands
20723 (org-at-heading-p))
20724 (call-interactively 'org-priority-up))
20725 ((and (not org-support-shift-select) (org-at-item-p))
20726 (call-interactively 'org-previous-item))
20727 ((org-clocktable-try-shift 'up arg))
20728 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20729 (org-support-shift-select
20730 (org-call-for-shift-select 'previous-line))
20731 (t (org-shiftselect-error))))
20733 (defun org-shiftdown (&optional arg)
20734 "Decrease item in timestamp or decrease priority of current headline.
20735 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20736 depending on context. See the individual commands for more information."
20737 (interactive "P")
20738 (cond
20739 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20740 ((and org-support-shift-select (org-region-active-p))
20741 (org-call-for-shift-select 'next-line))
20742 ((org-at-timestamp-p t)
20743 (call-interactively (if org-edit-timestamp-down-means-later
20744 'org-timestamp-up 'org-timestamp-down)))
20745 ((and (not (eq org-support-shift-select 'always))
20746 org-enable-priority-commands
20747 (org-at-heading-p))
20748 (call-interactively 'org-priority-down))
20749 ((and (not org-support-shift-select) (org-at-item-p))
20750 (call-interactively 'org-next-item))
20751 ((org-clocktable-try-shift 'down arg))
20752 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20753 (org-support-shift-select
20754 (org-call-for-shift-select 'next-line))
20755 (t (org-shiftselect-error))))
20757 (defun org-shiftright (&optional arg)
20758 "Cycle the thing at point or in the current line, depending on context.
20759 Depending on context, this does one of the following:
20761 - switch a timestamp at point one day into the future
20762 - on a headline, switch to the next TODO keyword.
20763 - on an item, switch entire list to the next bullet type
20764 - on a property line, switch to the next allowed value
20765 - on a clocktable definition line, move time block into the future"
20766 (interactive "P")
20767 (cond
20768 ((run-hook-with-args-until-success 'org-shiftright-hook))
20769 ((and org-support-shift-select (org-region-active-p))
20770 (org-call-for-shift-select 'forward-char))
20771 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20772 ((and (not (eq org-support-shift-select 'always))
20773 (org-at-heading-p))
20774 (let ((org-inhibit-logging
20775 (not org-treat-S-cursor-todo-selection-as-state-change))
20776 (org-inhibit-blocking
20777 (not org-treat-S-cursor-todo-selection-as-state-change)))
20778 (org-call-with-arg 'org-todo 'right)))
20779 ((or (and org-support-shift-select
20780 (not (eq org-support-shift-select 'always))
20781 (org-at-item-bullet-p))
20782 (and (not org-support-shift-select) (org-at-item-p)))
20783 (org-call-with-arg 'org-cycle-list-bullet nil))
20784 ((and (not (eq org-support-shift-select 'always))
20785 (org-at-property-p))
20786 (call-interactively 'org-property-next-allowed-value))
20787 ((org-clocktable-try-shift 'right arg))
20788 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20789 (org-support-shift-select
20790 (org-call-for-shift-select 'forward-char))
20791 (t (org-shiftselect-error))))
20793 (defun org-shiftleft (&optional arg)
20794 "Cycle the thing at point or in the current line, depending on context.
20795 Depending on context, this does one of the following:
20797 - switch a timestamp at point one day into the past
20798 - on a headline, switch to the previous TODO keyword.
20799 - on an item, switch entire list to the previous bullet type
20800 - on a property line, switch to the previous allowed value
20801 - on a clocktable definition line, move time block into the past"
20802 (interactive "P")
20803 (cond
20804 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20805 ((and org-support-shift-select (org-region-active-p))
20806 (org-call-for-shift-select 'backward-char))
20807 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20808 ((and (not (eq org-support-shift-select 'always))
20809 (org-at-heading-p))
20810 (let ((org-inhibit-logging
20811 (not org-treat-S-cursor-todo-selection-as-state-change))
20812 (org-inhibit-blocking
20813 (not org-treat-S-cursor-todo-selection-as-state-change)))
20814 (org-call-with-arg 'org-todo 'left)))
20815 ((or (and org-support-shift-select
20816 (not (eq org-support-shift-select 'always))
20817 (org-at-item-bullet-p))
20818 (and (not org-support-shift-select) (org-at-item-p)))
20819 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20820 ((and (not (eq org-support-shift-select 'always))
20821 (org-at-property-p))
20822 (call-interactively 'org-property-previous-allowed-value))
20823 ((org-clocktable-try-shift 'left arg))
20824 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20825 (org-support-shift-select
20826 (org-call-for-shift-select 'backward-char))
20827 (t (org-shiftselect-error))))
20829 (defun org-shiftcontrolright ()
20830 "Switch to next TODO set."
20831 (interactive)
20832 (cond
20833 ((and org-support-shift-select (org-region-active-p))
20834 (org-call-for-shift-select 'forward-word))
20835 ((and (not (eq org-support-shift-select 'always))
20836 (org-at-heading-p))
20837 (org-call-with-arg 'org-todo 'nextset))
20838 (org-support-shift-select
20839 (org-call-for-shift-select 'forward-word))
20840 (t (org-shiftselect-error))))
20842 (defun org-shiftcontrolleft ()
20843 "Switch to previous TODO set."
20844 (interactive)
20845 (cond
20846 ((and org-support-shift-select (org-region-active-p))
20847 (org-call-for-shift-select 'backward-word))
20848 ((and (not (eq org-support-shift-select 'always))
20849 (org-at-heading-p))
20850 (org-call-with-arg 'org-todo 'previousset))
20851 (org-support-shift-select
20852 (org-call-for-shift-select 'backward-word))
20853 (t (org-shiftselect-error))))
20855 (defun org-shiftcontrolup (&optional n)
20856 "Change timestamps synchronously up in CLOCK log lines.
20857 Optional argument N tells to change by that many units."
20858 (interactive "P")
20859 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20860 (let (org-support-shift-select)
20861 (org-clock-timestamps-up n))
20862 (user-error "Not at a clock log")))
20864 (defun org-shiftcontroldown (&optional n)
20865 "Change timestamps synchronously down in CLOCK log lines.
20866 Optional argument N tells to change by that many units."
20867 (interactive "P")
20868 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20869 (let (org-support-shift-select)
20870 (org-clock-timestamps-down n))
20871 (user-error "Not at a clock log")))
20873 (defun org-increase-number-at-point (&optional inc)
20874 "Increment the number at point.
20875 With an optional prefix numeric argument INC, increment using
20876 this numeric value."
20877 (interactive "p")
20878 (if (not (number-at-point))
20879 (user-error "Not on a number")
20880 (unless inc (setq inc 1))
20881 (let ((pos (point))
20882 (beg (skip-chars-backward "-+^/*0-9eE."))
20883 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20884 (setq nap (buffer-substring-no-properties
20885 (+ pos beg) (+ pos beg end)))
20886 (delete-region (+ pos beg) (+ pos beg end))
20887 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20888 (when (org-at-table-p)
20889 (org-table-align)
20890 (org-table-end-of-field 1))))
20892 (defun org-decrease-number-at-point (&optional inc)
20893 "Decrement the number at point.
20894 With an optional prefix numeric argument INC, decrement using
20895 this numeric value."
20896 (interactive "p")
20897 (org-increase-number-at-point (- (or inc 1))))
20899 (defun org-ctrl-c-ret ()
20900 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20901 (interactive)
20902 (cond
20903 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20904 (t (call-interactively 'org-insert-heading))))
20906 (defun org-find-visible ()
20907 (let ((s (point)))
20908 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20909 (get-char-property s 'invisible)))
20911 (defun org-find-invisible ()
20912 (let ((s (point)))
20913 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20914 (not (get-char-property s 'invisible))))
20917 (defun org-copy-visible (beg end)
20918 "Copy the visible parts of the region."
20919 (interactive "r")
20920 (let (snippets s)
20921 (save-excursion
20922 (save-restriction
20923 (narrow-to-region beg end)
20924 (setq s (goto-char (point-min)))
20925 (while (not (= (point) (point-max)))
20926 (goto-char (org-find-invisible))
20927 (push (buffer-substring s (point)) snippets)
20928 (setq s (goto-char (org-find-visible))))))
20929 (kill-new (apply 'concat (nreverse snippets)))))
20931 (defun org-copy-special ()
20932 "Copy region in table or copy current subtree.
20933 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20934 context. See the individual commands for more information."
20935 (interactive)
20936 (call-interactively
20937 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20939 (defun org-cut-special ()
20940 "Cut region in table or cut current subtree.
20941 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20942 context. See the individual commands for more information."
20943 (interactive)
20944 (call-interactively
20945 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20947 (defun org-paste-special (arg)
20948 "Paste rectangular region into table, or past subtree relative to level.
20949 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20950 See the individual commands for more information."
20951 (interactive "P")
20952 (if (org-at-table-p)
20953 (org-table-paste-rectangle)
20954 (org-paste-subtree arg)))
20956 (defun org-edit-special (&optional arg)
20957 "Call a special editor for the element at point.
20958 When at a table, call the formula editor with `org-table-edit-formulas'.
20959 When in a source code block, call `org-edit-src-code'.
20960 When in a fixed-width region, call `org-edit-fixed-width-region'.
20961 When in an export block, call `org-edit-export-block'.
20962 When at an #+INCLUDE keyword, visit the included file.
20963 When at a footnote reference, call `org-edit-footnote-reference'
20964 On a link, call `ffap' to visit the link at point.
20965 Otherwise, return a user error."
20966 (interactive "P")
20967 (let ((element (org-element-at-point)))
20968 (barf-if-buffer-read-only)
20969 (pcase (org-element-type element)
20970 (`src-block
20971 (if (not arg) (org-edit-src-code)
20972 (let* ((info (org-babel-get-src-block-info))
20973 (lang (nth 0 info))
20974 (params (nth 2 info))
20975 (session (cdr (assq :session params))))
20976 (if (not session) (org-edit-src-code)
20977 ;; At a src-block with a session and function called with
20978 ;; an ARG: switch to the buffer related to the inferior
20979 ;; process.
20980 (switch-to-buffer
20981 (funcall (intern (concat "org-babel-prep-session:" lang))
20982 session params))))))
20983 (`keyword
20984 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20985 (org-open-link-from-string
20986 (format "[[%s]]"
20987 (expand-file-name
20988 (let ((value (org-element-property :value element)))
20989 (cond ((not (org-string-nw-p value))
20990 (user-error "No file to edit"))
20991 ((string-match "\\`\"\\(.*?\\)\"" value)
20992 (match-string 1 value))
20993 ((string-match "\\`[^ \t\"]\\S-*" value)
20994 (match-string 0 value))
20995 (t (user-error "No valid file specified")))))))
20996 (user-error "No special environment to edit here")))
20997 (`table
20998 (if (eq (org-element-property :type element) 'table.el)
20999 (org-edit-table.el)
21000 (call-interactively 'org-table-edit-formulas)))
21001 ;; Only Org tables contain `table-row' type elements.
21002 (`table-row (call-interactively 'org-table-edit-formulas))
21003 (`example-block (org-edit-src-code))
21004 (`export-block (org-edit-export-block))
21005 (`fixed-width (org-edit-fixed-width-region))
21007 ;; No notable element at point. Though, we may be at a link or
21008 ;; a footnote reference, which are objects. Thus, scan deeper.
21009 (let ((context (org-element-context element)))
21010 (pcase (org-element-type context)
21011 (`footnote-reference (org-edit-footnote-reference))
21012 (`inline-src-block (org-edit-inline-src-code))
21013 (`link (call-interactively #'ffap))
21014 (_ (user-error "No special environment to edit here"))))))))
21016 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21017 (defun org-ctrl-c-ctrl-c (&optional arg)
21018 "Set tags in headline, or update according to changed information at point.
21020 This command does many different things, depending on context:
21022 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21023 this is what we do.
21025 - If the cursor is on a statistics cookie, update it.
21027 - If the cursor is in a headline, prompt for tags and insert them
21028 into the current line, aligned to `org-tags-column'. When called
21029 with prefix arg, realign all tags in the current buffer.
21031 - If the cursor is in one of the special #+KEYWORD lines, this
21032 triggers scanning the buffer for these lines and updating the
21033 information.
21035 - If the cursor is inside a table, realign the table. This command
21036 works even if the automatic table editor has been turned off.
21038 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21039 the entire table.
21041 - If the cursor is at a footnote reference or definition, jump to
21042 the corresponding definition or references, respectively.
21044 - If the cursor is a the beginning of a dynamic block, update it.
21046 - If the current buffer is a capture buffer, close note and file it.
21048 - If the cursor is on a <<<target>>>, update radio targets and
21049 corresponding links in this buffer.
21051 - If the cursor is on a numbered item in a plain list, renumber the
21052 ordered list.
21054 - If the cursor is on a checkbox, toggle it.
21056 - If the cursor is on a code block, evaluate it. The variable
21057 `org-confirm-babel-evaluate' can be used to control prompting
21058 before code block evaluation, by default every code block
21059 evaluation requires confirmation. Code block evaluation can be
21060 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21061 (interactive "P")
21062 (cond
21063 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21064 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21065 (org-remove-occur-highlights)
21066 (message "Temporary highlights/overlays removed from current buffer"))
21067 ((and (local-variable-p 'org-finish-function)
21068 (fboundp org-finish-function))
21069 (funcall org-finish-function))
21070 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21072 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21073 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21074 (user-error
21075 (substitute-command-keys
21076 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))
21077 (let* ((context (org-element-context))
21078 (type (org-element-type context)))
21079 (cl-case type
21080 ;; When at a link, act according to the parent instead.
21081 (link (setq context (org-element-property :parent context))
21082 (setq type (org-element-type context)))
21083 ;; Unsupported object types: refer to the first supported
21084 ;; element or object containing it.
21085 ((bold code entity export-snippet inline-babel-call inline-src-block
21086 italic latex-fragment line-break macro strike-through subscript
21087 superscript underline verbatim)
21088 (setq context
21089 (org-element-lineage
21090 context '(paragraph radio-target table-cell verse-block)))
21091 (setq type (org-element-type context))))
21092 ;; For convenience: at the first line of a paragraph on the
21093 ;; same line as an item, apply function on that item instead.
21094 (when (eq type 'paragraph)
21095 (let ((parent (org-element-property :parent context)))
21096 (when (and (eq (org-element-type parent) 'item)
21097 (= (line-beginning-position)
21098 (org-element-property :begin parent)))
21099 (setq context parent)
21100 (setq type 'item))))
21101 ;; Act according to type of element or object at point.
21102 (pcase type
21103 (`clock (org-clock-update-time-maybe))
21104 (`dynamic-block
21105 (save-excursion
21106 (goto-char (org-element-property :post-affiliated context))
21107 (org-update-dblock)))
21108 (`footnote-definition
21109 (goto-char (org-element-property :post-affiliated context))
21110 (call-interactively 'org-footnote-action))
21111 (`footnote-reference (call-interactively 'org-footnote-action))
21112 ((or `headline `inlinetask)
21113 (save-excursion (goto-char (org-element-property :begin context))
21114 (call-interactively #'org-set-tags)))
21115 (`item
21116 ;; At an item: a double C-u set checkbox to "[-]"
21117 ;; unconditionally, whereas a single one will toggle its
21118 ;; presence. Without a universal argument, if the item
21119 ;; has a checkbox, toggle it. Otherwise repair the list.
21120 (let* ((box (org-element-property :checkbox context))
21121 (struct (org-element-property :structure context))
21122 (old-struct (copy-tree struct))
21123 (parents (org-list-parents-alist struct))
21124 (prevs (org-list-prevs-alist struct))
21125 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21126 (org-list-set-checkbox
21127 (org-element-property :begin context) struct
21128 (cond ((equal arg '(16)) "[-]")
21129 ((and (not box) (equal arg '(4))) "[ ]")
21130 ((or (not box) (equal arg '(4))) nil)
21131 ((eq box 'on) "[ ]")
21132 (t "[X]")))
21133 ;; Mimic `org-list-write-struct' but with grabbing
21134 ;; a return value from `org-list-struct-fix-box'.
21135 (org-list-struct-fix-ind struct parents 2)
21136 (org-list-struct-fix-item-end struct)
21137 (org-list-struct-fix-bul struct prevs)
21138 (org-list-struct-fix-ind struct parents)
21139 (let ((block-item
21140 (org-list-struct-fix-box struct parents prevs orderedp)))
21141 (if (and box (equal struct old-struct))
21142 (if (equal arg '(16))
21143 (message "Checkboxes already reset")
21144 (user-error "Cannot toggle this checkbox: %s"
21145 (if (eq box 'on)
21146 "all subitems checked"
21147 "unchecked subitems")))
21148 (org-list-struct-apply-struct struct old-struct)
21149 (org-update-checkbox-count-maybe))
21150 (when block-item
21151 (message "Checkboxes were removed due to empty box at line %d"
21152 (org-current-line block-item))))))
21153 (`keyword
21154 (let ((org-inhibit-startup-visibility-stuff t)
21155 (org-startup-align-all-tables nil))
21156 (when (boundp 'org-table-coordinate-overlays)
21157 (mapc #'delete-overlay org-table-coordinate-overlays)
21158 (setq org-table-coordinate-overlays nil))
21159 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21160 (message "Local setup has been refreshed"))
21161 (`plain-list
21162 ;; At a plain list, with a double C-u argument, set
21163 ;; checkboxes of each item to "[-]", whereas a single one
21164 ;; will toggle their presence according to the state of the
21165 ;; first item in the list. Without an argument, repair the
21166 ;; list.
21167 (let* ((begin (org-element-property :contents-begin context))
21168 (beginm (move-marker (make-marker) begin))
21169 (struct (org-element-property :structure context))
21170 (old-struct (copy-tree struct))
21171 (first-box (save-excursion
21172 (goto-char begin)
21173 (looking-at org-list-full-item-re)
21174 (match-string-no-properties 3)))
21175 (new-box (cond ((equal arg '(16)) "[-]")
21176 ((equal arg '(4)) (unless first-box "[ ]"))
21177 ((equal first-box "[X]") "[ ]")
21178 (t "[X]"))))
21179 (cond
21180 (arg
21181 (dolist (pos
21182 (org-list-get-all-items
21183 begin struct (org-list-prevs-alist struct)))
21184 (org-list-set-checkbox pos struct new-box)))
21185 ((and first-box (eq (point) begin))
21186 ;; For convenience, when point is at bol on the first
21187 ;; item of the list and no argument is provided, simply
21188 ;; toggle checkbox of that item, if any.
21189 (org-list-set-checkbox begin struct new-box)))
21190 (org-list-write-struct
21191 struct (org-list-parents-alist struct) old-struct)
21192 (org-update-checkbox-count-maybe)
21193 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21194 ((or `property-drawer `node-property)
21195 (call-interactively #'org-property-action))
21196 ((or `radio-target `target)
21197 (call-interactively #'org-update-radio-target-regexp))
21198 (`statistics-cookie
21199 (call-interactively #'org-update-statistics-cookies))
21200 ((or `table `table-cell `table-row)
21201 ;; At a table, recalculate every field and align it. Also
21202 ;; send the table if necessary. If the table has
21203 ;; a `table.el' type, just give up. At a table row or
21204 ;; cell, maybe recalculate line but always align table.
21205 (if (eq (org-element-property :type context) 'table.el)
21206 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21207 Use \\[org-edit-special] to edit table.el tables"))
21208 (let ((org-enable-table-editor t))
21209 (if (or (eq type 'table)
21210 ;; Check if point is at a TBLFM line.
21211 (and (eq type 'table-row)
21212 (= (point) (org-element-property :end context))))
21213 (save-excursion
21214 (if (org-at-TBLFM-p)
21215 (progn (require 'org-table)
21216 (org-table-calc-current-TBLFM))
21217 (goto-char (org-element-property :contents-begin context))
21218 (org-call-with-arg 'org-table-recalculate (or arg t))
21219 (orgtbl-send-table 'maybe)))
21220 (org-table-maybe-eval-formula)
21221 (cond (arg (call-interactively 'org-table-recalculate))
21222 ((org-table-maybe-recalculate-line))
21223 (t (org-table-align)))))))
21224 (`timestamp (org-timestamp-change 0 'day))
21225 ((and `nil (guard (org-at-heading-p)))
21226 ;; When point is on an unsupported object type, we can miss
21227 ;; the fact that it also is at a heading. Handle it here.
21228 (call-interactively #'org-set-tags))
21230 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21231 (user-error
21232 (substitute-command-keys
21233 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))))
21235 (defun org-mode-restart ()
21236 (interactive)
21237 (let ((indent-status (bound-and-true-p org-indent-mode)))
21238 (funcall major-mode)
21239 (hack-local-variables)
21240 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21241 (org-indent-mode -1)))
21242 (message "%s restarted" major-mode))
21244 (defun org-kill-note-or-show-branches ()
21245 "Abort storing current note, or call `outline-show-branches'."
21246 (interactive)
21247 (if (not org-finish-function)
21248 (progn
21249 (outline-hide-subtree)
21250 (call-interactively 'outline-show-branches))
21251 (let ((org-note-abort t))
21252 (funcall org-finish-function))))
21254 (defun org-delete-indentation (&optional arg)
21255 "Join current line to previous and fix whitespace at join.
21257 If previous line is a headline add to headline title. Otherwise
21258 the function calls `delete-indentation'.
21260 With a non-nil optional argument, join it to the following one."
21261 (interactive "*P")
21262 (if (save-excursion
21263 (beginning-of-line (if arg 1 0))
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 (looking-at org-complex-heading-regexp)))
21332 ;; At headline. Split line. However, if point is on keyword,
21333 ;; priority cookie or tags, do not break any of them: add
21334 ;; a newline after the headline instead.
21335 (let ((tags-column (and (match-beginning 5)
21336 (save-excursion (goto-char (match-beginning 5))
21337 (current-column))))
21338 (string
21339 (when (and (match-end 4)
21340 (>= (point)
21341 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21342 (<= (point) (match-end 4)))
21343 (delete-and-extract-region (point) (match-end 4)))))
21344 ;; Adjust tag alignment.
21345 (cond
21346 ((not (and tags-column string)))
21347 (org-auto-align-tags (org-set-tags nil t))
21348 (t (org--align-tags-here tags-column))) ;preserve tags column
21349 (end-of-line)
21350 (org-show-entry)
21351 (if indent (newline-and-indent) (newline))
21352 (when string (save-excursion (insert (org-trim string))))))
21353 ;; In a list, make sure indenting keeps trailing text within.
21354 ((and indent
21355 (not (eolp))
21356 (org-element-lineage context '(item)))
21357 (let ((trailing-data
21358 (delete-and-extract-region (point) (line-end-position))))
21359 (newline-and-indent)
21360 (save-excursion (insert trailing-data))))
21361 (t (if indent (newline-and-indent) (newline))))))
21363 (defun org-return-indent ()
21364 "Goto next table row or insert a newline and indent.
21365 Calls `org-table-next-row' or `newline-and-indent', depending on
21366 context. See the individual commands for more information."
21367 (interactive)
21368 (org-return t))
21370 (defun org-ctrl-c-star ()
21371 "Compute table, or change heading status of lines.
21372 Calls `org-table-recalculate' or `org-toggle-heading',
21373 depending on context."
21374 (interactive)
21375 (cond
21376 ((org-at-table-p)
21377 (call-interactively 'org-table-recalculate))
21379 ;; Convert all lines in region to list items
21380 (call-interactively 'org-toggle-heading))))
21382 (defun org-ctrl-c-minus ()
21383 "Insert separator line in table or modify bullet status of line.
21384 Also turns a plain line or a region of lines into list items.
21385 Calls `org-table-insert-hline', `org-toggle-item', or
21386 `org-cycle-list-bullet', depending on context."
21387 (interactive)
21388 (cond
21389 ((org-at-table-p)
21390 (call-interactively 'org-table-insert-hline))
21391 ((org-region-active-p)
21392 (call-interactively 'org-toggle-item))
21393 ((org-in-item-p)
21394 (call-interactively 'org-cycle-list-bullet))
21396 (call-interactively 'org-toggle-item))))
21398 (defun org-toggle-heading (&optional nstars)
21399 "Convert headings to normal text, or items or text to headings.
21400 If there is no active region, only convert the current line.
21402 With a \\[universal-argument] prefix, convert the whole list at
21403 point into heading.
21405 In a region:
21407 - If the first non blank line is a headline, remove the stars
21408 from all headlines in the region.
21410 - If it is a normal line, turn each and every normal line (i.e.,
21411 not an heading or an item) in the region into headings. If you
21412 want to convert only the first line of this region, use one
21413 universal prefix argument.
21415 - If it is a plain list item, turn all plain list items into headings.
21417 When converting a line into a heading, the number of stars is chosen
21418 such that the lines become children of the current entry. However,
21419 when a numeric prefix argument is given, its value determines the
21420 number of stars to add."
21421 (interactive "P")
21422 (let ((skip-blanks
21423 (function
21424 ;; Return beginning of first non-blank line, starting from
21425 ;; line at POS.
21426 (lambda (pos)
21427 (save-excursion
21428 (goto-char pos)
21429 (while (org-at-comment-p) (forward-line))
21430 (skip-chars-forward " \r\t\n")
21431 (point-at-bol)))))
21432 beg end toggled)
21433 ;; Determine boundaries of changes. If a universal prefix has
21434 ;; been given, put the list in a region. If region ends at a bol,
21435 ;; do not consider the last line to be in the region.
21437 (when (and current-prefix-arg (org-at-item-p))
21438 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21439 (org-mark-element))
21441 (if (org-region-active-p)
21442 (setq beg (funcall skip-blanks (region-beginning))
21443 end (copy-marker (save-excursion
21444 (goto-char (region-end))
21445 (if (bolp) (point) (point-at-eol)))))
21446 (setq beg (funcall skip-blanks (point-at-bol))
21447 end (copy-marker (point-at-eol))))
21448 ;; Ensure inline tasks don't count as headings.
21449 (org-with-limited-levels
21450 (save-excursion
21451 (goto-char beg)
21452 (cond
21453 ;; Case 1. Started at an heading: de-star headings.
21454 ((org-at-heading-p)
21455 (while (< (point) end)
21456 (when (org-at-heading-p t)
21457 (looking-at org-outline-regexp) (replace-match "")
21458 (setq toggled t))
21459 (forward-line)))
21460 ;; Case 2. Started at an item: change items into headlines.
21461 ;; One star will be added by `org-list-to-subtree'.
21462 ((org-at-item-p)
21463 (while (< (point) end)
21464 (when (org-at-item-p)
21465 ;; Pay attention to cases when region ends before list.
21466 (let* ((struct (org-list-struct))
21467 (list-end
21468 (min (org-list-get-bottom-point struct) (1+ end))))
21469 (save-restriction
21470 (narrow-to-region (point) list-end)
21471 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21472 (setq toggled t))
21473 (forward-line)))
21474 ;; Case 3. Started at normal text: make every line an heading,
21475 ;; skipping headlines and items.
21476 (t (let* ((stars
21477 (make-string
21478 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21479 (add-stars
21480 (cond (nstars "") ; stars from prefix only
21481 ((equal stars "") "*") ; before first heading
21482 (org-odd-levels-only "**") ; inside heading, odd
21483 (t "*"))) ; inside heading, oddeven
21484 (rpl (concat stars add-stars " "))
21485 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21486 (while (< (point) (if (equal nstars '(4)) lend end))
21487 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21488 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21489 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21490 (forward-line)))))))
21491 (unless toggled (message "Cannot toggle heading from here"))))
21493 (defun org-meta-return (&optional _arg)
21494 "Insert a new heading or wrap a region in a table.
21495 Calls `org-insert-heading' or `org-table-wrap-region', depending
21496 on context. See the individual commands for more information."
21497 (interactive)
21498 (org-check-before-invisible-edit 'insert)
21499 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21500 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21501 #'org-insert-heading))))
21503 ;;; Menu entries
21505 (defsubst org-in-subtree-not-table-p ()
21506 "Are we in a subtree and not in a table?"
21507 (and (not (org-before-first-heading-p))
21508 (not (org-at-table-p))))
21510 ;; Define the Org mode menus
21511 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21512 '("Tbl"
21513 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21514 ["Next Field" org-cycle (org-at-table-p)]
21515 ["Previous Field" org-shifttab (org-at-table-p)]
21516 ["Next Row" org-return (org-at-table-p)]
21517 "--"
21518 ["Blank Field" org-table-blank-field (org-at-table-p)]
21519 ["Edit Field" org-table-edit-field (org-at-table-p)]
21520 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21521 "--"
21522 ("Column"
21523 ["Move Column Left" org-metaleft (org-at-table-p)]
21524 ["Move Column Right" org-metaright (org-at-table-p)]
21525 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21526 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21527 ("Row"
21528 ["Move Row Up" org-metaup (org-at-table-p)]
21529 ["Move Row Down" org-metadown (org-at-table-p)]
21530 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21531 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21532 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21533 "--"
21534 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21535 ("Rectangle"
21536 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21537 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21538 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21539 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21540 "--"
21541 ("Calculate"
21542 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21543 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21544 ["Edit Formulas" org-edit-special (org-at-table-p)]
21545 "--"
21546 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21547 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21548 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21549 "--"
21550 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21551 "--"
21552 ["Sum Column/Rectangle" org-table-sum
21553 (or (org-at-table-p) (org-region-active-p))]
21554 ["Which Column?" org-table-current-column (org-at-table-p)])
21555 ["Debug Formulas"
21556 org-table-toggle-formula-debugger
21557 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21558 ["Show Col/Row Numbers"
21559 org-table-toggle-coordinate-overlays
21560 :style toggle
21561 :selected (bound-and-true-p org-table-overlay-coordinates)]
21562 "--"
21563 ["Create" org-table-create (and (not (org-at-table-p))
21564 org-enable-table-editor)]
21565 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21566 ["Import from File" org-table-import (not (org-at-table-p))]
21567 ["Export to File" org-table-export (org-at-table-p)]
21568 "--"
21569 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21570 "--"
21571 ("Plot"
21572 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21573 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21575 (easy-menu-define org-org-menu org-mode-map "Org menu"
21576 '("Org"
21577 ("Show/Hide"
21578 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21579 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21580 ["Sparse Tree..." org-sparse-tree t]
21581 ["Reveal Context" org-reveal t]
21582 ["Show All" outline-show-all t]
21583 "--"
21584 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21585 "--"
21586 ["New Heading" org-insert-heading t]
21587 ("Navigate Headings"
21588 ["Up" outline-up-heading t]
21589 ["Next" outline-next-visible-heading t]
21590 ["Previous" outline-previous-visible-heading t]
21591 ["Next Same Level" outline-forward-same-level t]
21592 ["Previous Same Level" outline-backward-same-level t]
21593 "--"
21594 ["Jump" org-goto t])
21595 ("Edit Structure"
21596 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21597 "--"
21598 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21599 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21600 "--"
21601 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21602 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21603 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21604 "--"
21605 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21606 "--"
21607 ["Copy visible text" org-copy-visible t]
21608 "--"
21609 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21610 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21611 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21612 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21613 "--"
21614 ["Sort Region/Children" org-sort t]
21615 "--"
21616 ["Convert to odd levels" org-convert-to-odd-levels t]
21617 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21618 ("Editing"
21619 ["Emphasis..." org-emphasize t]
21620 ["Edit Source Example" org-edit-special t]
21621 "--"
21622 ["Footnote new/jump" org-footnote-action t]
21623 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21624 ("Archive"
21625 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21626 "--"
21627 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21628 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21629 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21631 "--"
21632 ("Hyperlinks"
21633 ["Store Link (Global)" org-store-link t]
21634 ["Find existing link to here" org-occur-link-in-agenda-files t]
21635 ["Insert Link" org-insert-link t]
21636 ["Follow Link" org-open-at-point t]
21637 "--"
21638 ["Next link" org-next-link t]
21639 ["Previous link" org-previous-link t]
21640 "--"
21641 ["Descriptive Links"
21642 org-toggle-link-display
21643 :style radio
21644 :selected org-descriptive-links
21646 ["Literal Links"
21647 org-toggle-link-display
21648 :style radio
21649 :selected (not org-descriptive-links)])
21650 "--"
21651 ("TODO Lists"
21652 ["TODO/DONE/-" org-todo t]
21653 ("Select keyword"
21654 ["Next keyword" org-shiftright (org-at-heading-p)]
21655 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21656 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21657 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21658 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21659 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21660 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21661 "--"
21662 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21663 :selected org-enforce-todo-dependencies :style toggle :active t]
21664 "Settings for tree at point"
21665 ["Do Children sequentially" org-toggle-ordered-property :style radio
21666 :selected (org-entry-get nil "ORDERED")
21667 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21668 ["Do Children parallel" org-toggle-ordered-property :style radio
21669 :selected (not (org-entry-get nil "ORDERED"))
21670 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21671 "--"
21672 ["Set Priority" org-priority t]
21673 ["Priority Up" org-shiftup t]
21674 ["Priority Down" org-shiftdown t]
21675 "--"
21676 ["Get news from all feeds" org-feed-update-all t]
21677 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21678 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21679 ("TAGS and Properties"
21680 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21681 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21682 "--"
21683 ["Set property" org-set-property (not (org-before-first-heading-p))]
21684 ["Column view of properties" org-columns t]
21685 ["Insert Column View DBlock" org-columns-insert-dblock t])
21686 ("Dates and Scheduling"
21687 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21688 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21689 ("Change Date"
21690 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21691 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21692 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21693 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21694 ["Compute Time Range" org-evaluate-time-range t]
21695 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21696 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21697 "--"
21698 ["Custom time format" org-toggle-time-stamp-overlays
21699 :style radio :selected org-display-custom-times]
21700 "--"
21701 ["Goto Calendar" org-goto-calendar t]
21702 ["Date from Calendar" org-date-from-calendar t]
21703 "--"
21704 ["Start/Restart Timer" org-timer-start t]
21705 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21706 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21707 ["Insert Timer String" org-timer t]
21708 ["Insert Timer Item" org-timer-item t])
21709 ("Logging work"
21710 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21711 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21712 ["Clock out" org-clock-out t]
21713 ["Clock cancel" org-clock-cancel t]
21714 "--"
21715 ["Mark as default task" org-clock-mark-default-task t]
21716 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21717 ["Goto running clock" org-clock-goto t]
21718 "--"
21719 ["Display times" org-clock-display t]
21720 ["Create clock table" org-clock-report t]
21721 "--"
21722 ["Record DONE time"
21723 (progn (setq org-log-done (not org-log-done))
21724 (message "Switching to %s will %s record a timestamp"
21725 (car org-done-keywords)
21726 (if org-log-done "automatically" "not")))
21727 :style toggle :selected org-log-done])
21728 "--"
21729 ["Agenda Command..." org-agenda t]
21730 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21731 ("File List for Agenda")
21732 ("Special views current file"
21733 ["TODO Tree" org-show-todo-tree t]
21734 ["Check Deadlines" org-check-deadlines t]
21735 ["Timeline" org-timeline 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-emph-re 2)
21981 (>= (point) (match-beginning 3))
21982 (<= (point) (match-end 4))
21983 (member (match-string 3) '("=" "~")))))
21985 (defun org-overlay-display (ovl text &optional face evap)
21986 "Make overlay OVL display TEXT with face FACE."
21987 (overlay-put ovl 'display text)
21988 (if face (overlay-put ovl 'face face))
21989 (if evap (overlay-put ovl 'evaporate t)))
21991 (defun org-overlay-before-string (ovl text &optional face evap)
21992 "Make overlay OVL display TEXT with face FACE."
21993 (if face (org-add-props text nil 'face face))
21994 (overlay-put ovl 'before-string text)
21995 (if evap (overlay-put ovl 'evaporate t)))
21997 (defun org-find-overlays (prop &optional pos delete)
21998 "Find all overlays specifying PROP at POS or point.
21999 If DELETE is non-nil, delete all those overlays."
22000 (let (found)
22001 (dolist (ov (overlays-at (or pos (point))) found)
22002 (cond ((not (overlay-get ov prop)))
22003 (delete (delete-overlay ov))
22004 (t (push ov found))))))
22006 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22007 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22008 (if (and marker (marker-buffer marker)
22009 (buffer-live-p (marker-buffer marker)))
22010 (progn
22011 (pop-to-buffer-same-window (marker-buffer marker))
22012 (when (or (> marker (point-max)) (< marker (point-min)))
22013 (widen))
22014 (goto-char marker)
22015 (org-show-context 'org-goto))
22016 (if bookmark
22017 (bookmark-jump bookmark)
22018 (error "Cannot find location"))))
22020 (defun org-quote-csv-field (s)
22021 "Quote field for inclusion in CSV material."
22022 (if (string-match "[\",]" s)
22023 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22026 (defun org-force-self-insert (N)
22027 "Needed to enforce self-insert under remapping."
22028 (interactive "p")
22029 (self-insert-command N))
22031 (defun org-string-width (s)
22032 "Compute width of string, ignoring invisible characters.
22033 This ignores character with invisibility property `org-link', and also
22034 characters with property `org-cwidth', because these will become invisible
22035 upon the next fontification round."
22036 (let (b l)
22037 (when (or (eq t buffer-invisibility-spec)
22038 (assq 'org-link buffer-invisibility-spec))
22039 (while (setq b (text-property-any 0 (length s)
22040 'invisible 'org-link s))
22041 (setq s (concat (substring s 0 b)
22042 (substring s (or (next-single-property-change
22043 b 'invisible s)
22044 (length s)))))))
22045 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22046 (setq s (concat (substring s 0 b)
22047 (substring s (or (next-single-property-change
22048 b 'org-cwidth s)
22049 (length s))))))
22050 (setq l (string-width s) b -1)
22051 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22052 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22055 (defun org-shorten-string (s maxlength)
22056 "Shorten string S so that it is no longer than MAXLENGTH characters.
22057 If the string is shorter or has length MAXLENGTH, just return the
22058 original string. If it is longer, the functions finds a space in the
22059 string, breaks this string off at that locations and adds three dots
22060 as ellipsis. Including the ellipsis, the string will not be longer
22061 than MAXLENGTH. If finding a good breaking point in the string does
22062 not work, the string is just chopped off in the middle of a word
22063 if necessary."
22064 (if (<= (length s) maxlength)
22066 (let* ((n (max (- maxlength 4) 1))
22067 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22068 (if (string-match re s)
22069 (concat (match-string 1 s) "...")
22070 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22072 (defun org-get-indentation (&optional line)
22073 "Get the indentation of the current line, interpreting tabs.
22074 When LINE is given, assume it represents a line and compute its indentation."
22075 (if line
22076 (when (string-match "^ *" (org-remove-tabs line))
22077 (match-end 0))
22078 (save-excursion
22079 (beginning-of-line 1)
22080 (skip-chars-forward " \t")
22081 (current-column))))
22083 (defun org-get-string-indentation (s)
22084 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22085 (let ((n -1) (i 0) (w tab-width) c)
22086 (catch 'exit
22087 (while (< (setq n (1+ n)) (length s))
22088 (setq c (aref s n))
22089 (cond ((= c ?\ ) (setq i (1+ i)))
22090 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22091 (t (throw 'exit t)))))
22094 (defun org-remove-tabs (s &optional width)
22095 "Replace tabulators in S with spaces.
22096 Assumes that s is a single line, starting in column 0."
22097 (setq width (or width tab-width))
22098 (while (string-match "\t" s)
22099 (setq s (replace-match
22100 (make-string
22101 (- (* width (/ (+ (match-beginning 0) width) width))
22102 (match-beginning 0)) ?\ )
22103 t t s)))
22106 (defun org-fix-indentation (line ind)
22107 "Fix indentation in LINE.
22108 IND is a cons cell with target and minimum indentation.
22109 If the current indentation in LINE is smaller than the minimum,
22110 leave it alone. If it is larger than ind, set it to the target."
22111 (let* ((l (org-remove-tabs line))
22112 (i (org-get-indentation l))
22113 (i1 (car ind)) (i2 (cdr ind)))
22114 (when (>= i i2) (setq l (substring line i2)))
22115 (if (> i1 0)
22116 (concat (make-string i1 ?\ ) l)
22117 l)))
22119 (defun org-remove-indentation (code &optional n)
22120 "Remove maximum common indentation in string CODE and return it.
22121 N may optionally be the number of columns to remove. Return CODE
22122 as-is if removal failed."
22123 (with-temp-buffer
22124 (insert code)
22125 (if (org-do-remove-indentation n) (buffer-string) code)))
22127 (defun org-do-remove-indentation (&optional n)
22128 "Remove the maximum common indentation from the buffer.
22129 When optional argument N is a positive integer, remove exactly
22130 that much characters from indentation, if possible. Return nil
22131 if it fails."
22132 (catch :exit
22133 (goto-char (point-min))
22134 ;; Find maximum common indentation, if not specified.
22135 (let ((n (or n
22136 (let ((min-ind (point-max)))
22137 (save-excursion
22138 (while (re-search-forward "^[ \t]*\\S-" nil t)
22139 (let ((ind (1- (current-column))))
22140 (if (zerop ind) (throw :exit nil)
22141 (setq min-ind (min min-ind ind))))))
22142 min-ind))))
22143 (if (zerop n) (throw :exit nil)
22144 ;; Remove exactly N indentation, but give up if not possible.
22145 (while (not (eobp))
22146 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22147 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22148 ((< ind n) (throw :exit nil))
22149 (t (indent-line-to (- ind n))))
22150 (forward-line)))
22151 ;; Signal success.
22152 t))))
22154 (defun org-fill-template (template alist)
22155 "Find each %key of ALIST in TEMPLATE and replace it."
22156 (let ((case-fold-search nil))
22157 (dolist (entry (sort (copy-sequence alist)
22158 (lambda (a b) (< (length (car a)) (length (car b))))))
22159 (setq template
22160 (replace-regexp-in-string
22161 (concat "%" (regexp-quote (car entry)))
22162 (or (cdr entry) "") template t t)))
22163 template))
22165 (defun org-base-buffer (buffer)
22166 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22167 (if (not buffer)
22168 buffer
22169 (or (buffer-base-buffer buffer)
22170 buffer)))
22172 (defun org-wrap (string &optional width lines)
22173 "Wrap string to either a number of lines, or a width in characters.
22174 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22175 that costs. If there is a word longer than WIDTH, the text is actually
22176 wrapped to the length of that word.
22177 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22178 many lines, whatever width that takes.
22179 The return value is a list of lines, without newlines at the end."
22180 (let* ((words (org-split-string string "[ \t\n]+"))
22181 (maxword (apply 'max (mapcar 'org-string-width words)))
22182 w ll)
22183 (cond (width
22184 (org-do-wrap words (max maxword width)))
22185 (lines
22186 (setq w maxword)
22187 (setq ll (org-do-wrap words maxword))
22188 (if (<= (length ll) lines)
22190 (setq ll words)
22191 (while (> (length ll) lines)
22192 (setq w (1+ w))
22193 (setq ll (org-do-wrap words w)))
22194 ll))
22195 (t (error "Cannot wrap this")))))
22197 (defun org-do-wrap (words width)
22198 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22199 (let (lines line)
22200 (while words
22201 (setq line (pop words))
22202 (while (and words (< (+ (length line) (length (car words))) width))
22203 (setq line (concat line " " (pop words))))
22204 (setq lines (push line lines)))
22205 (nreverse lines)))
22207 (defun org-split-string (string &optional separators)
22208 "Splits STRING into substrings at SEPARATORS.
22209 SEPARATORS is a regular expression.
22210 No empty strings are returned if there are matches at the beginning
22211 and end of string."
22212 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22213 (let ((start 0) notfirst list)
22214 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22215 (if (and notfirst
22216 (= start (match-beginning 0))
22217 (< start (length string)))
22218 (1+ start) start))
22219 (< (match-beginning 0) (length string)))
22220 (setq notfirst t)
22221 (or (eq (match-beginning 0) 0)
22222 (and (eq (match-beginning 0) (match-end 0))
22223 (eq (match-beginning 0) start))
22224 (push (substring string start (match-beginning 0)) list))
22225 (setq start (match-end 0)))
22226 (or (eq start (length string))
22227 (push (substring string start) list))
22228 (nreverse list)))
22230 (defun org-quote-vert (s)
22231 "Replace \"|\" with \"\\vert\"."
22232 (while (string-match "|" s)
22233 (setq s (replace-match "\\vert" t t s)))
22236 (defun org-uuidgen-p (s)
22237 "Is S an ID created by UUIDGEN?"
22238 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22240 (defun org-in-src-block-p (&optional inside)
22241 "Whether point is in a code source block.
22242 When INSIDE is non-nil, don't consider we are within a src block
22243 when point is at #+BEGIN_SRC or #+END_SRC."
22244 (let ((case-fold-search t))
22245 (or (and (eq (get-char-property (point) 'src-block) t))
22246 (and (not inside)
22247 (save-match-data
22248 (save-excursion
22249 (beginning-of-line)
22250 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22252 (defun org-context ()
22253 "Return a list of contexts of the current cursor position.
22254 If several contexts apply, all are returned.
22255 Each context entry is a list with a symbol naming the context, and
22256 two positions indicating start and end of the context. Possible
22257 contexts are:
22259 :headline anywhere in a headline
22260 :headline-stars on the leading stars in a headline
22261 :todo-keyword on a TODO keyword (including DONE) in a headline
22262 :tags on the TAGS in a headline
22263 :priority on the priority cookie in a headline
22264 :item on the first line of a plain list item
22265 :item-bullet on the bullet/number of a plain list item
22266 :checkbox on the checkbox in a plain list item
22267 :table in an Org table
22268 :table-special on a special filed in a table
22269 :table-table in a table.el table
22270 :clocktable in a clocktable
22271 :src-block in a source block
22272 :link on a hyperlink
22273 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22274 :target on a <<target>>
22275 :radio-target on a <<<radio-target>>>
22276 :latex-fragment on a LaTeX fragment
22277 :latex-preview on a LaTeX fragment with overlaid preview image
22279 This function expects the position to be visible because it uses font-lock
22280 faces as a help to recognize the following contexts: :table-special, :link,
22281 and :keyword."
22282 (let* ((f (get-text-property (point) 'face))
22283 (faces (if (listp f) f (list f)))
22284 (case-fold-search t)
22285 (p (point)) clist o)
22286 ;; First the large context
22287 (cond
22288 ((org-at-heading-p t)
22289 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22290 (when (progn
22291 (beginning-of-line 1)
22292 (looking-at org-todo-line-tags-regexp))
22293 (push (org-point-in-group p 1 :headline-stars) clist)
22294 (push (org-point-in-group p 2 :todo-keyword) clist)
22295 (push (org-point-in-group p 4 :tags) clist))
22296 (goto-char p)
22297 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22298 (when (looking-at "\\[#[A-Z0-9]\\]")
22299 (push (org-point-in-group p 0 :priority) clist)))
22301 ((org-at-item-p)
22302 (push (org-point-in-group p 2 :item-bullet) clist)
22303 (push (list :item (point-at-bol)
22304 (save-excursion (org-end-of-item) (point)))
22305 clist)
22306 (and (org-at-item-checkbox-p)
22307 (push (org-point-in-group p 0 :checkbox) clist)))
22309 ((org-at-table-p)
22310 (push (list :table (org-table-begin) (org-table-end)) clist)
22311 (when (memq 'org-formula faces)
22312 (push (list :table-special
22313 (previous-single-property-change p 'face)
22314 (next-single-property-change p 'face)) clist)))
22315 ((org-at-table-p 'any)
22316 (push (list :table-table) clist)))
22317 (goto-char p)
22319 (let ((case-fold-search t))
22320 ;; New the "medium" contexts: clocktables, source blocks
22321 (cond ((org-in-clocktable-p)
22322 (push (list :clocktable
22323 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22324 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22325 (match-beginning 1))
22326 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22327 (match-end 0))) clist))
22328 ((org-in-src-block-p)
22329 (push (list :src-block
22330 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22331 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22332 (match-beginning 1))
22333 (and (search-forward "#+END_SRC" nil t)
22334 (match-beginning 0))) clist))))
22335 (goto-char p)
22337 ;; Now the small context
22338 (cond
22339 ((org-at-timestamp-p)
22340 (push (org-point-in-group p 0 :timestamp) clist))
22341 ((memq 'org-link faces)
22342 (push (list :link
22343 (previous-single-property-change p 'face)
22344 (next-single-property-change p 'face)) clist))
22345 ((memq 'org-special-keyword faces)
22346 (push (list :keyword
22347 (previous-single-property-change p 'face)
22348 (next-single-property-change p 'face)) clist))
22349 ((org-at-target-p)
22350 (push (org-point-in-group p 0 :target) clist)
22351 (goto-char (1- (match-beginning 0)))
22352 (when (looking-at org-radio-target-regexp)
22353 (push (org-point-in-group p 0 :radio-target) clist))
22354 (goto-char p))
22355 ((setq o (cl-some
22356 (lambda (o)
22357 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22359 (overlays-at (point))))
22360 (push (list :latex-fragment
22361 (overlay-start o) (overlay-end o)) clist)
22362 (push (list :latex-preview
22363 (overlay-start o) (overlay-end o)) clist))
22364 ((org-inside-LaTeX-fragment-p)
22365 ;; FIXME: positions wrong.
22366 (push (list :latex-fragment (point) (point)) clist)))
22368 (setq clist (nreverse (delq nil clist)))
22369 clist))
22371 (defun org-in-regexp (regexp &optional nlines visually)
22372 "Check if point is inside a match of REGEXP.
22374 Normally only the current line is checked, but you can include
22375 NLINES extra lines around point into the search. If VISUALLY is
22376 set, require that the cursor is not after the match but really
22377 on, so that the block visually is on the match.
22379 Return nil or a cons cell (BEG . END) where BEG and END are,
22380 respectively, the positions at the beginning and the end of the
22381 match."
22382 (catch :exit
22383 (let ((pos (point))
22384 (eol (line-end-position (if nlines (1+ nlines) 1))))
22385 (save-excursion
22386 (beginning-of-line (- 1 (or nlines 0)))
22387 (while (and (re-search-forward regexp eol t)
22388 (<= (match-beginning 0) pos))
22389 (let ((end (match-end 0)))
22390 (when (or (> end pos) (and (= end pos) (not visually)))
22391 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22393 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22394 "Non-nil when point is between matches of START-RE and END-RE.
22396 Also return a non-nil value when point is on one of the matches.
22398 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22399 buffer positions. Default values are the positions of headlines
22400 surrounding the point.
22402 The functions returns a cons cell whose car (resp. cdr) is the
22403 position before START-RE (resp. after END-RE)."
22404 (save-match-data
22405 (let ((pos (point))
22406 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22407 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22408 beg end)
22409 (save-excursion
22410 ;; Point is on a block when on START-RE or if START-RE can be
22411 ;; found before it...
22412 (and (or (org-in-regexp start-re)
22413 (re-search-backward start-re limit-up t))
22414 (setq beg (match-beginning 0))
22415 ;; ... and END-RE after it...
22416 (goto-char (match-end 0))
22417 (re-search-forward end-re limit-down t)
22418 (> (setq end (match-end 0)) pos)
22419 ;; ... without another START-RE in-between.
22420 (goto-char (match-beginning 0))
22421 (not (re-search-backward start-re (1+ beg) t))
22422 ;; Return value.
22423 (cons beg end))))))
22425 (defun org-in-block-p (names)
22426 "Non-nil when point belongs to a block whose name belongs to NAMES.
22428 NAMES is a list of strings containing names of blocks.
22430 Return first block name matched, or nil. Beware that in case of
22431 nested blocks, the returned name may not belong to the closest
22432 block from point."
22433 (save-match-data
22434 (catch 'exit
22435 (let ((case-fold-search t)
22436 (lim-up (save-excursion (outline-previous-heading)))
22437 (lim-down (save-excursion (outline-next-heading))))
22438 (dolist (name names)
22439 (let ((n (regexp-quote name)))
22440 (when (org-between-regexps-p
22441 (concat "^[ \t]*#\\+begin_" n)
22442 (concat "^[ \t]*#\\+end_" n)
22443 lim-up lim-down)
22444 (throw 'exit n)))))
22445 nil)))
22447 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22448 "Call `multi-occur' with buffers for all agenda files."
22449 (interactive "sOrg-files matching: ")
22450 (let* ((files (org-agenda-files))
22451 (tnames (mapcar #'file-truename files))
22452 (extra org-agenda-text-search-extra-files))
22453 (when (eq (car extra) 'agenda-archives)
22454 (setq extra (cdr extra))
22455 (setq files (org-add-archive-files files)))
22456 (dolist (f extra)
22457 (unless (member (file-truename f) tnames)
22458 (unless (member f files) (setq files (append files (list f))))
22459 (setq tnames (append tnames (list (file-truename f))))))
22460 (multi-occur
22461 (mapcar (lambda (x)
22462 (with-current-buffer
22463 ;; FIXME: Why not just (find-file-noselect x)?
22464 ;; Is it to avoid the "revert buffer" prompt?
22465 (or (get-file-buffer x) (find-file-noselect x))
22466 (widen)
22467 (current-buffer)))
22468 files)
22469 regexp)))
22471 (add-hook 'occur-mode-find-occurrence-hook
22472 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22474 (defun org-occur-link-in-agenda-files ()
22475 "Create a link and search for it in the agendas.
22476 The link is not stored in `org-stored-links', it is just created
22477 for the search purpose."
22478 (interactive)
22479 (let ((link (condition-case nil
22480 (org-store-link nil)
22481 (error "Unable to create a link to here"))))
22482 (org-occur-in-agenda-files (regexp-quote link))))
22484 (defun org-reverse-string (string)
22485 "Return the reverse of STRING."
22486 (apply 'string (reverse (string-to-list string))))
22488 ;; defsubst org-uniquify must be defined before first use
22490 (defun org-uniquify-alist (alist)
22491 "Merge elements of ALIST with the same key.
22493 For example, in this alist:
22495 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22496 => \\='((a 1 3) (b 2))
22498 merge (a 1) and (a 3) into (a 1 3).
22500 The function returns the new ALIST."
22501 (let (rtn)
22502 (dolist (e alist rtn)
22503 (let (n)
22504 (if (not (assoc (car e) rtn))
22505 (push e rtn)
22506 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22507 (setq rtn (assq-delete-all (car e) rtn))
22508 (push n rtn))))))
22510 (defun org-delete-all (elts list)
22511 "Remove all elements in ELTS from LIST.
22512 Comparison is done with `equal'. It is a destructive operation
22513 that may remove elements by altering the list structure."
22514 (while elts
22515 (setq list (delete (pop elts) list)))
22516 list)
22518 (defun org-back-over-empty-lines ()
22519 "Move backwards over whitespace, to the beginning of the first empty line.
22520 Returns the number of empty lines passed."
22521 (let ((pos (point)))
22522 (if (cdr (assq 'heading org-blank-before-new-entry))
22523 (skip-chars-backward " \t\n\r")
22524 (unless (eobp)
22525 (forward-line -1)))
22526 (beginning-of-line 2)
22527 (goto-char (min (point) pos))
22528 (count-lines (point) pos)))
22530 (defun org-skip-whitespace ()
22531 (skip-chars-forward " \t\n\r"))
22533 (defun org-point-in-group (point group &optional context)
22534 "Check if POINT is in match-group GROUP.
22535 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22536 match. If the match group does not exist or point is not inside it,
22537 return nil."
22538 (and (match-beginning group)
22539 (>= point (match-beginning group))
22540 (<= point (match-end group))
22541 (if context
22542 (list context (match-beginning group) (match-end group))
22543 t)))
22545 (defun org-switch-to-buffer-other-window (&rest args)
22546 "Switch to buffer in a second window on the current frame.
22547 In particular, do not allow pop-up frames.
22548 Returns the newly created buffer."
22549 (org-no-popups
22550 (apply 'switch-to-buffer-other-window args)))
22552 (defun org-combine-plists (&rest plists)
22553 "Create a single property list from all plists in PLISTS.
22554 The process starts by copying the first list, and then setting properties
22555 from the other lists. Settings in the last list are the most significant
22556 ones and overrule settings in the other lists."
22557 (let ((rtn (copy-sequence (pop plists)))
22558 p v ls)
22559 (while plists
22560 (setq ls (pop plists))
22561 (while ls
22562 (setq p (pop ls) v (pop ls))
22563 (setq rtn (plist-put rtn p v))))
22564 rtn))
22566 (defun org-replace-escapes (string table)
22567 "Replace %-escapes in STRING with values in TABLE.
22568 TABLE is an association list with keys like \"%a\" and string values.
22569 The sequences in STRING may contain normal field width and padding information,
22570 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22571 so values can contain further %-escapes if they are define later in TABLE."
22572 (let ((tbl (copy-alist table))
22573 (case-fold-search nil)
22574 (pchg 0)
22575 re rpl)
22576 (dolist (e tbl)
22577 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22578 (when (and (cdr e) (string-match re (cdr e)))
22579 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22580 (safe "SREF"))
22581 (add-text-properties 0 3 (list 'sref sref) safe)
22582 (setcdr e (replace-match safe t t (cdr e)))))
22583 (while (string-match re string)
22584 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22585 (cdr e)))
22586 (setq string (replace-match rpl t t string))))
22587 (while (setq pchg (next-property-change pchg string))
22588 (let ((sref (get-text-property pchg 'sref string)))
22589 (when (and sref (string-match "SREF" string pchg))
22590 (setq string (replace-match sref t t string)))))
22591 string))
22593 (defun org-find-base-buffer-visiting (file)
22594 "Like `find-buffer-visiting' but always return the base buffer and
22595 not an indirect buffer."
22596 (let ((buf (or (get-file-buffer file)
22597 (find-buffer-visiting file))))
22598 (if buf
22599 (or (buffer-base-buffer buf) buf)
22600 nil)))
22602 ;;; TODO: Only called once, from ox-odt which should probably use
22603 ;;; org-export-inline-image-p or something.
22604 (defun org-file-image-p (file)
22605 "Return non-nil if FILE is an image."
22606 (save-match-data
22607 (string-match (image-file-name-regexp) file)))
22609 (defun org-get-cursor-date (&optional with-time)
22610 "Return the date at cursor in as a time.
22611 This works in the calendar and in the agenda, anywhere else it just
22612 returns the current time.
22613 If WITH-TIME is non-nil, returns the time of the event at point (in
22614 the agenda) or the current time of the day."
22615 (let (date day defd tp hod mod)
22616 (when with-time
22617 (setq tp (get-text-property (point) 'time))
22618 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22619 (setq hod (string-to-number (match-string 1 tp))
22620 mod (string-to-number (match-string 2 tp))))
22621 (or tp (let ((now (decode-time)))
22622 (setq hod (nth 2 now)
22623 mod (nth 1 now)))))
22624 (cond
22625 ((eq major-mode 'calendar-mode)
22626 (setq date (calendar-cursor-to-date)
22627 defd (encode-time 0 (or mod 0) (or hod 0)
22628 (nth 1 date) (nth 0 date) (nth 2 date))))
22629 ((eq major-mode 'org-agenda-mode)
22630 (setq day (get-text-property (point) 'day))
22631 (when day
22632 (setq date (calendar-gregorian-from-absolute day)
22633 defd (encode-time 0 (or mod 0) (or hod 0)
22634 (nth 1 date) (nth 0 date) (nth 2 date))))))
22635 (or defd (current-time))))
22637 (defun org-mark-subtree (&optional up)
22638 "Mark the current subtree.
22639 This puts point at the start of the current subtree, and mark at
22640 the end. If a numeric prefix UP is given, move up into the
22641 hierarchy of headlines by UP levels before marking the subtree."
22642 (interactive "P")
22643 (org-with-limited-levels
22644 (cond ((org-at-heading-p) (beginning-of-line))
22645 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22646 (t (outline-previous-visible-heading 1))))
22647 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22648 (if (called-interactively-p 'any)
22649 (call-interactively 'org-mark-element)
22650 (org-mark-element)))
22652 (defun org-file-newer-than-p (file time)
22653 "Non-nil if FILE is newer than TIME.
22654 FILE is a filename, as a string, TIME is a list of integers, as
22655 returned by, e.g., `current-time'."
22656 (and (file-exists-p file)
22657 ;; Only compare times up to whole seconds as some file-systems
22658 ;; (e.g. HFS+) do not retain any finer granularity. As
22659 ;; a consequence, make sure we return non-nil when the two
22660 ;; times are equal.
22661 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22662 (cl-subseq time 0 2)))))
22664 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22665 "Compile a SOURCE file using PROCESS.
22667 PROCESS is either a function or a list of shell commands, as
22668 strings. EXT is a file extension, without the leading dot, as
22669 a string. It is used to check if the process actually succeeded.
22671 PROCESS must create a file with the same base name and directory
22672 as SOURCE, but ending with EXT. The function then returns its
22673 filename. Otherwise, it raises an error. The error message can
22674 then be refined by providing string ERR-MSG, which is appended to
22675 the standard message.
22677 If PROCESS is a function, it is called with a single argument:
22678 the SOURCE file.
22680 If it is a list of commands, each of them is called using
22681 `shell-command'. By default, in each command, %b, %f, %F and %o
22682 are replaced with, respectively, SOURCE base name, name, full
22683 name and directory. It is possible, however, to use more
22684 place-holders by specifying them in optional argument SPEC, as an
22685 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22687 When PROCESS is a list of commands, optional argument LOG-BUF can
22688 be set to a buffer or a buffer name. `shell-command' then uses
22689 it for output.
22691 `default-directory' is set to SOURCE directory during the whole
22692 process."
22693 (let* ((source-name (file-name-nondirectory source))
22694 (base-name (file-name-sans-extension source-name))
22695 (full-name (file-truename source))
22696 (out-dir (file-name-directory source))
22697 (time (current-time))
22698 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22699 (save-window-excursion
22700 (let ((default-directory (file-name-directory full-name)))
22701 (pcase process
22702 ((pred functionp) (funcall process (shell-quote-argument source)))
22703 ((pred consp)
22704 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22705 (spec (append spec
22706 `((?b . ,(shell-quote-argument base-name))
22707 (?f . ,(shell-quote-argument source-name))
22708 (?F . ,(shell-quote-argument full-name))
22709 (?o . ,(shell-quote-argument out-dir))))))
22710 (dolist (command process)
22711 (shell-command (format-spec command spec) log-buf))))
22712 (_ (error "No valid command to process %S%s" source err-msg)))))
22713 ;; Check for process failure.
22714 (let ((output (concat out-dir base-name "." ext)))
22715 (unless (org-file-newer-than-p output time)
22716 (error (format "File %S wasn't produced%s" output err-msg)))
22717 output)))
22719 ;;; Indentation
22721 (defun org--get-expected-indentation (element contentsp)
22722 "Expected indentation column for current line, according to ELEMENT.
22723 ELEMENT is an element containing point. CONTENTSP is non-nil
22724 when indentation is to be computed according to contents of
22725 ELEMENT."
22726 (let ((type (org-element-type element))
22727 (start (org-element-property :begin element))
22728 (post-affiliated (org-element-property :post-affiliated element)))
22729 (org-with-wide-buffer
22730 (cond
22731 (contentsp
22732 (cl-case type
22733 ((diary-sexp footnote-definition) 0)
22734 ((headline inlinetask nil)
22735 (if (not org-adapt-indentation) 0
22736 (let ((level (org-current-level)))
22737 (if level (1+ level) 0))))
22738 ((item plain-list) (org-list-item-body-column post-affiliated))
22740 (goto-char start)
22741 (org-get-indentation))))
22742 ((memq type '(headline inlinetask nil))
22743 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22744 (org--get-expected-indentation element t)
22746 ((memq type '(diary-sexp footnote-definition)) 0)
22747 ;; First paragraph of a footnote definition or an item.
22748 ;; Indent like parent.
22749 ((< (line-beginning-position) start)
22750 (org--get-expected-indentation
22751 (org-element-property :parent element) t))
22752 ;; At first line: indent according to previous sibling, if any,
22753 ;; ignoring footnote definitions and inline tasks, or parent's
22754 ;; contents.
22755 ((= (line-beginning-position) start)
22756 (catch 'exit
22757 (while t
22758 (if (= (point-min) start) (throw 'exit 0)
22759 (goto-char (1- start))
22760 (let* ((previous (org-element-at-point))
22761 (parent previous))
22762 (while (and parent (<= (org-element-property :end parent) start))
22763 (setq previous parent
22764 parent (org-element-property :parent parent)))
22765 (cond
22766 ((not previous) (throw 'exit 0))
22767 ((> (org-element-property :end previous) start)
22768 (throw 'exit (org--get-expected-indentation previous t)))
22769 ((memq (org-element-type previous)
22770 '(footnote-definition inlinetask))
22771 (setq start (org-element-property :begin previous)))
22772 (t (goto-char (org-element-property :begin previous))
22773 (throw 'exit
22774 (if (bolp) (org-get-indentation)
22775 ;; At first paragraph in an item or
22776 ;; a footnote definition.
22777 (org--get-expected-indentation
22778 (org-element-property :parent previous) t))))))))))
22779 ;; Otherwise, move to the first non-blank line above.
22781 (beginning-of-line)
22782 (let ((pos (point)))
22783 (skip-chars-backward " \r\t\n")
22784 (cond
22785 ;; Two blank lines end a footnote definition or a plain
22786 ;; list. When we indent an empty line after them, the
22787 ;; containing list or footnote definition is over, so it
22788 ;; qualifies as a previous sibling. Therefore, we indent
22789 ;; like its first line.
22790 ((and (memq type '(footnote-definition plain-list))
22791 (> (count-lines (point) pos) 2))
22792 (goto-char start)
22793 (org-get-indentation))
22794 ;; Line above is the first one of a paragraph at the
22795 ;; beginning of an item or a footnote definition. Indent
22796 ;; like parent.
22797 ((< (line-beginning-position) start)
22798 (org--get-expected-indentation
22799 (org-element-property :parent element) t))
22800 ;; Line above is the beginning of an element, i.e., point
22801 ;; was originally on the blank lines between element's start
22802 ;; and contents.
22803 ((= (line-beginning-position) post-affiliated)
22804 (org--get-expected-indentation element t))
22805 ;; POS is after contents in a greater element. Indent like
22806 ;; the beginning of the element.
22808 ;; As a special case, if point is at the end of a footnote
22809 ;; definition or an item, indent like the very last element
22810 ;; within. If that last element is an item, indent like its
22811 ;; contents.
22812 ((and (not (eq type 'paragraph))
22813 (let ((cend (org-element-property :contents-end element)))
22814 (and cend (<= cend pos))))
22815 (if (memq type '(footnote-definition item plain-list))
22816 (let ((last (org-element-at-point)))
22817 (org--get-expected-indentation
22818 last (eq (org-element-type last) 'item)))
22819 (goto-char start)
22820 (org-get-indentation)))
22821 ;; In any other case, indent like the current line.
22822 (t (org-get-indentation)))))))))
22824 (defun org--align-node-property ()
22825 "Align node property at point.
22826 Alignment is done according to `org-property-format', which see."
22827 (when (save-excursion
22828 (beginning-of-line)
22829 (looking-at org-property-re))
22830 (replace-match
22831 (concat (match-string 4)
22832 (org-trim
22833 (format org-property-format (match-string 1) (match-string 3))))
22834 t t)))
22836 (defun org-indent-line ()
22837 "Indent line depending on context.
22839 Indentation is done according to the following rules:
22841 - Footnote definitions, diary sexps, headlines and inline tasks
22842 have to start at column 0.
22844 - On the very first line of an element, consider, in order, the
22845 next rules until one matches:
22847 1. If there's a sibling element before, ignoring footnote
22848 definitions and inline tasks, indent like its first line.
22850 2. If element has a parent, indent like its contents. More
22851 precisely, if parent is an item, indent after the
22852 description part, if any, or the bullet (see
22853 `org-list-description-max-indent'). Else, indent like
22854 parent's first line.
22856 3. Otherwise, indent relatively to current level, if
22857 `org-adapt-indentation' is non-nil, or to left margin.
22859 - On a blank line at the end of an element, indent according to
22860 the type of the element. More precisely
22862 1. If element is a plain list, an item, or a footnote
22863 definition, indent like the very last element within.
22865 2. If element is a paragraph, indent like its last non blank
22866 line.
22868 3. Otherwise, indent like its very first line.
22870 - In the code part of a source block, use language major mode
22871 to indent current line if `org-src-tab-acts-natively' is
22872 non-nil. If it is nil, do nothing.
22874 - Otherwise, indent like the first non-blank line above.
22876 The function doesn't indent an item as it could break the whole
22877 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22878 \\[org-shiftmetaright].
22880 Also align node properties according to `org-property-format'."
22881 (interactive)
22882 (cond
22883 (orgstruct-is-++
22884 (let ((indent-line-function
22885 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22886 (indent-according-to-mode)))
22887 ((org-at-heading-p) 'noindent)
22889 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22890 (type (org-element-type element)))
22891 (cond ((and (memq type '(plain-list item))
22892 (= (line-beginning-position)
22893 (org-element-property :post-affiliated element)))
22894 'noindent)
22895 ((and (eq type 'src-block)
22896 org-src-tab-acts-natively
22897 (> (line-beginning-position)
22898 (org-element-property :post-affiliated element))
22899 (< (line-beginning-position)
22900 (org-with-wide-buffer
22901 (goto-char (org-element-property :end element))
22902 (skip-chars-backward " \r\t\n")
22903 (line-beginning-position))))
22904 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22906 (let ((column (org--get-expected-indentation element nil)))
22907 ;; Preserve current column.
22908 (if (<= (current-column) (current-indentation))
22909 (indent-line-to column)
22910 (save-excursion (indent-line-to column))))
22911 ;; Align node property. Also preserve current column.
22912 (when (eq type 'node-property)
22913 (let ((column (current-column)))
22914 (org--align-node-property)
22915 (org-move-to-column column)))))))))
22917 (defun org-indent-region (start end)
22918 "Indent each non-blank line in the region.
22919 Called from a program, START and END specify the region to
22920 indent. The function will not indent contents of example blocks,
22921 verse blocks and export blocks as leading white spaces are
22922 assumed to be significant there."
22923 (interactive "r")
22924 (save-excursion
22925 (goto-char start)
22926 (skip-chars-forward " \r\t\n")
22927 (unless (eobp) (beginning-of-line))
22928 (let ((indent-to
22929 (lambda (ind pos)
22930 ;; Set IND as indentation for all lines between point and
22931 ;; POS. Blank lines are ignored. Leave point after POS
22932 ;; once done.
22933 (let ((limit (copy-marker pos)))
22934 (while (< (point) limit)
22935 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22936 (forward-line))
22937 (set-marker limit nil))))
22938 (end (copy-marker end)))
22939 (while (< (point) end)
22940 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22941 (let* ((element (org-element-at-point))
22942 (type (org-element-type element))
22943 (element-end (copy-marker (org-element-property :end element)))
22944 (ind (org--get-expected-indentation element nil)))
22945 (cond
22946 ((or (memq type '(paragraph table table-row))
22947 (not (or (org-element-property :contents-begin element)
22948 (memq type
22949 '(example-block export-block src-block)))))
22950 ;; Elements here are indented as a single block. Also
22951 ;; align node properties.
22952 (when (eq type 'node-property)
22953 (org--align-node-property)
22954 (beginning-of-line))
22955 (funcall indent-to ind (min element-end end)))
22957 ;; Elements in this category consist of three parts:
22958 ;; before the contents, the contents, and after the
22959 ;; contents. The contents are treated specially,
22960 ;; according to the element type, or not indented at
22961 ;; all. Other parts are indented as a single block.
22962 (let* ((post (copy-marker
22963 (org-element-property :post-affiliated element)))
22964 (cbeg
22965 (copy-marker
22966 (cond
22967 ((not (org-element-property :contents-begin element))
22968 ;; Fake contents for source blocks.
22969 (org-with-wide-buffer
22970 (goto-char post)
22971 (forward-line)
22972 (point)))
22973 ((memq type '(footnote-definition item plain-list))
22974 ;; Contents in these elements could start on
22975 ;; the same line as the beginning of the
22976 ;; element. Make sure we start indenting
22977 ;; from the second line.
22978 (org-with-wide-buffer
22979 (goto-char post)
22980 (end-of-line)
22981 (skip-chars-forward " \r\t\n")
22982 (if (eobp) (point) (line-beginning-position))))
22983 (t (org-element-property :contents-begin element)))))
22984 (cend (copy-marker
22985 (or (org-element-property :contents-end element)
22986 ;; Fake contents for source blocks.
22987 (org-with-wide-buffer
22988 (goto-char element-end)
22989 (skip-chars-backward " \r\t\n")
22990 (line-beginning-position)))
22991 t)))
22992 ;; Do not change items indentation individually as it
22993 ;; might break the list as a whole. On the other
22994 ;; hand, when at a plain list, indent it as a whole.
22995 (cond ((eq type 'plain-list)
22996 (let ((offset (- ind (org-get-indentation))))
22997 (unless (zerop offset)
22998 (indent-rigidly (org-element-property :begin element)
22999 (org-element-property :end element)
23000 offset))
23001 (goto-char cbeg)))
23002 ((eq type 'item) (goto-char cbeg))
23003 (t (funcall indent-to ind (min cbeg end))))
23004 (when (< (point) end)
23005 (cl-case type
23006 ((example-block export-block verse-block))
23007 (src-block
23008 ;; In a source block, indent source code
23009 ;; according to language major mode, but only if
23010 ;; `org-src-tab-acts-natively' is non-nil.
23011 (when (and (< (point) end) org-src-tab-acts-natively)
23012 (ignore-errors
23013 (org-babel-do-in-edit-buffer
23014 (indent-region (point-min) (point-max))))))
23015 (t (org-indent-region (point) (min cend end))))
23016 (goto-char (min cend end))
23017 (when (< (point) end)
23018 (funcall indent-to ind (min element-end end))))
23019 (set-marker post nil)
23020 (set-marker cbeg nil)
23021 (set-marker cend nil))))
23022 (set-marker element-end nil))))
23023 (set-marker end nil))))
23025 (defun org-indent-drawer ()
23026 "Indent the drawer at point."
23027 (interactive)
23028 (unless (save-excursion
23029 (beginning-of-line)
23030 (looking-at-p org-drawer-regexp))
23031 (user-error "Not at a drawer"))
23032 (let ((element (org-element-at-point)))
23033 (unless (memq (org-element-type element) '(drawer property-drawer))
23034 (user-error "Not at a drawer"))
23035 (org-with-wide-buffer
23036 (org-indent-region (org-element-property :begin element)
23037 (org-element-property :end element))))
23038 (message "Drawer at point indented"))
23040 (defun org-indent-block ()
23041 "Indent the block at point."
23042 (interactive)
23043 (unless (save-excursion
23044 (beginning-of-line)
23045 (let ((case-fold-search t))
23046 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23047 (user-error "Not at a block"))
23048 (let ((element (org-element-at-point)))
23049 (unless (memq (org-element-type element)
23050 '(comment-block center-block dynamic-block example-block
23051 export-block quote-block special-block
23052 src-block verse-block))
23053 (user-error "Not at a block"))
23054 (org-with-wide-buffer
23055 (org-indent-region (org-element-property :begin element)
23056 (org-element-property :end element))))
23057 (message "Block at point indented"))
23060 ;;; Filling
23062 ;; We use our own fill-paragraph and auto-fill functions.
23064 ;; `org-fill-paragraph' relies on adaptive filling and context
23065 ;; checking. Appropriate `fill-prefix' is computed with
23066 ;; `org-adaptive-fill-function'.
23068 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23069 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23070 ;; `org-adaptive-fill-function' value. Internally,
23071 ;; `org-comment-line-break-function' breaks the line.
23073 ;; `org-setup-filling' installs filling and auto-filling related
23074 ;; variables during `org-mode' initialization.
23076 (defvar org-element-paragraph-separate) ; org-element.el
23077 (defun org-setup-filling ()
23078 (require 'org-element)
23079 ;; Prevent auto-fill from inserting unwanted new items.
23080 (when (boundp 'fill-nobreak-predicate)
23081 (setq-local
23082 fill-nobreak-predicate
23083 (org-uniquify
23084 (append fill-nobreak-predicate
23085 '(org-fill-line-break-nobreak-p
23086 org-fill-paragraph-with-timestamp-nobreak-p)))))
23087 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23088 (setq-local paragraph-start paragraph-ending)
23089 (setq-local paragraph-separate paragraph-ending))
23090 (setq-local fill-paragraph-function 'org-fill-paragraph)
23091 (setq-local auto-fill-inhibit-regexp nil)
23092 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23093 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23094 (setq-local comment-line-break-function 'org-comment-line-break-function))
23096 (defun org-fill-line-break-nobreak-p ()
23097 "Non-nil when a new line at point would create an Org line break."
23098 (save-excursion
23099 (skip-chars-backward "[ \t]")
23100 (skip-chars-backward "\\\\")
23101 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23103 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23104 "Non-nil when a new line at point would split a timestamp."
23105 (and (org-at-timestamp-p t)
23106 (not (looking-at org-ts-regexp-both))))
23108 (declare-function message-in-body-p "message" ())
23109 (defvar orgtbl-line-start-regexp) ; From org-table.el
23110 (defun org-adaptive-fill-function ()
23111 "Compute a fill prefix for the current line.
23112 Return fill prefix, as a string, or nil if current line isn't
23113 meant to be filled. For convenience, if `adaptive-fill-regexp'
23114 matches in paragraphs or comments, use it."
23115 (catch 'exit
23116 (when (derived-mode-p 'message-mode)
23117 (save-excursion
23118 (beginning-of-line)
23119 (cond ((not (message-in-body-p)) (throw 'exit nil))
23120 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23121 ((looking-at message-cite-prefix-regexp)
23122 (throw 'exit (match-string-no-properties 0)))
23123 ((looking-at org-outline-regexp)
23124 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23125 (org-with-wide-buffer
23126 (unless (org-at-heading-p)
23127 (let* ((p (line-beginning-position))
23128 (element (save-excursion
23129 (beginning-of-line)
23130 (org-element-at-point)))
23131 (type (org-element-type element))
23132 (post-affiliated (org-element-property :post-affiliated element)))
23133 (unless (< p post-affiliated)
23134 (cl-case type
23135 (comment
23136 (save-excursion
23137 (beginning-of-line)
23138 (looking-at "[ \t]*")
23139 (concat (match-string 0) "# ")))
23140 (footnote-definition "")
23141 ((item plain-list)
23142 (make-string (org-list-item-body-column post-affiliated) ?\s))
23143 (paragraph
23144 ;; Fill prefix is usually the same as the current line,
23145 ;; unless the paragraph is at the beginning of an item.
23146 (let ((parent (org-element-property :parent element)))
23147 (save-excursion
23148 (beginning-of-line)
23149 (cond ((eq (org-element-type parent) 'item)
23150 (make-string (org-list-item-body-column
23151 (org-element-property :begin parent))
23152 ?\s))
23153 ((and adaptive-fill-regexp
23154 ;; Locally disable
23155 ;; `adaptive-fill-function' to let
23156 ;; `fill-context-prefix' handle
23157 ;; `adaptive-fill-regexp' variable.
23158 (let (adaptive-fill-function)
23159 (fill-context-prefix
23160 post-affiliated
23161 (org-element-property :end element)))))
23162 ((looking-at "[ \t]+") (match-string 0))
23163 (t "")))))
23164 (comment-block
23165 ;; Only fill contents if P is within block boundaries.
23166 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23167 (forward-line)
23168 (point)))
23169 (cend (save-excursion
23170 (goto-char (org-element-property :end element))
23171 (skip-chars-backward " \r\t\n")
23172 (line-beginning-position))))
23173 (when (and (>= p cbeg) (< p cend))
23174 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23175 (match-string 0)
23176 "")))))))))))
23178 (declare-function message-goto-body "message" ())
23179 (defvar message-cite-prefix-regexp) ; From message.el
23180 (defun org-fill-paragraph (&optional justify)
23181 "Fill element at point, when applicable.
23183 This function only applies to comment blocks, comments, example
23184 blocks and paragraphs. Also, as a special case, re-align table
23185 when point is at one.
23187 If JUSTIFY is non-nil (interactively, with prefix argument),
23188 justify as well. If `sentence-end-double-space' is non-nil, then
23189 period followed by one space does not end a sentence, so don't
23190 break a line there. The variable `fill-column' controls the
23191 width for filling.
23193 For convenience, when point is at a plain list, an item or
23194 a footnote definition, try to fill the first paragraph within."
23195 (interactive)
23196 (if (and (derived-mode-p 'message-mode)
23197 (or (not (message-in-body-p))
23198 (save-excursion (move-beginning-of-line 1)
23199 (looking-at message-cite-prefix-regexp))))
23200 ;; First ensure filling is correct in message-mode.
23201 (let ((fill-paragraph-function
23202 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23203 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23204 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23205 (paragraph-separate
23206 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23207 (fill-paragraph nil))
23208 (with-syntax-table org-mode-transpose-word-syntax-table
23209 ;; Move to end of line in order to get the first paragraph
23210 ;; within a plain list or a footnote definition.
23211 (let ((element (save-excursion
23212 (end-of-line)
23213 (or (ignore-errors (org-element-at-point))
23214 (user-error "An element cannot be parsed line %d"
23215 (line-number-at-pos (point)))))))
23216 ;; First check if point is in a blank line at the beginning of
23217 ;; the buffer. In that case, ignore filling.
23218 (cl-case (org-element-type element)
23219 ;; Use major mode filling function is src blocks.
23220 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23221 ;; Align Org tables, leave table.el tables as-is.
23222 (table-row (org-table-align) t)
23223 (table
23224 (when (eq (org-element-property :type element) 'org)
23225 (save-excursion
23226 (goto-char (org-element-property :post-affiliated element))
23227 (org-table-align)))
23229 (paragraph
23230 ;; Paragraphs may contain `line-break' type objects.
23231 (let ((beg (max (point-min)
23232 (org-element-property :contents-begin element)))
23233 (end (min (point-max)
23234 (org-element-property :contents-end element))))
23235 ;; Do nothing if point is at an affiliated keyword.
23236 (if (< (line-end-position) beg) t
23237 (when (derived-mode-p 'message-mode)
23238 ;; In `message-mode', do not fill following citation
23239 ;; in current paragraph nor text before message body.
23240 (let ((body-start (save-excursion (message-goto-body))))
23241 (when body-start (setq beg (max body-start beg))))
23242 (when (save-excursion
23243 (re-search-forward
23244 (concat "^" message-cite-prefix-regexp) end t))
23245 (setq end (match-beginning 0))))
23246 ;; Fill paragraph, taking line breaks into account.
23247 (save-excursion
23248 (goto-char beg)
23249 (let ((cuts (list beg)))
23250 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23251 (when (eq 'line-break
23252 (org-element-type
23253 (save-excursion (backward-char)
23254 (org-element-context))))
23255 (push (point) cuts)))
23256 (dolist (c (delq end cuts))
23257 (fill-region-as-paragraph c end justify)
23258 (setq end c))))
23259 t)))
23260 ;; Contents of `comment-block' type elements should be
23261 ;; filled as plain text, but only if point is within block
23262 ;; markers.
23263 (comment-block
23264 (let* ((case-fold-search t)
23265 (beg (save-excursion
23266 (goto-char (org-element-property :begin element))
23267 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23268 (forward-line)
23269 (point)))
23270 (end (save-excursion
23271 (goto-char (org-element-property :end element))
23272 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23273 (line-beginning-position))))
23274 (if (or (< (point) beg) (> (point) end)) t
23275 (fill-region-as-paragraph
23276 (save-excursion (end-of-line)
23277 (re-search-backward "^[ \t]*$" beg 'move)
23278 (line-beginning-position))
23279 (save-excursion (beginning-of-line)
23280 (re-search-forward "^[ \t]*$" end 'move)
23281 (line-beginning-position))
23282 justify))))
23283 ;; Fill comments.
23284 (comment
23285 (let ((begin (org-element-property :post-affiliated element))
23286 (end (org-element-property :end element)))
23287 (when (and (>= (point) begin) (<= (point) end))
23288 (let ((begin (save-excursion
23289 (end-of-line)
23290 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23291 (progn (forward-line) (point))
23292 begin)))
23293 (end (save-excursion
23294 (end-of-line)
23295 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23296 (1- (line-beginning-position))
23297 (skip-chars-backward " \r\t\n")
23298 (line-end-position)))))
23299 ;; Do not fill comments when at a blank line.
23300 (when (> end begin)
23301 (let ((fill-prefix
23302 (save-excursion
23303 (beginning-of-line)
23304 (looking-at "[ \t]*#")
23305 (let ((comment-prefix (match-string 0)))
23306 (goto-char (match-end 0))
23307 (if (looking-at adaptive-fill-regexp)
23308 (concat comment-prefix (match-string 0))
23309 (concat comment-prefix " "))))))
23310 (save-excursion
23311 (fill-region-as-paragraph begin end justify))))))
23313 ;; Ignore every other element.
23314 (otherwise t))))))
23316 (defun org-auto-fill-function ()
23317 "Auto-fill function."
23318 ;; Check if auto-filling is meaningful.
23319 (let ((fc (current-fill-column)))
23320 (when (and fc (> (current-column) fc))
23321 (let* ((fill-prefix (org-adaptive-fill-function))
23322 ;; Enforce empty fill prefix, if required. Otherwise, it
23323 ;; will be computed again.
23324 (adaptive-fill-mode (not (equal fill-prefix ""))))
23325 (when fill-prefix (do-auto-fill))))))
23327 (defun org-comment-line-break-function (&optional soft)
23328 "Break line at point and indent, continuing comment if within one.
23329 The inserted newline is marked hard if variable
23330 `use-hard-newlines' is true, unless optional argument SOFT is
23331 non-nil."
23332 (if soft (insert-and-inherit ?\n) (newline 1))
23333 (save-excursion (forward-char -1) (delete-horizontal-space))
23334 (delete-horizontal-space)
23335 (indent-to-left-margin)
23336 (insert-before-markers-and-inherit fill-prefix))
23339 ;;; Fixed Width Areas
23341 (defun org-toggle-fixed-width ()
23342 "Toggle fixed-width markup.
23344 Add or remove fixed-width markup on current line, whenever it
23345 makes sense. Return an error otherwise.
23347 If a region is active and if it contains only fixed-width areas
23348 or blank lines, remove all fixed-width markup in it. If the
23349 region contains anything else, convert all non-fixed-width lines
23350 to fixed-width ones.
23352 Blank lines at the end of the region are ignored unless the
23353 region only contains such lines."
23354 (interactive)
23355 (if (not (org-region-active-p))
23356 ;; No region:
23358 ;; Remove fixed width marker only in a fixed-with element.
23360 ;; Add fixed width maker in paragraphs, in blank lines after
23361 ;; elements or at the beginning of a headline or an inlinetask,
23362 ;; and before any one-line elements (e.g., a clock).
23363 (progn
23364 (beginning-of-line)
23365 (let* ((element (org-element-at-point))
23366 (type (org-element-type element)))
23367 (cond
23368 ((and (eq type 'fixed-width)
23369 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23370 (replace-match
23371 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23372 ((and (memq type '(babel-call clock comment diary-sexp headline
23373 horizontal-rule keyword paragraph
23374 planning))
23375 (<= (org-element-property :post-affiliated element) (point)))
23376 (skip-chars-forward " \t")
23377 (insert ": "))
23378 ((and (looking-at-p "[ \t]*$")
23379 (or (eq type 'inlinetask)
23380 (save-excursion
23381 (skip-chars-forward " \r\t\n")
23382 (<= (org-element-property :end element) (point)))))
23383 (delete-region (point) (line-end-position))
23384 (org-indent-line)
23385 (insert ": "))
23386 (t (user-error "Cannot insert a fixed-width line here")))))
23387 ;; Region active.
23388 (let* ((begin (save-excursion
23389 (goto-char (region-beginning))
23390 (line-beginning-position)))
23391 (end (copy-marker
23392 (save-excursion
23393 (goto-char (region-end))
23394 (unless (eolp) (beginning-of-line))
23395 (if (save-excursion (re-search-backward "\\S-" begin t))
23396 (progn (skip-chars-backward " \r\t\n") (point))
23397 (point)))))
23398 (all-fixed-width-p
23399 (catch 'not-all-p
23400 (save-excursion
23401 (goto-char begin)
23402 (skip-chars-forward " \r\t\n")
23403 (when (eobp) (throw 'not-all-p nil))
23404 (while (< (point) end)
23405 (let ((element (org-element-at-point)))
23406 (if (eq (org-element-type element) 'fixed-width)
23407 (goto-char (org-element-property :end element))
23408 (throw 'not-all-p nil))))
23409 t))))
23410 (if all-fixed-width-p
23411 (save-excursion
23412 (goto-char begin)
23413 (while (< (point) end)
23414 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23415 (replace-match
23416 "" nil nil nil
23417 (if (= (line-end-position) (match-end 0)) 0 1)))
23418 (forward-line)))
23419 (let ((min-ind (point-max)))
23420 ;; Find minimum indentation across all lines.
23421 (save-excursion
23422 (goto-char begin)
23423 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23424 (setq min-ind 0)
23425 (catch 'zerop
23426 (while (< (point) end)
23427 (unless (looking-at-p "[ \t]*$")
23428 (let ((ind (org-get-indentation)))
23429 (setq min-ind (min min-ind ind))
23430 (when (zerop ind) (throw 'zerop t))))
23431 (forward-line)))))
23432 ;; Loop over all lines and add fixed-width markup everywhere
23433 ;; but in fixed-width lines.
23434 (save-excursion
23435 (goto-char begin)
23436 (while (< (point) end)
23437 (cond
23438 ((org-at-heading-p)
23439 (insert ": ")
23440 (forward-line)
23441 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23442 (insert ":")
23443 (forward-line)))
23444 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23445 (let* ((element (org-element-at-point))
23446 (element-end (org-element-property :end element)))
23447 (if (eq (org-element-type element) 'fixed-width)
23448 (progn (goto-char element-end)
23449 (skip-chars-backward " \r\t\n")
23450 (forward-line))
23451 (let ((limit (min end element-end)))
23452 (while (< (point) limit)
23453 (org-move-to-column min-ind t)
23454 (insert ": ")
23455 (forward-line))))))
23457 (org-move-to-column min-ind t)
23458 (insert ": ")
23459 (forward-line)))))))
23460 (set-marker end nil))))
23463 ;;; Comments
23465 ;; Org comments syntax is quite complex. It requires the entire line
23466 ;; to be just a comment. Also, even with the right syntax at the
23467 ;; beginning of line, some some elements (i.e. verse-block or
23468 ;; example-block) don't accept comments. Usual Emacs comment commands
23469 ;; cannot cope with those requirements. Therefore, Org replaces them.
23471 ;; Org still relies on `comment-dwim', but cannot trust
23472 ;; `comment-only-p'. So, `comment-region-function' and
23473 ;; `uncomment-region-function' both point
23474 ;; to`org-comment-or-uncomment-region'. Eventually,
23475 ;; `org-insert-comment' takes care of insertion of comments at the
23476 ;; beginning of line.
23478 ;; `org-setup-comments-handling' install comments related variables
23479 ;; during `org-mode' initialization.
23481 (defun org-setup-comments-handling ()
23482 (interactive)
23483 (setq-local comment-use-syntax nil)
23484 (setq-local comment-start "# ")
23485 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23486 (setq-local comment-insert-comment-function 'org-insert-comment)
23487 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23488 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23490 (defun org-insert-comment ()
23491 "Insert an empty comment above current line.
23492 If the line is empty, insert comment at its beginning. When
23493 point is within a source block, comment according to the related
23494 major mode."
23495 (if (let ((element (org-element-at-point)))
23496 (and (eq (org-element-type element) 'src-block)
23497 (< (save-excursion
23498 (goto-char (org-element-property :post-affiliated element))
23499 (line-end-position))
23500 (point))
23501 (> (save-excursion
23502 (goto-char (org-element-property :end element))
23503 (skip-chars-backward " \r\t\n")
23504 (line-beginning-position))
23505 (point))))
23506 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23507 (beginning-of-line)
23508 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23509 (open-line 1))
23510 (org-indent-line)
23511 (insert "# ")))
23513 (defvar comment-empty-lines) ; From newcomment.el.
23514 (defun org-comment-or-uncomment-region (beg end &rest _)
23515 "Comment or uncomment each non-blank line in the region.
23516 Uncomment each non-blank line between BEG and END if it only
23517 contains commented lines. Otherwise, comment them. If region is
23518 strictly within a source block, use appropriate comment syntax."
23519 (if (let ((element (org-element-at-point)))
23520 (and (eq (org-element-type element) 'src-block)
23521 (< (save-excursion
23522 (goto-char (org-element-property :post-affiliated element))
23523 (line-end-position))
23524 beg)
23525 (>= (save-excursion
23526 (goto-char (org-element-property :end element))
23527 (skip-chars-backward " \r\t\n")
23528 (line-beginning-position))
23529 end)))
23530 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23531 (save-restriction
23532 ;; Restrict region
23533 (narrow-to-region (save-excursion (goto-char beg)
23534 (skip-chars-forward " \r\t\n" end)
23535 (line-beginning-position))
23536 (save-excursion (goto-char end)
23537 (skip-chars-backward " \r\t\n" beg)
23538 (line-end-position)))
23539 (let ((uncommentp
23540 ;; UNCOMMENTP is non-nil when every non blank line between
23541 ;; BEG and END is a comment.
23542 (save-excursion
23543 (goto-char (point-min))
23544 (while (and (not (eobp))
23545 (let ((element (org-element-at-point)))
23546 (and (eq (org-element-type element) 'comment)
23547 (goto-char (min (point-max)
23548 (org-element-property
23549 :end element)))))))
23550 (eobp))))
23551 (if uncommentp
23552 ;; Only blank lines and comments in region: uncomment it.
23553 (save-excursion
23554 (goto-char (point-min))
23555 (while (not (eobp))
23556 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23557 (replace-match "" nil nil nil 1))
23558 (forward-line)))
23559 ;; Comment each line in region.
23560 (let ((min-indent (point-max)))
23561 ;; First find the minimum indentation across all lines.
23562 (save-excursion
23563 (goto-char (point-min))
23564 (while (and (not (eobp)) (not (zerop min-indent)))
23565 (unless (looking-at "[ \t]*$")
23566 (setq min-indent (min min-indent (current-indentation))))
23567 (forward-line)))
23568 ;; Then loop over all lines.
23569 (save-excursion
23570 (goto-char (point-min))
23571 (while (not (eobp))
23572 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23573 ;; Don't get fooled by invisible text (e.g. link path)
23574 ;; when moving to column MIN-INDENT.
23575 (let ((buffer-invisibility-spec nil))
23576 (org-move-to-column min-indent t))
23577 (insert comment-start))
23578 (forward-line)))))))))
23580 (defun org-comment-dwim (_arg)
23581 "Call `comment-dwim' within a source edit buffer if needed."
23582 (interactive "*P")
23583 (if (org-in-src-block-p)
23584 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23585 (call-interactively 'comment-dwim)))
23588 ;;; Timestamps API
23590 ;; This section contains tools to operate on timestamp objects, as
23591 ;; returned by, e.g. `org-element-context'.
23593 (defun org-timestamp--to-internal-time (timestamp &optional end)
23594 "Encode TIMESTAMP object into Emacs internal time.
23595 Use end of date range or time range when END is non-nil."
23596 (apply #'encode-time
23597 (cons 0
23598 (mapcar
23599 (lambda (prop) (or (org-element-property prop timestamp) 0))
23600 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23601 '(:minute-start :hour-start :day-start :month-start
23602 :year-start))))))
23604 (defun org-timestamp-has-time-p (timestamp)
23605 "Non-nil when TIMESTAMP has a time specified."
23606 (org-element-property :hour-start timestamp))
23608 (defun org-timestamp-format (timestamp format &optional end utc)
23609 "Format a TIMESTAMP object into a string.
23611 FORMAT is a format specifier to be passed to
23612 `format-time-string'.
23614 When optional argument END is non-nil, use end of date-range or
23615 time-range, if possible.
23617 When optional argument UTC is non-nil, time will be expressed as
23618 Universal Time."
23619 (format-time-string
23620 format (org-timestamp--to-internal-time timestamp end)
23621 (and utc t)))
23623 (defun org-timestamp-split-range (timestamp &optional end)
23624 "Extract a TIMESTAMP object from a date or time range.
23626 END, when non-nil, means extract the end of the range.
23627 Otherwise, extract its start.
23629 Return a new timestamp object."
23630 (let ((type (org-element-property :type timestamp)))
23631 (if (memq type '(active inactive diary)) timestamp
23632 (let ((split-ts (org-element-copy timestamp)))
23633 ;; Set new type.
23634 (org-element-put-property
23635 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23636 ;; Copy start properties over end properties if END is
23637 ;; non-nil. Otherwise, copy end properties over `start' ones.
23638 (let ((p-alist '((:minute-start . :minute-end)
23639 (:hour-start . :hour-end)
23640 (:day-start . :day-end)
23641 (:month-start . :month-end)
23642 (:year-start . :year-end))))
23643 (dolist (p-cell p-alist)
23644 (org-element-put-property
23645 split-ts
23646 (funcall (if end #'car #'cdr) p-cell)
23647 (org-element-property
23648 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23649 ;; Eventually refresh `:raw-value'.
23650 (org-element-put-property split-ts :raw-value nil)
23651 (org-element-put-property
23652 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23654 (defun org-timestamp-translate (timestamp &optional boundary)
23655 "Translate TIMESTAMP object to custom format.
23657 Format string is defined in `org-time-stamp-custom-formats',
23658 which see.
23660 When optional argument BOUNDARY is non-nil, it is either the
23661 symbol `start' or `end'. In this case, only translate the
23662 starting or ending part of TIMESTAMP if it is a date or time
23663 range. Otherwise, translate both parts.
23665 Return timestamp as-is if `org-display-custom-times' is nil or if
23666 it has a `diary' type."
23667 (let ((type (org-element-property :type timestamp)))
23668 (if (or (not org-display-custom-times) (eq type 'diary))
23669 (org-element-interpret-data timestamp)
23670 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23671 org-time-stamp-custom-formats)))
23672 (if (and (not boundary) (memq type '(active-range inactive-range)))
23673 (concat (org-timestamp-format timestamp fmt)
23674 "--"
23675 (org-timestamp-format timestamp fmt t))
23676 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23680 ;;; Other stuff.
23682 (defvar reftex-docstruct-symbol)
23683 (defvar org--rds)
23685 (defun org-reftex-citation ()
23686 "Use reftex-citation to insert a citation into the buffer.
23687 This looks for a line like
23689 #+BIBLIOGRAPHY: foo plain option:-d
23691 and derives from it that foo.bib is the bibliography file relevant
23692 for this document. It then installs the necessary environment for RefTeX
23693 to work in this buffer and calls `reftex-citation' to insert a citation
23694 into the buffer.
23696 Export of such citations to both LaTeX and HTML is handled by the contributed
23697 package ox-bibtex by Taru Karttunen."
23698 (interactive)
23699 (let ((reftex-docstruct-symbol 'org--rds)
23700 org--rds bib)
23701 (org-with-wide-buffer
23702 (let ((case-fold-search t)
23703 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23704 (if (not (save-excursion
23705 (or (re-search-forward re nil t)
23706 (re-search-backward re nil t))))
23707 (user-error "No bibliography defined in file")
23708 (setq bib (concat (match-string 1) ".bib")
23709 org--rds (list (list 'bib bib))))))
23710 (call-interactively 'reftex-citation)))
23712 ;;;; Functions extending outline functionality
23714 (defun org-beginning-of-line (&optional arg)
23715 "Go to the beginning of the current line. If that is invisible, continue
23716 to a visible line beginning. This makes the function of C-a more intuitive.
23717 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23718 first attempt, and only move to after the tags when the cursor is already
23719 beyond the end of the headline."
23720 (interactive "P")
23721 (let ((pos (point))
23722 (special (if (consp org-special-ctrl-a/e)
23723 (car org-special-ctrl-a/e)
23724 org-special-ctrl-a/e))
23725 deactivate-mark refpos)
23726 (call-interactively (if (bound-and-true-p visual-line-mode)
23727 #'beginning-of-visual-line
23728 #'move-beginning-of-line))
23729 (cond
23730 ((or arg (not special)))
23731 ((and (looking-at org-complex-heading-regexp)
23732 (eq (char-after (match-end 1)) ?\s))
23733 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23734 (point-at-eol)))
23735 (goto-char
23736 (if (eq special t)
23737 (cond ((> pos refpos) refpos)
23738 ((= pos (point)) refpos)
23739 (t (point)))
23740 (cond ((> pos (point)) (point))
23741 ((not (eq last-command this-command)) (point))
23742 (t refpos)))))
23743 ((org-at-item-p)
23744 ;; Being at an item and not looking at an the item means point
23745 ;; was previously moved to beginning of a visual line, which
23746 ;; doesn't contain the item. Therefore, do nothing special,
23747 ;; just stay here.
23748 (when (looking-at org-list-full-item-re)
23749 ;; Set special position at first white space character after
23750 ;; bullet, and check-box, if any.
23751 (let ((after-bullet
23752 (let ((box (match-end 3)))
23753 (if (not box) (match-end 1)
23754 (let ((after (char-after box)))
23755 (if (and after (= after ? )) (1+ box) box))))))
23756 ;; Special case: Move point to special position when
23757 ;; currently after it or at beginning of line.
23758 (if (eq special t)
23759 (when (or (> pos after-bullet) (= (point) pos))
23760 (goto-char after-bullet))
23761 ;; Reversed case: Move point to special position when
23762 ;; point was already at beginning of line and command is
23763 ;; repeated.
23764 (when (and (= (point) pos) (eq last-command this-command))
23765 (goto-char after-bullet))))))))
23766 (setq disable-point-adjustment
23767 (or (not (invisible-p (point)))
23768 (not (invisible-p (max (point-min) (1- (point))))))))
23770 (defun org-end-of-line (&optional arg)
23771 "Go to the end of the line.
23772 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23773 tags on the first attempt, and only move to after the tags when
23774 the cursor is already beyond the end of the headline."
23775 (interactive "P")
23776 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23777 org-special-ctrl-a/e))
23778 (move-fun (cond ((bound-and-true-p visual-line-mode)
23779 'end-of-visual-line)
23780 ((fboundp 'move-end-of-line) 'move-end-of-line)
23781 (t 'end-of-line)))
23782 deactivate-mark)
23783 (if (or (not special) arg) (call-interactively move-fun)
23784 (let* ((element (save-excursion (beginning-of-line)
23785 (org-element-at-point)))
23786 (type (org-element-type element)))
23787 (cond
23788 ((memq type '(headline inlinetask))
23789 (let ((pos (point)))
23790 (beginning-of-line 1)
23791 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23792 (if (eq special t)
23793 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23794 (goto-char (match-beginning 1))
23795 (goto-char (match-end 0)))
23796 (if (or (< pos (match-end 0))
23797 (not (eq this-command last-command)))
23798 (goto-char (match-end 0))
23799 (goto-char (match-beginning 1))))
23800 (call-interactively move-fun))))
23801 ((outline-invisible-p (line-end-position))
23802 ;; If element is hidden, `move-end-of-line' would put point
23803 ;; after it. Use `end-of-line' to stay on current line.
23804 (call-interactively 'end-of-line))
23805 (t (call-interactively move-fun))))))
23806 (setq disable-point-adjustment
23807 (or (not (invisible-p (point)))
23808 (not (invisible-p (max (point-min) (1- (point))))))))
23810 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23811 (define-key org-mode-map "\C-e" 'org-end-of-line)
23813 (defun org-backward-sentence (&optional _arg)
23814 "Go to beginning of sentence, or beginning of table field.
23815 This will call `backward-sentence' or `org-table-beginning-of-field',
23816 depending on context."
23817 (interactive)
23818 (let* ((element (org-element-at-point))
23819 (contents-begin (org-element-property :contents-begin element))
23820 (table (org-element-lineage element '(table) t)))
23821 (if (and table
23822 (> (point) contents-begin)
23823 (<= (point) (org-element-property :contents-end table)))
23824 (call-interactively #'org-table-beginning-of-field)
23825 (save-restriction
23826 (when (and contents-begin
23827 (< (point-min) contents-begin)
23828 (> (point) contents-begin))
23829 (narrow-to-region contents-begin
23830 (org-element-property :contents-end element)))
23831 (call-interactively #'backward-sentence)))))
23833 (defun org-forward-sentence (&optional _arg)
23834 "Go to end of sentence, or end of table field.
23835 This will call `forward-sentence' or `org-table-end-of-field',
23836 depending on context."
23837 (interactive)
23838 (let* ((element (org-element-at-point))
23839 (contents-end (org-element-property :contents-end element))
23840 (table (org-element-lineage element '(table) t)))
23841 (if (and table
23842 (>= (point) (org-element-property :contents-begin table))
23843 (< (point) contents-end))
23844 (call-interactively #'org-table-end-of-field)
23845 (save-restriction
23846 (when (and contents-end
23847 (> (point-max) contents-end)
23848 ;; Skip blank lines between elements.
23849 (< (org-element-property :end element)
23850 (save-excursion (goto-char contents-end)
23851 (skip-chars-forward " \r\t\n"))))
23852 (narrow-to-region (org-element-property :contents-begin element)
23853 contents-end))
23854 (call-interactively #'forward-sentence)))))
23856 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23857 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23859 (defun org-kill-line (&optional _arg)
23860 "Kill line, to tags or end of line."
23861 (interactive)
23862 (cond
23863 ((or (not org-special-ctrl-k)
23864 (bolp)
23865 (not (org-at-heading-p)))
23866 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23867 org-ctrl-k-protect-subtree
23868 (or (eq org-ctrl-k-protect-subtree 'error)
23869 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23870 (user-error "C-k aborted as it would kill a hidden subtree"))
23871 (call-interactively
23872 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23873 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23874 (kill-region (point) (match-beginning 1))
23875 (org-set-tags nil t))
23876 (t (kill-region (point) (point-at-eol)))))
23878 (define-key org-mode-map "\C-k" 'org-kill-line)
23880 (defun org-yank (&optional arg)
23881 "Yank. If the kill is a subtree, treat it specially.
23882 This command will look at the current kill and check if is a single
23883 subtree, or a series of subtrees[1]. If it passes the test, and if the
23884 cursor is at the beginning of a line or after the stars of a currently
23885 empty headline, then the yank is handled specially. How exactly depends
23886 on the value of the following variables.
23888 `org-yank-folded-subtrees'
23889 By default, this variable is non-nil, which results in
23890 subtree(s) being folded after insertion, except if doing so
23891 would swallow text after the yanked text.
23893 `org-yank-adjusted-subtrees'
23894 When non-nil (the default value is nil), the subtree will be
23895 promoted or demoted in order to fit into the local outline tree
23896 structure, which means that the level will be adjusted so that it
23897 becomes the smaller one of the two *visible* surrounding headings.
23899 Any prefix to this command will cause `yank' to be called directly with
23900 no special treatment. In particular, a simple \\[universal-argument] prefix \
23901 will just
23902 plainly yank the text as it is.
23904 \[1] The test checks if the first non-white line is a heading
23905 and if there are no other headings with fewer stars."
23906 (interactive "P")
23907 (org-yank-generic 'yank arg))
23909 (defun org-yank-generic (command arg)
23910 "Perform some yank-like command.
23912 This function implements the behavior described in the `org-yank'
23913 documentation. However, it has been generalized to work for any
23914 interactive command with similar behavior."
23916 ;; pretend to be command COMMAND
23917 (setq this-command command)
23919 (if arg
23920 (call-interactively command)
23922 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23923 (and (org-kill-is-subtree-p)
23924 (or (bolp)
23925 (and (looking-at "[ \t]*$")
23926 (string-match
23927 "\\`\\*+\\'"
23928 (buffer-substring (point-at-bol) (point)))))))
23929 swallowp)
23930 (cond
23931 ((and subtreep org-yank-folded-subtrees)
23932 (let ((beg (point))
23933 end)
23934 (if (and subtreep org-yank-adjusted-subtrees)
23935 (org-paste-subtree nil nil 'for-yank)
23936 (call-interactively command))
23938 (setq end (point))
23939 (goto-char beg)
23940 (when (and (bolp) subtreep
23941 (not (setq swallowp
23942 (org-yank-folding-would-swallow-text beg end))))
23943 (org-with-limited-levels
23944 (or (looking-at org-outline-regexp)
23945 (re-search-forward org-outline-regexp-bol end t))
23946 (while (and (< (point) end) (looking-at org-outline-regexp))
23947 (outline-hide-subtree)
23948 (org-cycle-show-empty-lines 'folded)
23949 (condition-case nil
23950 (outline-forward-same-level 1)
23951 (error (goto-char end))))))
23952 (when swallowp
23953 (message
23954 "Inserted text not folded because that would swallow text"))
23956 (goto-char end)
23957 (skip-chars-forward " \t\n\r")
23958 (beginning-of-line 1)
23959 (push-mark beg 'nomsg)))
23960 ((and subtreep org-yank-adjusted-subtrees)
23961 (let ((beg (point-at-bol)))
23962 (org-paste-subtree nil nil 'for-yank)
23963 (push-mark beg 'nomsg)))
23965 (call-interactively command))))))
23967 (defun org-yank-folding-would-swallow-text (beg end)
23968 "Would hide-subtree at BEG swallow any text after END?"
23969 (let (level)
23970 (org-with-limited-levels
23971 (save-excursion
23972 (goto-char beg)
23973 (when (or (looking-at org-outline-regexp)
23974 (re-search-forward org-outline-regexp-bol end t))
23975 (setq level (org-outline-level)))
23976 (goto-char end)
23977 (skip-chars-forward " \t\r\n\v\f")
23978 (not (or (eobp)
23979 (and (bolp) (looking-at-p org-outline-regexp)
23980 (<= (org-outline-level) level))))))))
23982 (define-key org-mode-map "\C-y" 'org-yank)
23984 (defun org-truely-invisible-p ()
23985 "Check if point is at a character currently not visible.
23986 This version does not only check the character property, but also
23987 `visible-mode'."
23988 ;; Early versions of noutline don't have `outline-invisible-p'.
23989 (unless (bound-and-true-p visible-mode)
23990 (outline-invisible-p)))
23992 (defun org-invisible-p2 ()
23993 "Check if point is at a character currently not visible."
23994 (save-excursion
23995 (when (and (eolp) (not (bobp))) (backward-char 1))
23996 ;; Early versions of noutline don't have `outline-invisible-p'.
23997 (outline-invisible-p)))
23999 (defun org-back-to-heading (&optional invisible-ok)
24000 "Call `outline-back-to-heading', but provide a better error message."
24001 (condition-case nil
24002 (outline-back-to-heading invisible-ok)
24003 (error (error "Before first headline at position %d in buffer %s"
24004 (point) (current-buffer)))))
24006 (defun org-before-first-heading-p ()
24007 "Before first heading?"
24008 (save-excursion
24009 (end-of-line)
24010 (null (re-search-backward org-outline-regexp-bol nil t))))
24012 (defun org-at-heading-p (&optional ignored)
24013 (outline-on-heading-p t))
24015 (defun org-in-commented-heading-p (&optional no-inheritance)
24016 "Non-nil if point is under a commented heading.
24017 This function also checks ancestors of the current headline,
24018 unless optional argument NO-INHERITANCE is non-nil."
24019 (cond
24020 ((org-before-first-heading-p) nil)
24021 ((let ((headline (nth 4 (org-heading-components))))
24022 (and headline
24023 (let ((case-fold-search nil))
24024 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24025 headline)))))
24026 (no-inheritance nil)
24028 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24030 (defun org-at-comment-p nil
24031 "Is cursor in a commented line?"
24032 (save-excursion
24033 (save-match-data
24034 (beginning-of-line)
24035 (looking-at "^[ \t]*# "))))
24037 (defun org-at-drawer-p nil
24038 "Is cursor at a drawer keyword?"
24039 (save-excursion
24040 (move-beginning-of-line 1)
24041 (looking-at org-drawer-regexp)))
24043 (defun org-at-block-p nil
24044 "Is cursor at a block keyword?"
24045 (save-excursion
24046 (move-beginning-of-line 1)
24047 (looking-at org-block-regexp)))
24049 (defun org-point-at-end-of-empty-headline ()
24050 "If point is at the end of an empty headline, return t, else nil.
24051 If the heading only contains a TODO keyword, it is still still considered
24052 empty."
24053 (and (looking-at "[ \t]*$")
24054 (when org-todo-line-regexp
24055 (save-excursion
24056 (beginning-of-line 1)
24057 (let ((case-fold-search nil))
24058 (looking-at org-todo-line-regexp)
24059 (string= (match-string 3) ""))))))
24061 (defun org-at-heading-or-item-p ()
24062 (or (org-at-heading-p) (org-at-item-p)))
24064 (defun org-at-target-p ()
24065 (or (org-in-regexp org-radio-target-regexp)
24066 (org-in-regexp org-target-regexp)))
24067 ;; Compatibility alias with Org versions < 7.8.03
24068 (defalias 'org-on-target-p 'org-at-target-p)
24070 (defun org-up-heading-all (arg)
24071 "Move to the heading line of which the present line is a subheading.
24072 This function considers both visible and invisible heading lines.
24073 With argument, move up ARG levels."
24074 (outline-up-heading arg t))
24076 (defun org-up-heading-safe ()
24077 "Move to the heading line of which the present line is a subheading.
24078 This version will not throw an error. It will return the level of the
24079 headline found, or nil if no higher level is found.
24081 Also, this function will be a lot faster than `outline-up-heading',
24082 because it relies on stars being the outline starters. This can really
24083 make a significant difference in outlines with very many siblings."
24084 (when (ignore-errors (org-back-to-heading t))
24085 (let ((level-up (1- (funcall outline-level))))
24086 (and (> level-up 0)
24087 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24088 (funcall outline-level)))))
24090 (defun org-first-sibling-p ()
24091 "Is this heading the first child of its parents?"
24092 (interactive)
24093 (let ((re org-outline-regexp-bol)
24094 level l)
24095 (unless (org-at-heading-p t)
24096 (user-error "Not at a heading"))
24097 (setq level (funcall outline-level))
24098 (save-excursion
24099 (if (not (re-search-backward re nil t))
24101 (setq l (funcall outline-level))
24102 (< l level)))))
24104 (defun org-goto-sibling (&optional previous)
24105 "Goto the next sibling, even if it is invisible.
24106 When PREVIOUS is set, go to the previous sibling instead. Returns t
24107 when a sibling was found. When none is found, return nil and don't
24108 move point."
24109 (let ((fun (if previous 're-search-backward 're-search-forward))
24110 (pos (point))
24111 (re org-outline-regexp-bol)
24112 level l)
24113 (when (ignore-errors (org-back-to-heading t))
24114 (setq level (funcall outline-level))
24115 (catch 'exit
24116 (or previous (forward-char 1))
24117 (while (funcall fun re nil t)
24118 (setq l (funcall outline-level))
24119 (when (< l level) (goto-char pos) (throw 'exit nil))
24120 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24121 (goto-char pos)
24122 nil))))
24124 (defun org-show-siblings ()
24125 "Show all siblings of the current headline."
24126 (save-excursion
24127 (while (org-goto-sibling) (org-flag-heading nil)))
24128 (save-excursion
24129 (while (org-goto-sibling 'previous)
24130 (org-flag-heading nil))))
24132 (defun org-goto-first-child ()
24133 "Goto the first child, even if it is invisible.
24134 Return t when a child was found. Otherwise don't move point and
24135 return nil."
24136 (let (level (pos (point)) (re org-outline-regexp-bol))
24137 (when (ignore-errors (org-back-to-heading t))
24138 (setq level (outline-level))
24139 (forward-char 1)
24140 (if (and (re-search-forward re nil t) (> (outline-level) level))
24141 (progn (goto-char (match-beginning 0)) t)
24142 (goto-char pos) nil))))
24144 (defun org-show-hidden-entry ()
24145 "Show an entry where even the heading is hidden."
24146 (save-excursion
24147 (org-show-entry)))
24149 (defun org-flag-heading (flag &optional entry)
24150 "Flag the current heading. FLAG non-nil means make invisible.
24151 When ENTRY is non-nil, show the entire entry."
24152 (save-excursion
24153 (org-back-to-heading t)
24154 ;; Check if we should show the entire entry
24155 (if entry
24156 (progn
24157 (org-show-entry)
24158 (save-excursion
24159 (and (outline-next-heading)
24160 (org-flag-heading nil))))
24161 (outline-flag-region (max (point-min) (1- (point)))
24162 (save-excursion (outline-end-of-heading) (point))
24163 flag))))
24165 (defun org-get-next-sibling ()
24166 "Move to next heading of the same level, and return point.
24167 If there is no such heading, return nil.
24168 This is like outline-next-sibling, but invisible headings are ok."
24169 (let ((level (funcall outline-level)))
24170 (outline-next-heading)
24171 (while (and (not (eobp)) (> (funcall outline-level) level))
24172 (outline-next-heading))
24173 (unless (or (eobp) (< (funcall outline-level) level))
24174 (point))))
24176 (defun org-get-last-sibling ()
24177 "Move to previous heading of the same level, and return point.
24178 If there is no such heading, return nil."
24179 (let ((opoint (point))
24180 (level (funcall outline-level)))
24181 (outline-previous-heading)
24182 (when (and (/= (point) opoint) (outline-on-heading-p t))
24183 (while (and (> (funcall outline-level) level)
24184 (not (bobp)))
24185 (outline-previous-heading))
24186 (unless (< (funcall outline-level) level)
24187 (point)))))
24189 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24190 "Goto to the end of a subtree."
24191 ;; This contains an exact copy of the original function, but it uses
24192 ;; `org-back-to-heading', to make it work also in invisible
24193 ;; trees. And is uses an invisible-ok argument.
24194 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24195 ;; Furthermore, when used inside Org, finding the end of a large subtree
24196 ;; with many children and grandchildren etc, this can be much faster
24197 ;; than the outline version.
24198 (org-back-to-heading invisible-ok)
24199 (let ((first t)
24200 (level (funcall outline-level)))
24201 (if (and (derived-mode-p 'org-mode) (< level 1000))
24202 ;; A true heading (not a plain list item), in Org
24203 ;; This means we can easily find the end by looking
24204 ;; only for the right number of stars. Using a regexp to do
24205 ;; this is so much faster than using a Lisp loop.
24206 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24207 (forward-char 1)
24208 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24209 ;; something else, do it the slow way
24210 (while (and (not (eobp))
24211 (or first (> (funcall outline-level) level)))
24212 (setq first nil)
24213 (outline-next-heading)))
24214 (unless to-heading
24215 (when (memq (preceding-char) '(?\n ?\^M))
24216 ;; Go to end of line before heading
24217 (forward-char -1)
24218 (when (memq (preceding-char) '(?\n ?\^M))
24219 ;; leave blank line before heading
24220 (forward-char -1)))))
24221 (point))
24223 (defun org-end-of-meta-data (&optional full)
24224 "Skip planning line and properties drawer in current entry.
24225 When optional argument FULL is non-nil, also skip empty lines,
24226 clocking lines and regular drawers at the beginning of the
24227 entry."
24228 (org-back-to-heading t)
24229 (forward-line)
24230 (when (looking-at-p org-planning-line-re) (forward-line))
24231 (when (looking-at org-property-drawer-re)
24232 (goto-char (match-end 0))
24233 (forward-line))
24234 (when (and full (not (org-at-heading-p)))
24235 (catch 'exit
24236 (let ((end (save-excursion (outline-next-heading) (point)))
24237 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24238 (while (not (eobp))
24239 (cond ((looking-at-p org-drawer-regexp)
24240 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24241 (forward-line)
24242 (throw 'exit t)))
24243 ((looking-at-p re) (forward-line))
24244 (t (throw 'exit t))))))))
24246 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24247 "Move forward to the ARG'th subheading at same level as this one.
24248 Stop at the first and last subheadings of a superior heading.
24249 Normally this only looks at visible headings, but when INVISIBLE-OK is
24250 non-nil it will also look at invisible ones."
24251 (interactive "p")
24252 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24253 (if (and arg (< arg 0))
24254 (goto-char (point-min))
24255 (outline-next-heading))
24256 (org-at-heading-p)
24257 (let ((level (- (match-end 0) (match-beginning 0) 1))
24258 (f (if (and arg (< arg 0))
24259 're-search-backward
24260 're-search-forward))
24261 (count (if arg (abs arg) 1))
24262 (result (point)))
24263 (while (and (prog1 (> count 0)
24264 (forward-char (if (and arg (< arg 0)) -1 1)))
24265 (funcall f org-outline-regexp-bol nil 'move))
24266 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24267 (cond ((< l level) (setq count 0))
24268 ((and (= l level)
24269 (or invisible-ok
24270 (progn
24271 (goto-char (line-beginning-position))
24272 (not (outline-invisible-p)))))
24273 (setq count (1- count))
24274 (when (eq l level)
24275 (setq result (point)))))))
24276 (goto-char result))
24277 (beginning-of-line 1)))
24279 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24280 "Move backward to the ARG'th subheading at same level as this one.
24281 Stop at the first and last subheadings of a superior heading."
24282 (interactive "p")
24283 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24285 (defun org-next-visible-heading (arg)
24286 "Move to the next visible heading.
24288 This function wraps `outline-next-visible-heading' with
24289 `org-with-limited-levels' in order to skip over inline tasks and
24290 respect customization of `org-odd-levels-only'."
24291 (interactive "p")
24292 (org-with-limited-levels
24293 (outline-next-visible-heading arg)))
24295 (defun org-previous-visible-heading (arg)
24296 "Move to the previous visible heading.
24298 This function wraps `outline-previous-visible-heading' with
24299 `org-with-limited-levels' in order to skip over inline tasks and
24300 respect customization of `org-odd-levels-only'."
24301 (interactive "p")
24302 (org-with-limited-levels
24303 (outline-previous-visible-heading arg)))
24305 (defun org-next-block (arg &optional backward block-regexp)
24306 "Jump to the next block.
24308 With a prefix argument ARG, jump forward ARG many blocks.
24310 When BACKWARD is non-nil, jump to the previous block.
24312 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24313 Match data is set according to this regexp when the function
24314 returns.
24316 Return point at beginning of the opening line of found block.
24317 Throw an error if no block is found."
24318 (interactive "p")
24319 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24320 (case-fold-search t)
24321 (search-fn (if backward #'re-search-backward #'re-search-forward))
24322 (count (or arg 1))
24323 (origin (point))
24324 last-element)
24325 (if backward (beginning-of-line) (end-of-line))
24326 (while (and (> count 0) (funcall search-fn re nil t))
24327 (let ((element (save-excursion
24328 (goto-char (match-beginning 0))
24329 (save-match-data (org-element-at-point)))))
24330 (when (and (memq (org-element-type element)
24331 '(center-block comment-block dynamic-block
24332 example-block export-block quote-block
24333 special-block src-block verse-block))
24334 (<= (match-beginning 0)
24335 (org-element-property :post-affiliated element)))
24336 (setq last-element element)
24337 (cl-decf count))))
24338 (if (= count 0)
24339 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24340 (save-match-data (org-show-context)))
24341 (goto-char origin)
24342 (user-error "No %s code blocks" (if backward "previous" "further")))))
24344 (defun org-previous-block (arg &optional block-regexp)
24345 "Jump to the previous block.
24346 With a prefix argument ARG, jump backward ARG many source blocks.
24347 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24348 (interactive "p")
24349 (org-next-block arg t block-regexp))
24351 (defun org-forward-paragraph ()
24352 "Move forward to beginning of next paragraph or equivalent.
24354 The function moves point to the beginning of the next visible
24355 structural element, which can be a paragraph, a table, a list
24356 item, etc. It also provides some special moves for convenience:
24358 - On an affiliated keyword, jump to the beginning of the
24359 relative element.
24360 - On an item or a footnote definition, move to the second
24361 element inside, if any.
24362 - On a table or a property drawer, jump after it.
24363 - On a verse or source block, stop after blank lines."
24364 (interactive)
24365 (when (eobp) (user-error "Cannot move further down"))
24366 (let* ((deactivate-mark nil)
24367 (element (org-element-at-point))
24368 (type (org-element-type element))
24369 (post-affiliated (org-element-property :post-affiliated element))
24370 (contents-begin (org-element-property :contents-begin element))
24371 (contents-end (org-element-property :contents-end element))
24372 (end (let ((end (org-element-property :end element)) (parent element))
24373 (while (and (setq parent (org-element-property :parent parent))
24374 (= (org-element-property :contents-end parent) end))
24375 (setq end (org-element-property :end parent)))
24376 end)))
24377 (cond ((not element)
24378 (skip-chars-forward " \r\t\n")
24379 (or (eobp) (beginning-of-line)))
24380 ;; On affiliated keywords, move to element's beginning.
24381 ((< (point) post-affiliated)
24382 (goto-char post-affiliated))
24383 ;; At a table row, move to the end of the table. Similarly,
24384 ;; at a node property, move to the end of the property
24385 ;; drawer.
24386 ((memq type '(node-property table-row))
24387 (goto-char (org-element-property
24388 :end (org-element-property :parent element))))
24389 ((memq type '(property-drawer table)) (goto-char end))
24390 ;; Consider blank lines as separators in verse and source
24391 ;; blocks to ease editing.
24392 ((memq type '(src-block verse-block))
24393 (when (eq type 'src-block)
24394 (setq contents-end
24395 (save-excursion (goto-char end)
24396 (skip-chars-backward " \r\t\n")
24397 (line-beginning-position))))
24398 (beginning-of-line)
24399 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24400 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24401 (goto-char end)
24402 (skip-chars-forward " \r\t\n")
24403 (if (= (point) contents-end) (goto-char end)
24404 (beginning-of-line))))
24405 ;; With no contents, just skip element.
24406 ((not contents-begin) (goto-char end))
24407 ;; If contents are invisible, skip the element altogether.
24408 ((outline-invisible-p (line-end-position))
24409 (cl-case type
24410 (headline
24411 (org-with-limited-levels (outline-next-visible-heading 1)))
24412 ;; At a plain list, make sure we move to the next item
24413 ;; instead of skipping the whole list.
24414 (plain-list (forward-char)
24415 (org-forward-paragraph))
24416 (otherwise (goto-char end))))
24417 ((>= (point) contents-end) (goto-char end))
24418 ((>= (point) contents-begin)
24419 ;; This can only happen on paragraphs and plain lists.
24420 (cl-case type
24421 (paragraph (goto-char end))
24422 ;; At a plain list, try to move to second element in
24423 ;; first item, if possible.
24424 (plain-list (end-of-line)
24425 (org-forward-paragraph))))
24426 ;; When contents start on the middle of a line (e.g. in
24427 ;; items and footnote definitions), try to reach first
24428 ;; element starting after current line.
24429 ((> (line-end-position) contents-begin)
24430 (end-of-line)
24431 (org-forward-paragraph))
24432 (t (goto-char contents-begin)))))
24434 (defun org-backward-paragraph ()
24435 "Move backward to start of previous paragraph or equivalent.
24437 The function moves point to the beginning of the current
24438 structural element, which can be a paragraph, a table, a list
24439 item, etc., or to the beginning of the previous visible one if
24440 point is already there. It also provides some special moves for
24441 convenience:
24443 - On an affiliated keyword, jump to the first one.
24444 - On a table or a property drawer, move to its beginning.
24445 - On a verse or source block, stop before blank lines."
24446 (interactive)
24447 (when (bobp) (user-error "Cannot move further up"))
24448 (let* ((deactivate-mark nil)
24449 (element (org-element-at-point))
24450 (type (org-element-type element))
24451 (contents-begin (org-element-property :contents-begin element))
24452 (contents-end (org-element-property :contents-end element))
24453 (post-affiliated (org-element-property :post-affiliated element))
24454 (begin (org-element-property :begin element)))
24455 (cond
24456 ((not element) (goto-char (point-min)))
24457 ((= (point) begin)
24458 (backward-char)
24459 (org-backward-paragraph))
24460 ((<= (point) post-affiliated) (goto-char begin))
24461 ((memq type '(node-property table-row))
24462 (goto-char (org-element-property
24463 :post-affiliated (org-element-property :parent element))))
24464 ((memq type '(property-drawer table)) (goto-char begin))
24465 ((memq type '(src-block verse-block))
24466 (when (eq type 'src-block)
24467 (setq contents-begin
24468 (save-excursion (goto-char begin) (forward-line) (point))))
24469 (if (= (point) contents-begin) (goto-char post-affiliated)
24470 ;; Inside a verse block, see blank lines as paragraph
24471 ;; separators.
24472 (let ((origin (point)))
24473 (skip-chars-backward " \r\t\n" contents-begin)
24474 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24475 (skip-chars-forward " \r\t\n" origin)
24476 (if (= (point) origin) (goto-char contents-begin)
24477 (beginning-of-line))))))
24478 ((not contents-begin) (goto-char (or post-affiliated begin)))
24479 ((eq type 'paragraph)
24480 (goto-char contents-begin)
24481 ;; When at first paragraph in an item or a footnote definition,
24482 ;; move directly to beginning of line.
24483 (let ((parent-contents
24484 (org-element-property
24485 :contents-begin (org-element-property :parent element))))
24486 (when (and parent-contents (= parent-contents contents-begin))
24487 (beginning-of-line))))
24488 ;; At the end of a greater element, move to the beginning of the
24489 ;; last element within.
24490 ((>= (point) contents-end)
24491 (goto-char (1- contents-end))
24492 (org-backward-paragraph))
24493 (t (goto-char (or post-affiliated begin))))
24494 ;; Ensure we never leave point invisible.
24495 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24497 (defun org-forward-element ()
24498 "Move forward by one element.
24499 Move to the next element at the same level, when possible."
24500 (interactive)
24501 (cond ((eobp) (user-error "Cannot move further down"))
24502 ((org-with-limited-levels (org-at-heading-p))
24503 (let ((origin (point)))
24504 (goto-char (org-end-of-subtree nil t))
24505 (unless (org-with-limited-levels (org-at-heading-p))
24506 (goto-char origin)
24507 (user-error "Cannot move further down"))))
24509 (let* ((elem (org-element-at-point))
24510 (end (org-element-property :end elem))
24511 (parent (org-element-property :parent elem)))
24512 (cond ((and parent (= (org-element-property :contents-end parent) end))
24513 (goto-char (org-element-property :end parent)))
24514 ((integer-or-marker-p end) (goto-char end))
24515 (t (message "No element at point")))))))
24517 (defun org-backward-element ()
24518 "Move backward by one element.
24519 Move to the previous element at the same level, when possible."
24520 (interactive)
24521 (cond ((bobp) (user-error "Cannot move further up"))
24522 ((org-with-limited-levels (org-at-heading-p))
24523 ;; At a headline, move to the previous one, if any, or stay
24524 ;; here.
24525 (let ((origin (point)))
24526 (org-with-limited-levels (org-backward-heading-same-level 1))
24527 ;; When current headline has no sibling above, move to its
24528 ;; parent.
24529 (when (= (point) origin)
24530 (or (org-with-limited-levels (org-up-heading-safe))
24531 (progn (goto-char origin)
24532 (user-error "Cannot move further up"))))))
24534 (let* ((elem (org-element-at-point))
24535 (beg (org-element-property :begin elem)))
24536 (cond
24537 ;; Move to beginning of current element if point isn't
24538 ;; there already.
24539 ((null beg) (message "No element at point"))
24540 ((/= (point) beg) (goto-char beg))
24541 (t (goto-char beg)
24542 (skip-chars-backward " \r\t\n")
24543 (unless (bobp)
24544 (let ((prev (org-element-at-point)))
24545 (goto-char (org-element-property :begin prev))
24546 (while (and (setq prev (org-element-property :parent prev))
24547 (<= (org-element-property :end prev) beg))
24548 (goto-char (org-element-property :begin prev)))))))))))
24550 (defun org-up-element ()
24551 "Move to upper element."
24552 (interactive)
24553 (if (org-with-limited-levels (org-at-heading-p))
24554 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24555 (let* ((elem (org-element-at-point))
24556 (parent (org-element-property :parent elem)))
24557 (if parent (goto-char (org-element-property :begin parent))
24558 (if (org-with-limited-levels (org-before-first-heading-p))
24559 (user-error "No surrounding element")
24560 (org-with-limited-levels (org-back-to-heading)))))))
24562 (defvar org-element-greater-elements)
24563 (defun org-down-element ()
24564 "Move to inner element."
24565 (interactive)
24566 (let ((element (org-element-at-point)))
24567 (cond
24568 ((memq (org-element-type element) '(plain-list table))
24569 (goto-char (org-element-property :contents-begin element))
24570 (forward-char))
24571 ((memq (org-element-type element) org-element-greater-elements)
24572 ;; If contents are hidden, first disclose them.
24573 (when (outline-invisible-p (line-end-position)) (org-cycle))
24574 (goto-char (or (org-element-property :contents-begin element)
24575 (user-error "No content for this element"))))
24576 (t (user-error "No inner element")))))
24578 (defun org-drag-element-backward ()
24579 "Move backward element at point."
24580 (interactive)
24581 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24582 (let* ((elem (org-element-at-point))
24583 (prev-elem
24584 (save-excursion
24585 (goto-char (org-element-property :begin elem))
24586 (skip-chars-backward " \r\t\n")
24587 (unless (bobp)
24588 (let* ((beg (org-element-property :begin elem))
24589 (prev (org-element-at-point))
24590 (up prev))
24591 (while (and (setq up (org-element-property :parent up))
24592 (<= (org-element-property :end up) beg))
24593 (setq prev up))
24594 prev)))))
24595 ;; Error out if no previous element or previous element is
24596 ;; a parent of the current one.
24597 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24598 (user-error "Cannot drag element backward")
24599 (let ((pos (point)))
24600 (org-element-swap-A-B prev-elem elem)
24601 (goto-char (+ (org-element-property :begin prev-elem)
24602 (- pos (org-element-property :begin elem)))))))))
24604 (defun org-drag-element-forward ()
24605 "Move forward element at point."
24606 (interactive)
24607 (let* ((pos (point))
24608 (elem (org-element-at-point)))
24609 (when (= (point-max) (org-element-property :end elem))
24610 (user-error "Cannot drag element forward"))
24611 (goto-char (org-element-property :end elem))
24612 (let ((next-elem (org-element-at-point)))
24613 (when (or (org-element-nested-p elem next-elem)
24614 (and (eq (org-element-type next-elem) 'headline)
24615 (not (eq (org-element-type elem) 'headline))))
24616 (goto-char pos)
24617 (user-error "Cannot drag element forward"))
24618 ;; Compute new position of point: it's shifted by NEXT-ELEM
24619 ;; body's length (without final blanks) and by the length of
24620 ;; blanks between ELEM and NEXT-ELEM.
24621 (let ((size-next (- (save-excursion
24622 (goto-char (org-element-property :end next-elem))
24623 (skip-chars-backward " \r\t\n")
24624 (forward-line)
24625 ;; Small correction if buffer doesn't end
24626 ;; with a newline character.
24627 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24628 (org-element-property :begin next-elem)))
24629 (size-blank (- (org-element-property :end elem)
24630 (save-excursion
24631 (goto-char (org-element-property :end elem))
24632 (skip-chars-backward " \r\t\n")
24633 (forward-line)
24634 (point)))))
24635 (org-element-swap-A-B elem next-elem)
24636 (goto-char (+ pos size-next size-blank))))))
24638 (defun org-drag-line-forward (arg)
24639 "Drag the line at point ARG lines forward."
24640 (interactive "p")
24641 (dotimes (_ (abs arg))
24642 (let ((c (current-column)))
24643 (if (< 0 arg)
24644 (progn
24645 (beginning-of-line 2)
24646 (transpose-lines 1)
24647 (beginning-of-line 0))
24648 (transpose-lines 1)
24649 (beginning-of-line -1))
24650 (org-move-to-column c))))
24652 (defun org-drag-line-backward (arg)
24653 "Drag the line at point ARG lines backward."
24654 (interactive "p")
24655 (org-drag-line-forward (- arg)))
24657 (defun org-mark-element ()
24658 "Put point at beginning of this element, mark at end.
24660 Interactively, if this command is repeated or (in Transient Mark
24661 mode) if the mark is active, it marks the next element after the
24662 ones already marked."
24663 (interactive)
24664 (let (deactivate-mark)
24665 (if (and (called-interactively-p 'any)
24666 (or (and (eq last-command this-command) (mark t))
24667 (and transient-mark-mode mark-active)))
24668 (set-mark
24669 (save-excursion
24670 (goto-char (mark))
24671 (goto-char (org-element-property :end (org-element-at-point)))))
24672 (let ((element (org-element-at-point)))
24673 (end-of-line)
24674 (push-mark (org-element-property :end element) t t)
24675 (goto-char (org-element-property :begin element))))))
24677 (defun org-narrow-to-element ()
24678 "Narrow buffer to current element."
24679 (interactive)
24680 (let ((elem (org-element-at-point)))
24681 (cond
24682 ((eq (car elem) 'headline)
24683 (narrow-to-region
24684 (org-element-property :begin elem)
24685 (org-element-property :end elem)))
24686 ((memq (car elem) org-element-greater-elements)
24687 (narrow-to-region
24688 (org-element-property :contents-begin elem)
24689 (org-element-property :contents-end elem)))
24691 (narrow-to-region
24692 (org-element-property :begin elem)
24693 (org-element-property :end elem))))))
24695 (defun org-transpose-element ()
24696 "Transpose current and previous elements, keeping blank lines between.
24697 Point is moved after both elements."
24698 (interactive)
24699 (org-skip-whitespace)
24700 (let ((end (org-element-property :end (org-element-at-point))))
24701 (org-drag-element-backward)
24702 (goto-char end)))
24704 (defun org-unindent-buffer ()
24705 "Un-indent the visible part of the buffer.
24706 Relative indentation (between items, inside blocks, etc.) isn't
24707 modified."
24708 (interactive)
24709 (unless (eq major-mode 'org-mode)
24710 (user-error "Cannot un-indent a buffer not in Org mode"))
24711 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24712 (unindent-tree
24713 (lambda (contents)
24714 (dolist (element (reverse contents))
24715 (if (memq (org-element-type element) '(headline section))
24716 (funcall unindent-tree (org-element-contents element))
24717 (save-excursion
24718 (save-restriction
24719 (narrow-to-region
24720 (org-element-property :begin element)
24721 (org-element-property :end element))
24722 (org-do-remove-indentation))))))))
24723 (funcall unindent-tree (org-element-contents parse-tree))))
24725 (defun org-show-children (&optional level)
24726 "Show all direct subheadings of this heading.
24727 Prefix arg LEVEL is how many levels below the current level
24728 should be shown. Default is enough to cause the following
24729 heading to appear."
24730 (interactive "p")
24731 ;; If `orgstruct-mode' is active, use the slower version.
24732 (if orgstruct-mode (call-interactively #'outline-show-children)
24733 (save-excursion
24734 (org-back-to-heading t)
24735 (let* ((current-level (funcall outline-level))
24736 (max-level (org-get-valid-level
24737 current-level
24738 (if level (prefix-numeric-value level) 1)))
24739 (end (save-excursion (org-end-of-subtree t t)))
24740 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24741 (past-first-child nil)
24742 ;; Make sure to skip inlinetasks.
24743 (re (format regexp-fmt
24744 current-level
24745 (cond
24746 ((not (featurep 'org-inlinetask)) "")
24747 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24749 (t (1- org-inlinetask-min-level))))))
24750 ;; Display parent heading.
24751 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24752 (forward-line)
24753 ;; Display children. First child may be deeper than expected
24754 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24755 ;; MAX-LEVEL accordingly.
24756 (while (re-search-forward re end t)
24757 (unless past-first-child
24758 (setq re (format regexp-fmt
24759 current-level
24760 (max (funcall outline-level) max-level)))
24761 (setq past-first-child t))
24762 (outline-flag-region
24763 (line-end-position 0) (line-end-position) nil))))))
24765 (defun org-show-subtree ()
24766 "Show everything after this heading at deeper levels."
24767 (interactive)
24768 (outline-flag-region
24769 (point)
24770 (save-excursion
24771 (org-end-of-subtree t t))
24772 nil))
24774 (defun org-show-entry ()
24775 "Show the body directly following this heading.
24776 Show the heading too, if it is currently invisible."
24777 (interactive)
24778 (save-excursion
24779 (ignore-errors
24780 (org-back-to-heading t)
24781 (outline-flag-region
24782 (max (point-min) (1- (point)))
24783 (save-excursion
24784 (if (re-search-forward
24785 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24786 (match-beginning 1)
24787 (point-max)))
24788 nil)
24789 (org-cycle-hide-drawers 'children))))
24791 (defun org-make-options-regexp (kwds &optional extra)
24792 "Make a regular expression for keyword lines.
24793 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24794 when non-nil, is a regexp matching keywords names."
24795 (concat "^[ \t]*#\\+\\("
24796 (regexp-opt kwds)
24797 (and extra (concat (and kwds "\\|") extra))
24798 "\\):[ \t]*\\(.*\\)"))
24800 ;;;; Integration with and fixes for other packages
24802 ;;; Imenu support
24804 (defvar-local org-imenu-markers nil
24805 "All markers currently used by Imenu.")
24807 (defun org-imenu-new-marker (&optional pos)
24808 "Return a new marker for use by Imenu, and remember the marker."
24809 (let ((m (make-marker)))
24810 (move-marker m (or pos (point)))
24811 (push m org-imenu-markers)
24814 (defun org-imenu-get-tree ()
24815 "Produce the index for Imenu."
24816 (dolist (x org-imenu-markers) (move-marker x nil))
24817 (setq org-imenu-markers nil)
24818 (let* ((case-fold-search nil)
24819 (n org-imenu-depth)
24820 (re (concat "^" (org-get-limited-outline-regexp)))
24821 (subs (make-vector (1+ n) nil))
24822 (last-level 0)
24823 m level head0 head)
24824 (org-with-wide-buffer
24825 (goto-char (point-max))
24826 (while (re-search-backward re nil t)
24827 (setq level (org-reduced-level (funcall outline-level)))
24828 (when (and (<= level n)
24829 (looking-at org-complex-heading-regexp)
24830 (setq head0 (match-string-no-properties 4)))
24831 (setq head (org-link-display-format head0)
24832 m (org-imenu-new-marker))
24833 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24834 (if (>= level last-level)
24835 (push (cons head m) (aref subs level))
24836 (push (cons head (aref subs (1+ level))) (aref subs level))
24837 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24838 (setq last-level level))))
24839 (aref subs 1)))
24841 (eval-after-load "imenu"
24842 '(progn
24843 (add-hook 'imenu-after-jump-hook
24844 (lambda ()
24845 (when (derived-mode-p 'org-mode)
24846 (org-show-context 'org-goto))))))
24848 (defun org-link-display-format (s)
24849 "Replace links in string S with their description.
24850 If there is no description, use the link target."
24851 (save-match-data
24852 (replace-regexp-in-string
24853 org-bracket-link-analytic-regexp
24854 (lambda (m)
24855 (if (match-end 5) (match-string 5 m)
24856 (concat (match-string 1 m) (match-string 3 m))))
24857 s nil t)))
24859 (defun org-toggle-link-display ()
24860 "Toggle the literal or descriptive display of links."
24861 (interactive)
24862 (if org-descriptive-links
24863 (progn (org-remove-from-invisibility-spec '(org-link))
24864 (org-restart-font-lock)
24865 (setq org-descriptive-links nil))
24866 (progn (add-to-invisibility-spec '(org-link))
24867 (org-restart-font-lock)
24868 (setq org-descriptive-links t))))
24870 ;; Speedbar support
24872 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24873 "Overlay marking the agenda restriction line in speedbar.")
24874 (overlay-put org-speedbar-restriction-lock-overlay
24875 'face 'org-agenda-restriction-lock)
24876 (overlay-put org-speedbar-restriction-lock-overlay
24877 'help-echo "Agendas are currently limited to this item.")
24878 (delete-overlay org-speedbar-restriction-lock-overlay)
24880 (defun org-speedbar-set-agenda-restriction ()
24881 "Restrict future agenda commands to the location at point in speedbar.
24882 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24883 (interactive)
24884 (require 'org-agenda)
24885 (let (p m tp np dir txt)
24886 (cond
24887 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24888 'org-imenu t))
24889 (setq m (get-text-property p 'org-imenu-marker))
24890 (with-current-buffer (marker-buffer m)
24891 (goto-char m)
24892 (org-agenda-set-restriction-lock 'subtree)))
24893 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24894 'speedbar-function 'speedbar-find-file))
24895 (setq tp (previous-single-property-change
24896 (1+ p) 'speedbar-function)
24897 np (next-single-property-change
24898 tp 'speedbar-function)
24899 dir (speedbar-line-directory)
24900 txt (buffer-substring-no-properties (or tp (point-min))
24901 (or np (point-max))))
24902 (with-current-buffer (find-file-noselect
24903 (let ((default-directory dir))
24904 (expand-file-name txt)))
24905 (unless (derived-mode-p 'org-mode)
24906 (user-error "Cannot restrict to non-Org mode file"))
24907 (org-agenda-set-restriction-lock 'file)))
24908 (t (user-error "Don't know how to restrict Org mode agenda")))
24909 (move-overlay org-speedbar-restriction-lock-overlay
24910 (point-at-bol) (point-at-eol))
24911 (setq current-prefix-arg nil)
24912 (org-agenda-maybe-redo)))
24914 (defvar speedbar-file-key-map)
24915 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24916 (eval-after-load "speedbar"
24917 '(progn
24918 (speedbar-add-supported-extension ".org")
24919 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24920 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24921 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24922 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24923 (add-hook 'speedbar-visiting-tag-hook
24924 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24926 ;;; Fixes and Hacks for problems with other packages
24928 (defun org--flyspell-object-check-p (element)
24929 "Non-nil when Flyspell can check object at point.
24930 ELEMENT is the element at point."
24931 (let ((object (save-excursion
24932 (when (looking-at-p "\\>") (backward-char))
24933 (org-element-context element))))
24934 (cl-case (org-element-type object)
24935 ;; Prevent checks in links due to keybinding conflict with
24936 ;; Flyspell.
24937 ((code entity export-snippet inline-babel-call
24938 inline-src-block line-break latex-fragment link macro
24939 statistics-cookie target timestamp verbatim)
24940 nil)
24941 (footnote-reference
24942 ;; Only in inline footnotes, within the definition.
24943 (and (eq (org-element-property :type object) 'inline)
24944 (< (save-excursion
24945 (goto-char (org-element-property :begin object))
24946 (search-forward ":" nil t 2))
24947 (point))))
24948 (otherwise t))))
24950 (defun org-mode-flyspell-verify ()
24951 "Function used for `flyspell-generic-check-word-predicate'."
24952 (if (org-at-heading-p)
24953 ;; At a headline or an inlinetask, check title only. This is
24954 ;; faster than relying on `org-element-at-point'.
24955 (and (save-excursion (beginning-of-line)
24956 (and (let ((case-fold-search t))
24957 (not (looking-at "\\*+ END[ \t]*$")))
24958 (looking-at org-complex-heading-regexp)))
24959 (match-beginning 4)
24960 (>= (point) (match-beginning 4))
24961 (or (not (match-beginning 5))
24962 (< (point) (match-beginning 5))))
24963 (let* ((element (org-element-at-point))
24964 (post-affiliated (org-element-property :post-affiliated element)))
24965 (cond
24966 ;; Ignore checks in all affiliated keywords but captions.
24967 ((< (point) post-affiliated)
24968 (and (save-excursion
24969 (beginning-of-line)
24970 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24971 (> (point) (match-end 0))
24972 (org--flyspell-object-check-p element)))
24973 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24974 ((let ((log (org-log-into-drawer)))
24975 (and log
24976 (let ((drawer (org-element-lineage element '(drawer))))
24977 (and drawer
24978 (eq (compare-strings
24979 log nil nil
24980 (org-element-property :drawer-name drawer) nil nil t)
24981 t)))))
24982 nil)
24984 (cl-case (org-element-type element)
24985 ((comment quote-section) t)
24986 (comment-block
24987 ;; Allow checks between block markers, not on them.
24988 (and (> (line-beginning-position) post-affiliated)
24989 (save-excursion
24990 (end-of-line)
24991 (skip-chars-forward " \r\t\n")
24992 (< (point) (org-element-property :end element)))))
24993 ;; Arbitrary list of keywords where checks are meaningful.
24994 ;; Make sure point is on the value part of the element.
24995 (keyword
24996 (and (member (org-element-property :key element)
24997 '("DESCRIPTION" "TITLE"))
24998 (save-excursion
24999 (search-backward ":" (line-beginning-position) t))))
25000 ;; Check is globally allowed in paragraphs verse blocks and
25001 ;; table rows (after affiliated keywords) but some objects
25002 ;; must not be affected.
25003 ((paragraph table-row verse-block)
25004 (let ((cbeg (org-element-property :contents-begin element))
25005 (cend (org-element-property :contents-end element)))
25006 (and cbeg (>= (point) cbeg) (< (point) cend)
25007 (org--flyspell-object-check-p element))))))))))
25008 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25010 (defun org-remove-flyspell-overlays-in (beg end)
25011 "Remove flyspell overlays in region."
25012 (and (bound-and-true-p flyspell-mode)
25013 (fboundp 'flyspell-delete-region-overlays)
25014 (flyspell-delete-region-overlays beg end)))
25016 (defvar flyspell-delayed-commands)
25017 (eval-after-load "flyspell"
25018 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25020 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25021 (eval-after-load "bookmark"
25022 '(if (boundp 'bookmark-after-jump-hook)
25023 ;; We can use the hook
25024 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25025 ;; Hook not available, use advice
25026 (defadvice bookmark-jump (after org-make-visible activate)
25027 "Make the position visible."
25028 (org-bookmark-jump-unhide))))
25030 ;; Make sure saveplace shows the location if it was hidden
25031 (eval-after-load "saveplace"
25032 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25033 "Make the position visible."
25034 (org-bookmark-jump-unhide)))
25036 ;; Make sure ecb shows the location if it was hidden
25037 (eval-after-load "ecb"
25038 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25039 "Make hierarchy visible when jumping into location from ECB tree buffer."
25040 (when (derived-mode-p 'org-mode)
25041 (org-show-context))))
25043 (defun org-bookmark-jump-unhide ()
25044 "Unhide the current position, to show the bookmark location."
25045 (and (derived-mode-p 'org-mode)
25046 (or (outline-invisible-p)
25047 (save-excursion (goto-char (max (point-min) (1- (point))))
25048 (outline-invisible-p)))
25049 (org-show-context 'bookmark-jump)))
25051 (defun org-mark-jump-unhide ()
25052 "Make the point visible with `org-show-context' after jumping to the mark."
25053 (when (and (derived-mode-p 'org-mode)
25054 (outline-invisible-p))
25055 (org-show-context 'mark-goto)))
25057 (eval-after-load "simple"
25058 '(defadvice pop-to-mark-command (after org-make-visible activate)
25059 "Make the point visible with `org-show-context'."
25060 (org-mark-jump-unhide)))
25062 (eval-after-load "simple"
25063 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25064 "Make the point visible with `org-show-context'."
25065 (org-mark-jump-unhide)))
25067 (eval-after-load "simple"
25068 '(defadvice pop-global-mark (after org-make-visible activate)
25069 "Make the point visible with `org-show-context'."
25070 (org-mark-jump-unhide)))
25072 ;; Make session.el ignore our circular variable
25073 (defvar session-globals-exclude)
25074 (eval-after-load "session"
25075 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25077 ;;;; Finish up
25079 (provide 'org)
25081 (run-hooks 'org-load-hook)
25083 ;;; org.el ends here