Use `string-match-p' instead of `org-string-match-p'
[org-mode.git] / lisp / org.el
blobe183053fe8554d06013fcd33fbeffe59fea750b8
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-mode 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 contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the doc/ directory.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda"
118 (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-edit-field "org-table" (arg))
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function org-table-next-row "org-table" ())
166 (declare-function org-table-paste-rectangle "org-table" ())
167 (declare-function org-table-wrap-region "org-table" (arg))
168 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
169 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
170 (declare-function orgtbl-mode "org-table" (&optional arg))
172 (defsubst org-uniquify (list)
173 "Non-destructively remove duplicate elements from LIST."
174 (let ((res (copy-sequence list))) (delete-dups res)))
176 (defsubst org-get-at-bol (property)
177 "Get text property PROPERTY at the beginning of line."
178 (get-text-property (point-at-bol) property))
180 (defsubst org-trim (s &optional keep-lead)
181 "Remove whitespace at the beginning and the end of string S.
182 When optional argument KEEP-LEAD is non-nil, removing blank lines
183 at the beginning of the string does not affect leading indentation."
184 (replace-regexp-in-string
185 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
186 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org-mode FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the org-mode file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org-mode buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Emacs Lisp" emacs-lisp)
261 (const :tag "Forth" forth)
262 (const :tag "Fortran" fortran)
263 (const :tag "Gnuplot" gnuplot)
264 (const :tag "Haskell" haskell)
265 (const :tag "IO" io)
266 (const :tag "J" J)
267 (const :tag "Java" java)
268 (const :tag "Javascript" js)
269 (const :tag "LaTeX" latex)
270 (const :tag "Ledger" ledger)
271 (const :tag "Lilypond" lilypond)
272 (const :tag "Lisp" lisp)
273 (const :tag "Makefile" makefile)
274 (const :tag "Maxima" maxima)
275 (const :tag "Matlab" matlab)
276 (const :tag "Mscgen" mscgen)
277 (const :tag "Ocaml" ocaml)
278 (const :tag "Octave" octave)
279 (const :tag "Org" org)
280 (const :tag "Perl" perl)
281 (const :tag "Pico Lisp" picolisp)
282 (const :tag "PlantUML" plantuml)
283 (const :tag "Python" python)
284 (const :tag "Ruby" ruby)
285 (const :tag "Sass" sass)
286 (const :tag "Scala" scala)
287 (const :tag "Scheme" scheme)
288 (const :tag "Screen" screen)
289 (const :tag "Shell Script" shell)
290 (const :tag "Shen" shen)
291 (const :tag "Sql" sql)
292 (const :tag "Sqlite" sqlite)
293 (const :tag "Stan" stan)
294 (const :tag "ebnf2ps" ebnf2ps))
295 :value-type (boolean :tag "Activate" :value t)))
297 ;;;; Customization variables
298 (defcustom org-clone-delete-id nil
299 "Remove ID property of clones of a subtree.
300 When non-nil, clones of a subtree don't inherit the ID property.
301 Otherwise they inherit the ID property with a new unique
302 identifier."
303 :type 'boolean
304 :version "24.1"
305 :group 'org-id)
307 ;;; Version
308 (org-check-version)
310 ;;;###autoload
311 (defun org-version (&optional here full message)
312 "Show the org-mode version.
313 Interactively, or when MESSAGE is non-nil, show it in echo area.
314 With prefix argument, or when HERE is non-nil, insert it at point.
315 In non-interactive uses, a reduced version string is output unless
316 FULL is given."
317 (interactive (list current-prefix-arg t (not current-prefix-arg)))
318 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
319 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
320 (load-suffixes (list ".el"))
321 (org-install-dir
322 (ignore-errors (org-find-library-dir "org-loaddefs"))))
323 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
324 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
325 (let* ((load-suffixes save-load-suffixes)
326 (release (org-release))
327 (git-version (org-git-version))
328 (version (format "Org-mode version %s (%s @ %s)"
329 release
330 git-version
331 (if org-install-dir
332 (if (string= org-dir org-install-dir)
333 org-install-dir
334 (concat "mixed installation! "
335 org-install-dir
336 " and "
337 org-dir))
338 "org-loaddefs.el can not be found!")))
339 (version1 (if full version release)))
340 (when here (insert version1))
341 (when message (message "%s" version1))
342 version1)))
344 (defconst org-version (org-version))
347 ;;; Syntax Constants
349 ;;;; Block
351 (defconst org-block-regexp
352 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
353 "Regular expression for hiding blocks.")
355 (defconst org-dblock-start-re
356 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
357 "Matches the start line of a dynamic block, with parameters.")
359 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
360 "Matches the end of a dynamic block.")
362 ;;;; Clock and Planning
364 (defconst org-clock-string "CLOCK:"
365 "String used as prefix for timestamps clocking work hours on an item.")
367 (defvar org-closed-string "CLOSED:"
368 "String used as the prefix for timestamps logging closing a TODO entry.")
370 (defvar org-deadline-string "DEADLINE:"
371 "String to mark deadline entries.
372 A deadline is this string, followed by a time stamp. Should be a word,
373 terminated by a colon. You can insert a schedule keyword and
374 a timestamp with \\[org-deadline].")
376 (defvar org-scheduled-string "SCHEDULED:"
377 "String to mark scheduled TODO entries.
378 A schedule is this string, followed by a time stamp. Should be a word,
379 terminated by a colon. You can insert a schedule keyword and
380 a timestamp with \\[org-schedule].")
382 (defconst org-ds-keyword-length
383 (+ 2
384 (apply #'max
385 (mapcar #'length
386 (list org-deadline-string org-scheduled-string
387 org-clock-string org-closed-string))))
388 "Maximum length of the DEADLINE and SCHEDULED keywords.")
390 (defconst org-planning-line-re
391 (concat "^[ \t]*"
392 (regexp-opt
393 (list org-closed-string org-deadline-string org-scheduled-string)
395 "Matches a line with planning info.
396 Matched keyword is in group 1.")
398 (defconst org-clock-line-re
399 (concat "^[ \t]*" org-clock-string)
400 "Matches a line with clock info.")
402 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
403 "Matches the DEADLINE keyword.")
405 (defconst org-deadline-time-regexp
406 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
407 "Matches the DEADLINE keyword together with a time stamp.")
409 (defconst org-deadline-time-hour-regexp
410 (concat "\\<" org-deadline-string
411 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
412 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
414 (defconst org-deadline-line-regexp
415 (concat "\\<\\(" org-deadline-string "\\).*")
416 "Matches the DEADLINE keyword and the rest of the line.")
418 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
419 "Matches the SCHEDULED keyword.")
421 (defconst org-scheduled-time-regexp
422 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
423 "Matches the SCHEDULED keyword together with a time stamp.")
425 (defconst org-scheduled-time-hour-regexp
426 (concat "\\<" org-scheduled-string
427 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
428 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
430 (defconst org-closed-time-regexp
431 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
432 "Matches the CLOSED keyword together with a time stamp.")
434 (defconst org-keyword-time-regexp
435 (concat "\\<"
436 (regexp-opt
437 (list org-scheduled-string org-deadline-string org-closed-string
438 org-clock-string)
440 " *[[<]\\([^]>]+\\)[]>]")
441 "Matches any of the 4 keywords, together with the time stamp.")
443 (defconst org-keyword-time-not-clock-regexp
444 (concat
445 "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string) t)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 3 keywords, together with the time stamp.")
451 (defconst org-maybe-keyword-time-regexp
452 (concat "\\(\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 "\\)?"
458 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
459 "\\|"
460 "<%%([^\r\n>]*>\\)")
461 "Matches a timestamp, possibly preceded by a keyword.")
463 (defconst org-all-time-keywords
464 (mapcar (lambda (w) (substring w 0 -1))
465 (list org-scheduled-string org-deadline-string
466 org-clock-string org-closed-string))
467 "List of time keywords.")
469 ;;;; Drawer
471 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
472 "Matches first or last line of a hidden block.
473 Group 1 contains drawer's name or \"END\".")
475 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
476 "Regular expression matching the first line of a property drawer.")
478 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
479 "Regular expression matching the last line of a property drawer.")
481 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
482 "Regular expression matching the first line of a clock drawer.")
484 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a clock drawer.")
487 (defconst org-property-drawer-re
488 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
489 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
490 "[ \t]*:END:[ \t]*$")
491 "Matches an entire property drawer.")
493 (defconst org-clock-drawer-re
494 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
495 org-clock-drawer-end-re "\\)\n?")
496 "Matches an entire clock drawer.")
498 ;;;; Headline
500 (defconst org-heading-keyword-regexp-format
501 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
502 "Printf format for a regexp matching a headline with some keyword.
503 This regexp will match the headline of any node which has the
504 exact keyword that is put into the format. The keyword isn't in
505 any group by default, but the stars and the body are.")
507 (defconst org-heading-keyword-maybe-regexp-format
508 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
509 "Printf format for a regexp matching a headline, possibly with some keyword.
510 This regexp can match any headline with the specified keyword, or
511 without a keyword. The keyword isn't in any group by default,
512 but the stars and the body are.")
514 (defconst org-archive-tag "ARCHIVE"
515 "The tag that marks a subtree as archived.
516 An archived subtree does not open during visibility cycling, and does
517 not contribute to the agenda listings.")
519 (defconst org-comment-string "COMMENT"
520 "Entries starting with this keyword will never be exported.
521 An entry can be toggled between COMMENT and normal with
522 \\[org-toggle-comment].")
525 ;;;; LaTeX Environments and Fragments
527 (defconst org-latex-regexps
528 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
529 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
530 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
531 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
532 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
533 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
534 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
535 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
536 "Regular expressions for matching embedded LaTeX.")
538 ;;;; Node Property
540 (defconst org-effort-property "Effort"
541 "The property that is being used to keep track of effort estimates.
542 Effort estimates given in this property need to have the format H:MM.")
544 ;;;; Table
546 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
547 "Detect an org-type or table-type table.")
549 (defconst org-table-line-regexp "^[ \t]*|"
550 "Detect an org-type table line.")
552 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
553 "Detect an org-type table line.")
555 (defconst org-table-hline-regexp "^[ \t]*|-"
556 "Detect an org-type table hline.")
558 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
559 "Detect a table-type table hline.")
561 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
562 "Detect the first line outside a table when searching from within it.
563 This works for both table types.")
565 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
566 "Detect a #+TBLFM line.")
568 ;;;; Timestamp
570 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
571 "Regular expression for fast time stamp matching.")
573 (defconst org-ts-regexp-inactive
574 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
575 "Regular expression for fast inactive time stamp matching.")
577 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp0
581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
582 "Regular expression matching time strings for analysis.
583 This one does not require the space after the date, so it can be used
584 on a string that terminates immediately after the date.")
586 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.")
589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
590 "Regular expression matching time stamps, with groups.")
592 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
593 "Regular expression matching time stamps (also [..]), with groups.")
595 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
596 "Regular expression matching a time stamp range.")
598 (defconst org-tr-regexp-both
599 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
600 "Regular expression matching a time stamp range.")
602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
603 org-ts-regexp "\\)?")
604 "Regular expression matching a time stamp or time stamp range.")
606 (defconst org-tsr-regexp-both
607 (concat org-ts-regexp-both "\\(--?-?"
608 org-ts-regexp-both "\\)?")
609 "Regular expression matching a time stamp or time stamp range.
610 The time stamps may be either active or inactive.")
612 (defconst org-repeat-re
613 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
614 "Regular expression for specifying repeated events.
615 After a match, group 1 contains the repeat expression.")
617 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
618 "Formats for `format-time-string' which are used for time stamps.")
621 ;;; The custom variables
623 (defgroup org nil
624 "Outline-based notes management and organizer."
625 :tag "Org"
626 :group 'outlines
627 :group 'calendar)
629 (defcustom org-mode-hook nil
630 "Mode hook for Org-mode, run after the mode was turned on."
631 :group 'org
632 :type 'hook)
634 (defcustom org-load-hook nil
635 "Hook that is run after org.el has been loaded."
636 :group 'org
637 :type 'hook)
639 (defcustom org-log-buffer-setup-hook nil
640 "Hook that is run after an Org log buffer is created."
641 :group 'org
642 :version "24.1"
643 :type 'hook)
645 (defvar org-modules) ; defined below
646 (defvar org-modules-loaded nil
647 "Have the modules been loaded already?")
649 (defun org-load-modules-maybe (&optional force)
650 "Load all extensions listed in `org-modules'."
651 (when (or force (not org-modules-loaded))
652 (dolist (ext org-modules)
653 (condition-case nil (require ext)
654 (error (message "Problems while trying to load feature `%s'" ext))))
655 (setq org-modules-loaded t)))
657 (defun org-set-modules (var value)
658 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
659 (set var value)
660 (when (featurep 'org)
661 (org-load-modules-maybe 'force)
662 (org-element-cache-reset 'all)))
664 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
665 "Modules that should always be loaded together with org.el.
667 If a description starts with <C>, the file is not part of Emacs
668 and loading it will require that you have downloaded and properly
669 installed the Org mode distribution.
671 You can also use this system to load external packages (i.e. neither Org
672 core modules, nor modules from the CONTRIB directory). Just add symbols
673 to the end of the list. If the package is called org-xyz.el, then you need
674 to add the symbol `xyz', and the package must have a call to:
676 (provide \\='org-xyz)
678 For export specific modules, see also `org-export-backends'."
679 :group 'org
680 :set 'org-set-modules
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type
684 '(set :greedy t
685 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
686 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
687 (const :tag " crypt: Encryption of subtrees" org-crypt)
688 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
689 (const :tag " docview: Links to doc-view buffers" org-docview)
690 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
691 (const :tag " habit: Track your consistency with habits" org-habit)
692 (const :tag " id: Global IDs for identifying entries" org-id)
693 (const :tag " info: Links to Info nodes" org-info)
694 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
695 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
696 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
697 (const :tag " mouse: Additional mouse support" org-mouse)
698 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
699 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
700 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
702 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
703 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
704 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
705 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
706 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
707 (const :tag "C collector: Collect properties into tables" org-collector)
708 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
709 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
710 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
711 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
712 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
713 (const :tag "C eval: Include command output as text" org-eval)
714 (const :tag "C eww: Store link to url of eww" org-eww)
715 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
716 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
717 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
718 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
719 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
720 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
721 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
722 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
723 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
724 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
725 (const :tag "C mew: Links to Mew folders/messages" org-mew)
726 (const :tag "C mtags: Support for muse-like tags" org-mtags)
727 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
728 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
729 (const :tag "C registry: A registry for Org-mode links" org-registry)
730 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
731 (const :tag "C secretary: Team management with org-mode" org-secretary)
732 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
733 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
734 (const :tag "C track: Keep up with Org-mode development" org-track)
735 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
736 (const :tag "C vm: Links to VM folders/messages" org-vm)
737 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
738 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
739 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
741 (defvar org-export-registered-backends) ; From ox.el.
742 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
743 (declare-function org-export-backend-name "ox" (backend) t)
744 (defcustom org-export-backends '(ascii html icalendar latex odt)
745 "List of export back-ends that should be always available.
747 If a description starts with <C>, the file is not part of Emacs
748 and loading it will require that you have downloaded and properly
749 installed the Org mode distribution.
751 Unlike to `org-modules', libraries in this list will not be
752 loaded along with Org, but only once the export framework is
753 needed.
755 This variable needs to be set before org.el is loaded. If you
756 need to make a change while Emacs is running, use the customize
757 interface or run the following code, where VAL stands for the new
758 value of the variable, after updating it:
760 (progn
761 (setq org-export-registered-backends
762 (cl-remove-if-not
763 (lambda (backend)
764 (let ((name (org-export-backend-name backend)))
765 (or (memq name val)
766 (catch \\='parentp
767 (dolist (b val)
768 (and (org-export-derived-backend-p b name)
769 (throw \\='parentp t)))))))
770 org-export-registered-backends))
771 (let ((new-list (mapcar #\\='org-export-backend-name
772 org-export-registered-backends)))
773 (dolist (backend val)
774 (cond
775 ((not (load (format \"ox-%s\" backend) t t))
776 (message \"Problems while trying to load export back-end \\=`%s\\='\"
777 backend))
778 ((not (memq backend new-list)) (push backend new-list))))
779 (set-default \\='org-export-backends new-list)))
781 Adding a back-end to this list will also pull the back-end it
782 depends on, if any."
783 :group 'org
784 :group 'org-export
785 :version "25.1"
786 :package-version '(Org . "9.0")
787 :initialize 'custom-initialize-set
788 :set (lambda (var val)
789 (if (not (featurep 'ox)) (set-default var val)
790 ;; Any back-end not required anymore (not present in VAL and not
791 ;; a parent of any back-end in the new value) is removed from the
792 ;; list of registered back-ends.
793 (setq org-export-registered-backends
794 (cl-remove-if-not
795 (lambda (backend)
796 (let ((name (org-export-backend-name backend)))
797 (or (memq name val)
798 (catch 'parentp
799 (dolist (b val)
800 (and (org-export-derived-backend-p b name)
801 (throw 'parentp t)))))))
802 org-export-registered-backends))
803 ;; Now build NEW-LIST of both new back-ends and required
804 ;; parents.
805 (let ((new-list (mapcar #'org-export-backend-name
806 org-export-registered-backends)))
807 (dolist (backend val)
808 (cond
809 ((not (load (format "ox-%s" backend) t t))
810 (message "Problems while trying to load export back-end `%s'"
811 backend))
812 ((not (memq backend new-list)) (push backend new-list))))
813 ;; Set VAR to that list with fixed dependencies.
814 (set-default var new-list))))
815 :type '(set :greedy t
816 (const :tag " ascii Export buffer to ASCII format" ascii)
817 (const :tag " beamer Export buffer to Beamer presentation" beamer)
818 (const :tag " html Export buffer to HTML format" html)
819 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
820 (const :tag " latex Export buffer to LaTeX format" latex)
821 (const :tag " man Export buffer to MAN format" man)
822 (const :tag " md Export buffer to Markdown format" md)
823 (const :tag " odt Export buffer to ODT format" odt)
824 (const :tag " org Export buffer to Org format" org)
825 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
826 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
827 (const :tag "C deck Export buffer to deck.js presentations" deck)
828 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
829 (const :tag "C groff Export buffer to Groff format" groff)
830 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
831 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
832 (const :tag "C s5 Export buffer to s5 presentations" s5)
833 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
835 (eval-after-load 'ox
836 '(dolist (backend org-export-backends)
837 (condition-case nil (require (intern (format "ox-%s" backend)))
838 (error (message "Problems while trying to load export back-end `%s'"
839 backend)))))
841 (defcustom org-support-shift-select nil
842 "Non-nil means make shift-cursor commands select text when possible.
843 \\<org-mode-map>\
845 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
846 start selecting a region, or enlarge regions started in this way.
847 In Org-mode, in special contexts, these same keys are used for
848 other purposes, important enough to compete with shift selection.
849 Org tries to balance these needs by supporting `shift-select-mode'
850 outside these special contexts, under control of this variable.
852 The default of this variable is nil, to avoid confusing behavior. Shifted
853 cursor keys will then execute Org commands in the following contexts:
854 - on a headline, changing TODO state (left/right) and priority (up/down)
855 - on a time stamp, changing the time
856 - in a plain list item, changing the bullet type
857 - in a property definition line, switching between allowed values
858 - in the BEGIN line of a clock table (changing the time block).
859 Outside these contexts, the commands will throw an error.
861 When this variable is t and the cursor is not in a special
862 context, Org-mode will support shift-selection for making and
863 enlarging regions. To make this more effective, the bullet
864 cycling will no longer happen anywhere in an item line, but only
865 if the cursor is exactly on the bullet.
867 If you set this variable to the symbol `always', then the keys
868 will not be special in headlines, property lines, and item lines,
869 to make shift selection work there as well. If this is what you
870 want, you can use the following alternative commands:
871 `\\[org-todo]' and `\\[org-priority]' \
872 to change TODO state and priority,
873 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
874 can be used to switch TODO sets,
875 `\\[org-ctrl-c-minus]' to cycle item bullet types,
876 and properties can be edited by hand or in column view.
878 However, when the cursor is on a timestamp, shift-cursor commands
879 will still edit the time stamp - this is just too good to give up."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped.
942 The variable `org-startup-truncated' allows to configure
943 truncation for Org mode different to the other modes that use the
944 variable `truncate-lines' and as a shortcut instead of putting
945 the variable `truncate-lines' into the `org-mode-hook'. If one
946 wants to configure truncation for Org mode not statically but
947 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
948 the variable `truncate-lines' has to be used because in such a
949 case it is too late to set the variable `org-startup-truncated'."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
958 #+STARTUP: indent
959 #+STARTUP: noindent"
960 :group 'org-structure
961 :type '(choice
962 (const :tag "Not" nil)
963 (const :tag "Globally (slow on startup in large files)" t)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
990 :group 'org-startup
991 :version "24.4"
992 :package-version '(Org . "8.0")
993 :type '(choice
994 (const :tag "Always interpret" t)
995 (const :tag "Only with braces" {})
996 (const :tag "Never interpret" nil)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1003 #+STARTUP: beamer"
1004 :group 'org-startup
1005 :version "24.1"
1006 :type 'boolean)
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This is useful when the column width in tables is forced with <N> cookies
1011 in table fields. Such tables will look correct only after the first re-align.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-with-inline-images nil
1020 "Non-nil means show inline images when loading a new Org file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: inlineimages
1024 #+STARTUP: noinlineimages"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-with-latex-preview nil
1030 "Non-nil means preview LaTeX fragments when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: latexpreview
1035 #+STARTUP: nolatexpreview"
1036 :group 'org-startup
1037 :version "24.4"
1038 :package-version '(Org . "8.0")
1039 :type 'boolean)
1041 (defcustom org-insert-mode-line-in-empty-file nil
1042 "Non-nil means insert the first line setting Org-mode in empty files.
1043 When the function `org-mode' is called interactively in an empty file, this
1044 normally means that the file name does not automatically trigger Org-mode.
1045 To ensure that the file will always be in Org-mode in the future, a
1046 line enforcing Org-mode will be inserted into the buffer, if this option
1047 has been set."
1048 :group 'org-startup
1049 :type 'boolean)
1051 (defcustom org-replace-disputed-keys nil
1052 "Non-nil means use alternative key bindings for some keys.
1053 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1054 These keys are also used by other packages like shift-selection-mode'
1055 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1056 If you want to use Org-mode together with one of these other modes,
1057 or more generally if you would like to move some Org-mode commands to
1058 other keys, set this variable and configure the keys with the variable
1059 `org-disputed-keys'.
1061 This option is only relevant at load-time of Org-mode, and must be set
1062 *before* org.el is loaded. Changing it requires a restart of Emacs to
1063 become effective."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-use-extra-keys nil
1068 "Non-nil means use extra key sequence definitions for certain commands.
1069 This happens automatically if `window-system' is nil. This
1070 variable lets you do the same manually. You must set it before
1071 loading Org."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1077 (defcustom org-disputed-keys
1078 '(([(shift up)] . [(meta p)])
1079 ([(shift down)] . [(meta n)])
1080 ([(shift left)] . [(meta -)])
1081 ([(shift right)] . [(meta +)])
1082 ([(control shift right)] . [(meta shift +)])
1083 ([(control shift left)] . [(meta shift -)]))
1084 "Keys for which Org-mode and other modes compete.
1085 This is an alist, cars are the default keys, second element specifies
1086 the alternative to use when `org-replace-disputed-keys' is t.
1088 Keys can be specified in any syntax supported by `define-key'.
1089 The value of this option takes effect only at Org-mode's startup,
1090 therefore you'll have to restart Emacs to apply it after changing."
1091 :group 'org-startup
1092 :type 'alist)
1094 (defun org-key (key)
1095 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1096 Or return the original if not disputed."
1097 (when org-replace-disputed-keys
1098 (let* ((nkey (key-description key))
1099 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1100 org-disputed-keys)))
1101 (setq key (if x (cdr x) key))))
1102 key)
1104 (defun org-defkey (keymap key def)
1105 "Define a key, possibly translated, as returned by `org-key'."
1106 (define-key keymap (org-key key) def))
1108 (defcustom org-ellipsis nil
1109 "The ellipsis to use in the Org-mode outline.
1110 When nil, just use the standard three dots.
1111 When a string, use that string instead.
1112 When a face, use the standard 3 dots, but with the specified face.
1113 The change affects only Org-mode (which will then use its own display table).
1114 Changing this requires executing \\[org-mode] in a buffer to become
1115 effective."
1116 :group 'org-startup
1117 :type '(choice (const :tag "Default" nil)
1118 (face :tag "Face" :value org-warning)
1119 (string :tag "String" :value "...#")))
1121 (defvar org-display-table nil
1122 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1124 (defgroup org-keywords nil
1125 "Keywords in Org-mode."
1126 :tag "Org Keywords"
1127 :group 'org)
1129 (defcustom org-closed-keep-when-no-todo nil
1130 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1131 :group 'org-todo
1132 :group 'org-keywords
1133 :version "24.4"
1134 :package-version '(Org . "8.0")
1135 :type 'boolean)
1137 (defgroup org-structure nil
1138 "Options concerning the general structure of Org-mode files."
1139 :tag "Org Structure"
1140 :group 'org)
1142 (defgroup org-reveal-location nil
1143 "Options about how to make context of a location visible."
1144 :tag "Org Reveal Location"
1145 :group 'org-structure)
1147 (defcustom org-show-context-detail '((agenda . local)
1148 (bookmark-jump . lineage)
1149 (isearch . lineage)
1150 (default . ancestors))
1151 "Alist between context and visibility span when revealing a location.
1153 \\<org-mode-map>Some actions may move point into invisible
1154 locations. As a consequence, Org always expose a neighborhood
1155 around point. How much is shown depends on the initial action,
1156 or context. Valid contexts are
1158 agenda when exposing an entry from the agenda
1159 org-goto when using the command `org-goto' (\\[org-goto])
1160 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1161 tags-tree when constructing a sparse tree based on tags matches
1162 link-search when exposing search matches associated with a link
1163 mark-goto when exposing the jump goal of a mark
1164 bookmark-jump when exposing a bookmark location
1165 isearch when exiting from an incremental search
1166 default default for all contexts not set explicitly
1168 Allowed visibility spans are
1170 minimal show current headline; if point is not on headline,
1171 also show entry
1173 local show current headline, entry and next headline
1175 ancestors show current headline and its direct ancestors; if
1176 point is not on headline, also show entry
1178 lineage show current headline, its direct ancestors and all
1179 their children; if point is not on headline, also show
1180 entry and first child
1182 tree show current headline, its direct ancestors and all
1183 their children; if point is not on headline, also show
1184 entry and all children
1186 canonical show current headline, its direct ancestors along with
1187 their entries and children; if point is not located on
1188 the headline, also show current entry and all children
1190 As special cases, a nil or t value means show all contexts in
1191 `minimal' or `canonical' view, respectively.
1193 Some views can make displayed information very compact, but also
1194 make it harder to edit the location of the match. In such
1195 a case, use the command `org-reveal' (\\[org-reveal]) to show
1196 more context."
1197 :group 'org-reveal-location
1198 :version "25.2"
1199 :package-version '(Org . "9.0")
1200 :type '(choice
1201 (const :tag "Canonical" t)
1202 (const :tag "Minimal" nil)
1203 (repeat :greedy t :tag "Individual contexts"
1204 (cons
1205 (choice :tag "Context"
1206 (const agenda)
1207 (const org-goto)
1208 (const occur-tree)
1209 (const tags-tree)
1210 (const link-search)
1211 (const mark-goto)
1212 (const bookmark-jump)
1213 (const isearch)
1214 (const default))
1215 (choice :tag "Detail level"
1216 (const minimal)
1217 (const local)
1218 (const ancestors)
1219 (const lineage)
1220 (const tree)
1221 (const canonical))))))
1223 (defcustom org-indirect-buffer-display 'other-window
1224 "How should indirect tree buffers be displayed?
1225 This applies to indirect buffers created with the commands
1226 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1227 Valid values are:
1228 current-window Display in the current window
1229 other-window Just display in another window.
1230 dedicated-frame Create one new frame, and re-use it each time.
1231 new-frame Make a new frame each time. Note that in this case
1232 previously-made indirect buffers are kept, and you need to
1233 kill these buffers yourself."
1234 :group 'org-structure
1235 :group 'org-agenda-windows
1236 :type '(choice
1237 (const :tag "In current window" current-window)
1238 (const :tag "In current frame, other window" other-window)
1239 (const :tag "Each time a new frame" new-frame)
1240 (const :tag "One dedicated frame" dedicated-frame)))
1242 (defcustom org-use-speed-commands nil
1243 "Non-nil means activate single letter commands at beginning of a headline.
1244 This may also be a function to test for appropriate locations where speed
1245 commands should be active.
1247 For example, to activate speed commands when the point is on any
1248 star at the beginning of the headline, you can do this:
1250 (setq org-use-speed-commands
1251 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1252 :group 'org-structure
1253 :type '(choice
1254 (const :tag "Never" nil)
1255 (const :tag "At beginning of headline stars" t)
1256 (function)))
1258 (defcustom org-speed-commands-user nil
1259 "Alist of additional speed commands.
1260 This list will be checked before `org-speed-commands-default'
1261 when the variable `org-use-speed-commands' is non-nil
1262 and when the cursor is at the beginning of a headline.
1263 The car if each entry is a string with a single letter, which must
1264 be assigned to `self-insert-command' in the global map.
1265 The cdr is either a command to be called interactively, a function
1266 to be called, or a form to be evaluated.
1267 An entry that is just a list with a single string will be interpreted
1268 as a descriptive headline that will be added when listing the speed
1269 commands in the Help buffer using the `?' speed command."
1270 :group 'org-structure
1271 :type '(repeat :value ("k" . ignore)
1272 (choice :value ("k" . ignore)
1273 (list :tag "Descriptive Headline" (string :tag "Headline"))
1274 (cons :tag "Letter and Command"
1275 (string :tag "Command letter")
1276 (choice
1277 (function)
1278 (sexp))))))
1280 (defcustom org-bookmark-names-plist
1281 '(:last-capture "org-capture-last-stored"
1282 :last-refile "org-refile-last-stored"
1283 :last-capture-marker "org-capture-last-stored-marker")
1284 "Names for bookmarks automatically set by some Org commands.
1285 This can provide strings as names for a number of bookmarks Org sets
1286 automatically. The following keys are currently implemented:
1287 :last-capture
1288 :last-capture-marker
1289 :last-refile
1290 When a key does not show up in the property list, the corresponding bookmark
1291 is not set."
1292 :group 'org-structure
1293 :type 'plist)
1295 (defgroup org-cycle nil
1296 "Options concerning visibility cycling in Org-mode."
1297 :tag "Org Cycle"
1298 :group 'org-structure)
1300 (defcustom org-cycle-skip-children-state-if-no-children t
1301 "Non-nil means skip CHILDREN state in entries that don't have any."
1302 :group 'org-cycle
1303 :type 'boolean)
1305 (defcustom org-cycle-max-level nil
1306 "Maximum level which should still be subject to visibility cycling.
1307 Levels higher than this will, for cycling, be treated as text, not a headline.
1308 When `org-odd-levels-only' is set, a value of N in this variable actually
1309 means 2N-1 stars as the limiting headline.
1310 When nil, cycle all levels.
1311 Note that the limiting level of cycling is also influenced by
1312 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1313 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1314 than its value."
1315 :group 'org-cycle
1316 :type '(choice
1317 (const :tag "No limit" nil)
1318 (integer :tag "Maximum level")))
1320 (defcustom org-hide-block-startup nil
1321 "Non-nil means entering Org-mode will fold all blocks.
1322 This can also be set in on a per-file basis with
1324 #+STARTUP: hideblocks
1325 #+STARTUP: showblocks"
1326 :group 'org-startup
1327 :group 'org-cycle
1328 :type 'boolean)
1330 (defcustom org-cycle-global-at-bob nil
1331 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1332 This makes it possible to do global cycling without having to use S-TAB or
1333 \\[universal-argument] TAB. For this special case to work, the first line
1334 of the buffer must not be a headline -- it may be empty or some other text.
1335 When used in this way, `org-cycle-hook' is disabled temporarily to make
1336 sure the cursor stays at the beginning of the buffer. When this option is
1337 nil, don't do anything special at the beginning of the buffer."
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-level-after-item/entry-creation t
1342 "Non-nil means cycle entry level or item indentation in new empty entries.
1344 When the cursor is at the end of an empty headline, i.e., with only stars
1345 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1346 and then all possible ancestor states, before returning to the original state.
1347 This makes data entry extremely fast: M-RET to create a new headline,
1348 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1350 When the cursor is at the end of an empty plain list item, one TAB will
1351 make it a subitem, two or more tabs will back up to make this an item
1352 higher up in the item hierarchy."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-emulate-tab t
1357 "Where should `org-cycle' emulate TAB.
1358 nil Never
1359 white Only in completely white lines
1360 whitestart Only at the beginning of lines, before the first non-white char
1361 t Everywhere except in headlines
1362 exc-hl-bol Everywhere except at the start of a headline
1363 If TAB is used in a place where it does not emulate TAB, the current subtree
1364 visibility is cycled."
1365 :group 'org-cycle
1366 :type '(choice (const :tag "Never" nil)
1367 (const :tag "Only in completely white lines" white)
1368 (const :tag "Before first char in a line" whitestart)
1369 (const :tag "Everywhere except in headlines" t)
1370 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1372 (defcustom org-cycle-separator-lines 2
1373 "Number of empty lines needed to keep an empty line between collapsed trees.
1374 If you leave an empty line between the end of a subtree and the following
1375 headline, this empty line is hidden when the subtree is folded.
1376 Org-mode will leave (exactly) one empty line visible if the number of
1377 empty lines is equal or larger to the number given in this variable.
1378 So the default 2 means at least 2 empty lines after the end of a subtree
1379 are needed to produce free space between a collapsed subtree and the
1380 following headline.
1382 If the number is negative, and the number of empty lines is at least -N,
1383 all empty lines are shown.
1385 Special case: when 0, never leave empty lines in collapsed view."
1386 :group 'org-cycle
1387 :type 'integer)
1388 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1390 (defcustom org-pre-cycle-hook nil
1391 "Hook that is run before visibility cycling is happening.
1392 The function(s) in this hook must accept a single argument which indicates
1393 the new state that will be set right after running this hook. The
1394 argument is a symbol. Before a global state change, it can have the values
1395 `overview', `content', or `all'. Before a local state change, it can have
1396 the values `folded', `children', or `subtree'."
1397 :group 'org-cycle
1398 :type 'hook)
1400 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1401 org-cycle-hide-drawers
1402 org-cycle-show-empty-lines
1403 org-optimize-window-after-visibility-change)
1404 "Hook that is run after `org-cycle' has changed the buffer visibility.
1405 The function(s) in this hook must accept a single argument which indicates
1406 the new state that was set by the most recent `org-cycle' command. The
1407 argument is a symbol. After a global state change, it can have the values
1408 `overview', `contents', or `all'. After a local state change, it can have
1409 the values `folded', `children', or `subtree'."
1410 :group 'org-cycle
1411 :type 'hook
1412 :version "25.1"
1413 :package-version '(Org . "8.3"))
1415 (defgroup org-edit-structure nil
1416 "Options concerning structure editing in Org-mode."
1417 :tag "Org Edit Structure"
1418 :group 'org-structure)
1420 (defcustom org-odd-levels-only nil
1421 "Non-nil means skip even levels and only use odd levels for the outline.
1422 This has the effect that two stars are being added/taken away in
1423 promotion/demotion commands. It also influences how levels are
1424 handled by the exporters.
1425 Changing it requires restart of `font-lock-mode' to become effective
1426 for fontification also in regions already fontified.
1427 You may also set this on a per-file basis by adding one of the following
1428 lines to the buffer:
1430 #+STARTUP: odd
1431 #+STARTUP: oddeven"
1432 :group 'org-edit-structure
1433 :group 'org-appearance
1434 :type 'boolean)
1436 (defcustom org-adapt-indentation t
1437 "Non-nil means adapt indentation to outline node level.
1439 When this variable is set, Org assumes that you write outlines by
1440 indenting text in each node to align with the headline (after the
1441 stars). The following issues are influenced by this variable:
1443 - The indentation is increased by one space in a demotion
1444 command, and decreased by one in a promotion command. However,
1445 in the latter case, if shifting some line in the entry body
1446 would alter document structure (e.g., insert a new headline),
1447 indentation is not changed at all.
1449 - Property drawers and planning information is inserted indented
1450 when this variable is set. When nil, they will not be indented.
1452 - TAB indents a line relative to current level. The lines below
1453 a headline will be indented when this variable is set.
1455 Note that this is all about true indentation, by adding and
1456 removing space characters. See also `org-indent.el' which does
1457 level-dependent indentation in a virtual way, i.e. at display
1458 time in Emacs."
1459 :group 'org-edit-structure
1460 :type 'boolean)
1462 (defcustom org-special-ctrl-a/e nil
1463 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1465 When t, `C-a' will bring back the cursor to the beginning of the
1466 headline text, i.e. after the stars and after a possible TODO
1467 keyword. In an item, this will be the position after bullet and
1468 check-box, if any. When the cursor is already at that position,
1469 another `C-a' will bring it to the beginning of the line.
1471 `C-e' will jump to the end of the headline, ignoring the presence
1472 of tags in the headline. A second `C-e' will then jump to the
1473 true end of the line, after any tags. This also means that, when
1474 this variable is non-nil, `C-e' also will never jump beyond the
1475 end of the heading of a folded section, i.e. not after the
1476 ellipses.
1478 When set to the symbol `reversed', the first `C-a' or `C-e' works
1479 normally, going to the true line boundary first. Only a directly
1480 following, identical keypress will bring the cursor to the
1481 special positions.
1483 This may also be a cons cell where the behavior for `C-a' and
1484 `C-e' is set separately."
1485 :group 'org-edit-structure
1486 :type '(choice
1487 (const :tag "off" nil)
1488 (const :tag "on: after stars/bullet and before tags first" t)
1489 (const :tag "reversed: true line boundary first" reversed)
1490 (cons :tag "Set C-a and C-e separately"
1491 (choice :tag "Special C-a"
1492 (const :tag "off" nil)
1493 (const :tag "on: after stars/bullet first" t)
1494 (const :tag "reversed: before stars/bullet first" reversed))
1495 (choice :tag "Special C-e"
1496 (const :tag "off" nil)
1497 (const :tag "on: before tags first" t)
1498 (const :tag "reversed: after tags first" reversed)))))
1499 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1501 (defcustom org-special-ctrl-k nil
1502 "Non-nil means `C-k' will behave specially in headlines.
1503 When nil, `C-k' will call the default `kill-line' command.
1504 When t, the following will happen while the cursor is in the headline:
1506 - When the cursor is at the beginning of a headline, kill the entire
1507 line and possible the folded subtree below the line.
1508 - When in the middle of the headline text, kill the headline up to the tags.
1509 - When after the headline text, kill the tags."
1510 :group 'org-edit-structure
1511 :type 'boolean)
1513 (defcustom org-ctrl-k-protect-subtree nil
1514 "Non-nil means, do not delete a hidden subtree with C-k.
1515 When set to the symbol `error', simply throw an error when C-k is
1516 used to kill (part-of) a headline that has hidden text behind it.
1517 Any other non-nil value will result in a query to the user, if it is
1518 OK to kill that hidden subtree. When nil, kill without remorse."
1519 :group 'org-edit-structure
1520 :version "24.1"
1521 :type '(choice
1522 (const :tag "Do not protect hidden subtrees" nil)
1523 (const :tag "Protect hidden subtrees with a security query" t)
1524 (const :tag "Never kill a hidden subtree with C-k" error)))
1526 (defcustom org-special-ctrl-o t
1527 "Non-nil means, make `C-o' insert a row in tables."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-catch-invisible-edits nil
1532 "Check if in invisible region before inserting or deleting a character.
1533 Valid values are:
1535 nil Do not check, so just do invisible edits.
1536 error Throw an error and do nothing.
1537 show Make point visible, and do the requested edit.
1538 show-and-error Make point visible, then throw an error and abort the edit.
1539 smart Make point visible, and do insertion/deletion if it is
1540 adjacent to visible text and the change feels predictable.
1541 Never delete a previously invisible character or add in the
1542 middle or right after an invisible region. Basically, this
1543 allows insertion and backward-delete right before ellipses.
1544 FIXME: maybe in this case we should not even show?"
1545 :group 'org-edit-structure
1546 :version "24.1"
1547 :type '(choice
1548 (const :tag "Do not check" nil)
1549 (const :tag "Throw error when trying to edit" error)
1550 (const :tag "Unhide, but do not do the edit" show-and-error)
1551 (const :tag "Show invisible part and do the edit" show)
1552 (const :tag "Be smart and do the right thing" smart)))
1554 (defcustom org-yank-folded-subtrees t
1555 "Non-nil means when yanking subtrees, fold them.
1556 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1557 it starts with a heading and all other headings in it are either children
1558 or siblings, then fold all the subtrees. However, do this only if no
1559 text after the yank would be swallowed into a folded tree by this action."
1560 :group 'org-edit-structure
1561 :type 'boolean)
1563 (defcustom org-yank-adjusted-subtrees nil
1564 "Non-nil means when yanking subtrees, adjust the level.
1565 With this setting, `org-paste-subtree' is used to insert the subtree, see
1566 this function for details."
1567 :group 'org-edit-structure
1568 :type 'boolean)
1570 (defcustom org-M-RET-may-split-line '((default . t))
1571 "Non-nil means M-RET will split the line at the cursor position.
1572 When nil, it will go to the end of the line before making a
1573 new line.
1574 You may also set this option in a different way for different
1575 contexts. Valid contexts are:
1577 headline when creating a new headline
1578 item when creating a new item
1579 table in a table field
1580 default the value to be used for all contexts not explicitly
1581 customized"
1582 :group 'org-structure
1583 :group 'org-table
1584 :type '(choice
1585 (const :tag "Always" t)
1586 (const :tag "Never" nil)
1587 (repeat :greedy t :tag "Individual contexts"
1588 (cons
1589 (choice :tag "Context"
1590 (const headline)
1591 (const item)
1592 (const table)
1593 (const default))
1594 (boolean)))))
1597 (defcustom org-insert-heading-respect-content nil
1598 "Non-nil means insert new headings after the current subtree.
1599 When nil, the new heading is created directly after the current line.
1600 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1601 this variable on for the duration of the command."
1602 :group 'org-structure
1603 :type 'boolean)
1605 (defcustom org-blank-before-new-entry '((heading . auto)
1606 (plain-list-item . auto))
1607 "Should `org-insert-heading' leave a blank line before new heading/item?
1608 The value is an alist, with `heading' and `plain-list-item' as CAR,
1609 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1610 which case Org will look at the surrounding headings/items and try to
1611 make an intelligent decision whether to insert a blank line or not."
1612 :group 'org-edit-structure
1613 :type '(list
1614 (cons (const heading)
1615 (choice (const :tag "Never" nil)
1616 (const :tag "Always" t)
1617 (const :tag "Auto" auto)))
1618 (cons (const plain-list-item)
1619 (choice (const :tag "Never" nil)
1620 (const :tag "Always" t)
1621 (const :tag "Auto" auto)))))
1623 (defcustom org-insert-heading-hook nil
1624 "Hook being run after inserting a new heading."
1625 :group 'org-edit-structure
1626 :type 'hook)
1628 (defcustom org-enable-fixed-width-editor t
1629 "Non-nil means lines starting with \":\" are treated as fixed-width.
1630 This currently only means they are never auto-wrapped.
1631 When nil, such lines will be treated like ordinary lines."
1632 :group 'org-edit-structure
1633 :type 'boolean)
1635 (defcustom org-goto-auto-isearch t
1636 "Non-nil means typing characters in `org-goto' starts incremental search.
1637 When nil, you can use these keybindings to navigate the buffer:
1639 q Quit the org-goto interface
1640 n Go to the next visible heading
1641 p Go to the previous visible heading
1642 f Go one heading forward on same level
1643 b Go one heading backward on same level
1644 u Go one heading up"
1645 :group 'org-edit-structure
1646 :type 'boolean)
1648 (defgroup org-sparse-trees nil
1649 "Options concerning sparse trees in Org-mode."
1650 :tag "Org Sparse Trees"
1651 :group 'org-structure)
1653 (defcustom org-highlight-sparse-tree-matches t
1654 "Non-nil means highlight all matches that define a sparse tree.
1655 The highlights will automatically disappear the next time the buffer is
1656 changed by an edit command."
1657 :group 'org-sparse-trees
1658 :type 'boolean)
1660 (defcustom org-remove-highlights-with-change t
1661 "Non-nil means any change to the buffer will remove temporary highlights.
1662 \\<org-mode-map>\
1663 Such highlights are created by `org-occur' and `org-clock-display'.
1664 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1665 to get rid of the highlights.
1666 The highlights created by `org-toggle-latex-fragment' always need
1667 `\\[org-toggle-latex-fragment]' to be removed."
1668 :group 'org-sparse-trees
1669 :group 'org-time
1670 :type 'boolean)
1672 (defcustom org-occur-case-fold-search t
1673 "Non-nil means `org-occur' should be case-insensitive.
1674 If set to `smart' the search will be case-insensitive only if it
1675 doesn't specify any upper case character."
1676 :group 'org-sparse-trees
1677 :version "25.1"
1678 :type '(choice
1679 (const :tag "Case-sensitive" nil)
1680 (const :tag "Case-insensitive" t)
1681 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1683 (defcustom org-occur-hook '(org-first-headline-recenter)
1684 "Hook that is run after `org-occur' has constructed a sparse tree.
1685 This can be used to recenter the window to show as much of the structure
1686 as possible."
1687 :group 'org-sparse-trees
1688 :type 'hook)
1690 (defgroup org-imenu-and-speedbar nil
1691 "Options concerning imenu and speedbar in Org-mode."
1692 :tag "Org Imenu and Speedbar"
1693 :group 'org-structure)
1695 (defcustom org-imenu-depth 2
1696 "The maximum level for Imenu access to Org-mode headlines.
1697 This also applied for speedbar access."
1698 :group 'org-imenu-and-speedbar
1699 :type 'integer)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org-mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-enable-table-editor 'optimized
1707 "Non-nil means lines starting with \"|\" are handled by the table editor.
1708 When nil, such lines will be treated like ordinary lines.
1710 When equal to the symbol `optimized', the table editor will be optimized to
1711 do the following:
1712 - Automatic overwrite mode in front of whitespace in table fields.
1713 This makes the structure of the table stay in tact as long as the edited
1714 field does not exceed the column width.
1715 - Minimize the number of realigns. Normally, the table is aligned each time
1716 TAB or RET are pressed to move to another field. With optimization this
1717 happens only if changes to a field might have changed the column width.
1718 Optimization requires replacing the functions `self-insert-command',
1719 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1720 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1721 very good at guessing when a re-align will be necessary, but you can always
1722 force one with \\[org-ctrl-c-ctrl-c].
1724 If you would like to use the optimized version in Org-mode, but the
1725 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1727 This variable can be used to turn on and off the table editor during a session,
1728 but in order to toggle optimization, a restart is required.
1730 See also the variable `org-table-auto-blank-field'."
1731 :group 'org-table
1732 :type '(choice
1733 (const :tag "off" nil)
1734 (const :tag "on" t)
1735 (const :tag "on, optimized" optimized)))
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org-mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-parameters
1762 '(("doi" :follow org--open-doi-link)
1763 ("elisp" :follow org--open-elisp-link)
1764 ("file" :complete org-file-complete-link)
1765 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1766 ("help" :follow org--open-help-link)
1767 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1768 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1769 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1770 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1771 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1772 ("shell" :follow org--open-shell-link))
1773 "An alist of properties that defines all the links in Org mode.
1774 The key in each association is a string of the link type.
1775 Subsequent optional elements make up a p-list of link properties.
1777 :follow - A function that takes the link path as an argument.
1779 :export - A function that takes the link path, description and
1780 export-backend as arguments.
1782 :store - A function responsible for storing the link. See the
1783 function `org-store-link-functions'.
1785 :complete - A function that inserts a link with completion. The
1786 function takes one optional prefix arg.
1788 :face - A face for the link, or a function that returns a face.
1789 The function takes one argument which is the link path. The
1790 default face is `org-link'.
1792 :mouse-face - The mouse-face. The default is `highlight'.
1794 :display - `full' will not fold the link in descriptive
1795 display. Default is `org-link'.
1797 :help-echo - A string or function that takes (window object position)
1798 as arguments and returns a string.
1800 :keymap - A keymap that is active on the link. The default is
1801 `org-mouse-map'.
1803 :htmlize-link - A function for the htmlize-link. Defaults
1804 to (list :uri \"type:path\")
1806 :activate-func - A function to run at the end of font-lock
1807 activation. The function must accept (link-start link-end path bracketp)
1808 as arguments."
1809 :group 'org-link
1810 :type '(alist :tag "Link display parameters"
1811 :value-type plist))
1813 (defun org-link-get-parameter (type key)
1814 "Get TYPE link property for KEY.
1815 TYPE is a string and KEY is a plist keyword."
1816 (plist-get
1817 (cdr (assoc type org-link-parameters))
1818 key))
1820 (defun org-link-set-parameters (type &rest parameters)
1821 "Set link TYPE properties to PARAMETERS.
1822 PARAMETERS should be :key val pairs."
1823 (let ((data (assoc type org-link-parameters)))
1824 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1825 (push (cons type parameters) org-link-parameters)
1826 (org-make-link-regexps)
1827 (org-element-update-syntax))))
1829 (defun org-link-types ()
1830 "Return a list of known link types."
1831 (mapcar #'car org-link-parameters))
1833 (defcustom org-link-abbrev-alist nil
1834 "Alist of link abbreviations.
1835 The car of each element is a string, to be replaced at the start of a link.
1836 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1837 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1839 [[linkkey:tag][description]]
1841 The `linkkey' must be a word word, starting with a letter, followed
1842 by letters, numbers, `-' or `_'.
1844 If REPLACE is a string, the tag will simply be appended to create the link.
1845 If the string contains \"%s\", the tag will be inserted there. If the string
1846 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1847 at that point (see the function `url-hexify-string'). If the string contains
1848 the specifier \"%(my-function)\", then the custom function `my-function' will
1849 be invoked: this function takes the tag as its only argument and must return
1850 a string.
1852 REPLACE may also be a function that will be called with the tag as the
1853 only argument to create the link, which should be returned as a string.
1855 See the manual for examples."
1856 :group 'org-link
1857 :type '(repeat
1858 (cons
1859 (string :tag "Protocol")
1860 (choice
1861 (string :tag "Format")
1862 (function)))))
1864 (defcustom org-descriptive-links t
1865 "Non-nil means Org will display descriptive links.
1866 E.g. [[http://orgmode.org][Org website]] will be displayed as
1867 \"Org Website\", hiding the link itself and just displaying its
1868 description. When set to nil, Org will display the full links
1869 literally.
1871 You can interactively set the value of this variable by calling
1872 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1873 :group 'org-link
1874 :type 'boolean)
1876 (defcustom org-link-file-path-type 'adaptive
1877 "How the path name in file links should be stored.
1878 Valid values are:
1880 relative Relative to the current directory, i.e. the directory of the file
1881 into which the link is being inserted.
1882 absolute Absolute path, if possible with ~ for home directory.
1883 noabbrev Absolute path, no abbreviation of home directory.
1884 adaptive Use relative path for files in the current directory and sub-
1885 directories of it. For other files, use an absolute path."
1886 :group 'org-link
1887 :type '(choice
1888 (const relative)
1889 (const absolute)
1890 (const noabbrev)
1891 (const adaptive)))
1893 (defvaralias 'org-activate-links 'org-highlight-links)
1894 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1895 "Types of links that should be highlighted in Org-mode files.
1897 This is a list of symbols, each one of them leading to the
1898 highlighting of a certain link type.
1900 You can still open links that are not highlighted.
1902 In principle, it does not hurt to turn on highlighting for all
1903 link types. There may be a small gain when turning off unused
1904 link types. The types are:
1906 bracket The recommended [[link][description]] or [[link]] links with hiding.
1907 angle Links in angular brackets that may contain whitespace like
1908 <bbdb:Carsten Dominik>.
1909 plain Plain links in normal text, no whitespace, like http://google.com.
1910 radio Text that is matched by a radio target, see manual for details.
1911 tag Tag settings in a headline (link to tag search).
1912 date Time stamps (link to calendar).
1913 footnote Footnote labels.
1915 If you set this variable during an Emacs session, use `org-mode-restart'
1916 in the Org buffer so that the change takes effect."
1917 :group 'org-link
1918 :group 'org-appearance
1919 :type '(set :greedy t
1920 (const :tag "Double bracket links" bracket)
1921 (const :tag "Angular bracket links" angle)
1922 (const :tag "Plain text links" plain)
1923 (const :tag "Radio target matches" radio)
1924 (const :tag "Tags" tag)
1925 (const :tag "Timestamps" date)
1926 (const :tag "Footnotes" footnote)))
1928 (defcustom org-make-link-description-function nil
1929 "Function to use for generating link descriptions from links.
1930 When nil, the link location will be used. This function must take
1931 two parameters: the first one is the link, the second one is the
1932 description generated by `org-insert-link'. The function should
1933 return the description to use."
1934 :group 'org-link
1935 :type '(choice (const nil) (function)))
1937 (defgroup org-link-store nil
1938 "Options concerning storing links in Org-mode."
1939 :tag "Org Store Link"
1940 :group 'org-link)
1942 (defcustom org-url-hexify-p t
1943 "When non-nil, hexify URL when creating a link."
1944 :type 'boolean
1945 :version "24.3"
1946 :group 'org-link-store)
1948 (defcustom org-email-link-description-format "Email %c: %.30s"
1949 "Format of the description part of a link to an email or usenet message.
1950 The following %-escapes will be replaced by corresponding information:
1952 %F full \"From\" field
1953 %f name, taken from \"From\" field, address if no name
1954 %T full \"To\" field
1955 %t first name in \"To\" field, address if no name
1956 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1957 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1958 %s subject
1959 %d date
1960 %m message-id.
1962 You may use normal field width specification between the % and the letter.
1963 This is for example useful to limit the length of the subject.
1965 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1966 :group 'org-link-store
1967 :type 'string)
1969 (defcustom org-from-is-user-regexp
1970 (let (r1 r2)
1971 (when (and user-mail-address (not (string= user-mail-address "")))
1972 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1973 (when (and user-full-name (not (string= user-full-name "")))
1974 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1975 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1976 "Regexp matched against the \"From:\" header of an email or usenet message.
1977 It should match if the message is from the user him/herself."
1978 :group 'org-link-store
1979 :type 'regexp)
1981 (defcustom org-context-in-file-links t
1982 "Non-nil means file links from `org-store-link' contain context.
1983 A search string will be added to the file name with :: as separator and
1984 used to find the context when the link is activated by the command
1985 `org-open-at-point'. When this option is t, the entire active region
1986 will be placed in the search string of the file link. If set to a
1987 positive integer, only the first n lines of context will be stored.
1989 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1990 negates this setting for the duration of the command."
1991 :group 'org-link-store
1992 :type '(choice boolean integer))
1994 (defcustom org-keep-stored-link-after-insertion nil
1995 "Non-nil means keep link in list for entire session.
1997 The command `org-store-link' adds a link pointing to the current
1998 location to an internal list. These links accumulate during a session.
1999 The command `org-insert-link' can be used to insert links into any
2000 Org-mode file (offering completion for all stored links). When this
2001 option is nil, every link which has been inserted once using \\[org-insert-link]
2002 will be removed from the list, to make completing the unused links
2003 more efficient."
2004 :group 'org-link-store
2005 :type 'boolean)
2007 (defgroup org-link-follow nil
2008 "Options concerning following links in Org-mode."
2009 :tag "Org Follow Link"
2010 :group 'org-link)
2012 (defcustom org-link-translation-function nil
2013 "Function to translate links with different syntax to Org syntax.
2014 This can be used to translate links created for example by the Planner
2015 or emacs-wiki packages to Org syntax.
2016 The function must accept two parameters, a TYPE containing the link
2017 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2018 which is everything after the link protocol. It should return a cons
2019 with possibly modified values of type and path.
2020 Org contains a function for this, so if you set this variable to
2021 `org-translate-link-from-planner', you should be able follow many
2022 links created by planner."
2023 :group 'org-link-follow
2024 :type '(choice (const nil) (function)))
2026 (defcustom org-follow-link-hook nil
2027 "Hook that is run after a link has been followed."
2028 :group 'org-link-follow
2029 :type 'hook)
2031 (defcustom org-tab-follows-link nil
2032 "Non-nil means on links TAB will follow the link.
2033 Needs to be set before org.el is loaded.
2034 This really should not be used, it does not make sense, and the
2035 implementation is bad."
2036 :group 'org-link-follow
2037 :type 'boolean)
2039 (defcustom org-return-follows-link nil
2040 "Non-nil means on links RET will follow the link.
2041 In tables, the special behavior of RET has precedence."
2042 :group 'org-link-follow
2043 :type 'boolean)
2045 (defcustom org-mouse-1-follows-link
2046 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2047 "Non-nil means mouse-1 on a link will follow the link.
2048 A longer mouse click will still set point. Needs to be set
2049 before org.el is loaded."
2050 :group 'org-link-follow
2051 :version "24.4"
2052 :package-version '(Org . "8.3")
2053 :type '(choice
2054 (const :tag "A double click follows the link" double)
2055 (const :tag "Unconditionally follow the link with mouse-1" t)
2056 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2058 (defcustom org-mark-ring-length 4
2059 "Number of different positions to be recorded in the ring.
2060 Changing this requires a restart of Emacs to work correctly."
2061 :group 'org-link-follow
2062 :type 'integer)
2064 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2065 "Non-nil means internal links in Org files must exactly match a headline.
2066 When nil, the link search tries to match a phrase with all words
2067 in the search text."
2068 :group 'org-link-follow
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "Use fuzzy text search" nil)
2072 (const :tag "Match only exact headline" t)
2073 (const :tag "Match exact headline or query to create it"
2074 query-to-create)))
2076 (defcustom org-link-frame-setup
2077 '((vm . vm-visit-folder-other-frame)
2078 (vm-imap . vm-visit-imap-folder-other-frame)
2079 (gnus . org-gnus-no-new-news)
2080 (file . find-file-other-window)
2081 (wl . wl-other-frame))
2082 "Setup the frame configuration for following links.
2083 When following a link with Emacs, it may often be useful to display
2084 this link in another window or frame. This variable can be used to
2085 set this up for the different types of links.
2086 For VM, use any of
2087 `vm-visit-folder'
2088 `vm-visit-folder-other-window'
2089 `vm-visit-folder-other-frame'
2090 For Gnus, use any of
2091 `gnus'
2092 `gnus-other-frame'
2093 `org-gnus-no-new-news'
2094 For FILE, use any of
2095 `find-file'
2096 `find-file-other-window'
2097 `find-file-other-frame'
2098 For Wanderlust use any of
2099 `wl'
2100 `wl-other-frame'
2101 For the calendar, use the variable `calendar-setup'.
2102 For BBDB, it is currently only possible to display the matches in
2103 another window."
2104 :group 'org-link-follow
2105 :type '(list
2106 (cons (const vm)
2107 (choice
2108 (const vm-visit-folder)
2109 (const vm-visit-folder-other-window)
2110 (const vm-visit-folder-other-frame)))
2111 (cons (const vm-imap)
2112 (choice
2113 (const vm-visit-imap-folder)
2114 (const vm-visit-imap-folder-other-window)
2115 (const vm-visit-imap-folder-other-frame)))
2116 (cons (const gnus)
2117 (choice
2118 (const gnus)
2119 (const gnus-other-frame)
2120 (const org-gnus-no-new-news)))
2121 (cons (const file)
2122 (choice
2123 (const find-file)
2124 (const find-file-other-window)
2125 (const find-file-other-frame)))
2126 (cons (const wl)
2127 (choice
2128 (const wl)
2129 (const wl-other-frame)))))
2131 (defcustom org-display-internal-link-with-indirect-buffer nil
2132 "Non-nil means use indirect buffer to display infile links.
2133 Activating internal links (from one location in a file to another location
2134 in the same file) normally just jumps to the location. When the link is
2135 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2136 is displayed in
2137 another window. When this option is set, the other window actually displays
2138 an indirect buffer clone of the current buffer, to avoid any visibility
2139 changes to the current buffer."
2140 :group 'org-link-follow
2141 :type 'boolean)
2143 (defcustom org-open-non-existing-files nil
2144 "Non-nil means `org-open-file' will open non-existing files.
2145 When nil, an error will be generated.
2146 This variable applies only to external applications because they
2147 might choke on non-existing files. If the link is to a file that
2148 will be opened in Emacs, the variable is ignored."
2149 :group 'org-link-follow
2150 :type 'boolean)
2152 (defcustom org-open-directory-means-index-dot-org nil
2153 "Non-nil means a link to a directory really means to index.org.
2154 When nil, following a directory link will run dired or open a finder/explorer
2155 window on that directory."
2156 :group 'org-link-follow
2157 :type 'boolean)
2159 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2160 "Non-nil means ask for confirmation before executing shell links.
2161 Shell links can be dangerous: just think about a link
2163 [[shell:rm -rf ~/*][Google Search]]
2165 This link would show up in your Org-mode document as \"Google Search\",
2166 but really it would remove your entire home directory.
2167 Therefore we advise against setting this variable to nil.
2168 Just change it to `y-or-n-p' if you want to confirm with a
2169 single keystroke rather than having to type \"yes\"."
2170 :group 'org-link-follow
2171 :type '(choice
2172 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2173 (const :tag "with y-or-n (faster)" y-or-n-p)
2174 (const :tag "no confirmation (dangerous)" nil)))
2175 (put 'org-confirm-shell-link-function
2176 'safe-local-variable
2177 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2179 (defcustom org-confirm-shell-link-not-regexp ""
2180 "A regexp to skip confirmation for shell links."
2181 :group 'org-link-follow
2182 :version "24.1"
2183 :type 'regexp)
2185 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2186 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2187 Elisp links can be dangerous: just think about a link
2189 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2191 This link would show up in your Org-mode document as \"Google Search\",
2192 but really it would remove your entire home directory.
2193 Therefore we advise against setting this variable to nil.
2194 Just change it to `y-or-n-p' if you want to confirm with a
2195 single keystroke rather than having to type \"yes\"."
2196 :group 'org-link-follow
2197 :type '(choice
2198 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2199 (const :tag "with y-or-n (faster)" y-or-n-p)
2200 (const :tag "no confirmation (dangerous)" nil)))
2201 (put 'org-confirm-shell-link-function
2202 'safe-local-variable
2203 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2205 (defcustom org-confirm-elisp-link-not-regexp ""
2206 "A regexp to skip confirmation for Elisp links."
2207 :group 'org-link-follow
2208 :version "24.1"
2209 :type 'regexp)
2211 (defconst org-file-apps-defaults-gnu
2212 '((remote . emacs)
2213 (system . mailcap)
2214 (t . mailcap))
2215 "Default file applications on a UNIX or GNU/Linux system.
2216 See `org-file-apps'.")
2218 (defconst org-file-apps-defaults-macosx
2219 '((remote . emacs)
2220 (system . "open %s")
2221 ("ps.gz" . "gv %s")
2222 ("eps.gz" . "gv %s")
2223 ("dvi" . "xdvi %s")
2224 ("fig" . "xfig %s")
2225 (t . "open %s"))
2226 "Default file applications on a MacOS X system.
2227 The system \"open\" is known as a default, but we use X11 applications
2228 for some files for which the OS does not have a good default.
2229 See `org-file-apps'.")
2231 (defconst org-file-apps-defaults-windowsnt
2232 (list '(remote . emacs)
2233 (cons 'system (lambda (file _path)
2234 (with-no-warnings (w32-shell-execute "open" file))))
2235 (cons t (lambda (file _path)
2236 (with-no-warnings (w32-shell-execute "open" file)))))
2237 "Default file applications on a Windows NT system.
2238 The system \"open\" is used for most files.
2239 See `org-file-apps'.")
2241 (defcustom org-file-apps
2242 '((auto-mode . emacs)
2243 ("\\.mm\\'" . default)
2244 ("\\.x?html?\\'" . default)
2245 ("\\.pdf\\'" . default))
2246 "External applications for opening `file:path' items in a document.
2247 \\<org-mode-map>\
2249 Org mode uses system defaults for different file types, but
2250 you can use this variable to set the application for a given file
2251 extension. The entries in this list are cons cells where the car identifies
2252 files and the cdr the corresponding command.
2254 Possible values for the file identifier are:
2256 \"string\" A string as a file identifier can be interpreted in different
2257 ways, depending on its contents:
2259 - Alphanumeric characters only:
2260 Match links with this file extension.
2261 Example: (\"pdf\" . \"evince %s\")
2262 to open PDFs with evince.
2264 - Regular expression: Match links where the
2265 filename matches the regexp. If you want to
2266 use groups here, use shy groups.
2268 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2269 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2270 to open *.html and *.xhtml with firefox.
2272 - Regular expression which contains (non-shy) groups:
2273 Match links where the whole link, including \"::\", and
2274 anything after that, matches the regexp.
2275 In a custom command string, %1, %2, etc. are replaced with
2276 the parts of the link that were matched by the groups.
2277 For backwards compatibility, if a command string is given
2278 that does not use any of the group matches, this case is
2279 handled identically to the second one (i.e. match against
2280 file name only).
2281 In a custom function, you can access the group matches with
2282 \(match-string n link).
2284 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2285 \"evince -p %1 %s\")
2286 to open [[file:document.pdf::5]] with evince at page 5.
2288 `directory' Matches a directory
2289 `remote' Matches a remote file, accessible through tramp or efs.
2290 Remote files most likely should be visited through Emacs
2291 because external applications cannot handle such paths.
2292 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2293 so all files Emacs knows how to handle. Using this with
2294 command `emacs' will open most files in Emacs. Beware that this
2295 will also open html files inside Emacs, unless you add
2296 \(\"html\" . default) to the list as well.
2297 `system' The system command to open files, like `open' on Windows
2298 and Mac OS X, and mailcap under GNU/Linux. This is the command
2299 that will be selected if you call \\[org-open-at-point] with a double
2300 \\[universal-argument] \\[universal-argument] prefix.
2301 t Default for files not matched by any of the other options.
2303 Possible values for the command are:
2305 `emacs' The file will be visited by the current Emacs process.
2306 `default' Use the default application for this file type, which is the
2307 association for t in the list, most likely in the system-specific
2308 part. This can be used to overrule an unwanted setting in the
2309 system-specific variable.
2310 `system' Use the system command for opening files, like \"open\".
2311 This command is specified by the entry whose car is `system'.
2312 Most likely, the system-specific version of this variable
2313 does define this command, but you can overrule/replace it
2314 here.
2315 `mailcap' Use command specified in the mailcaps.
2316 string A command to be executed by a shell; %s will be replaced
2317 by the path to the file.
2318 function A Lisp function, which will be called with two arguments:
2319 the file path and the original link string, without the
2320 \"file:\" prefix.
2322 For more examples, see the system specific constants
2323 `org-file-apps-defaults-macosx'
2324 `org-file-apps-defaults-windowsnt'
2325 `org-file-apps-defaults-gnu'."
2326 :group 'org-link-follow
2327 :type '(repeat
2328 (cons (choice :value ""
2329 (string :tag "Extension")
2330 (const :tag "System command to open files" system)
2331 (const :tag "Default for unrecognized files" t)
2332 (const :tag "Remote file" remote)
2333 (const :tag "Links to a directory" directory)
2334 (const :tag "Any files that have Emacs modes"
2335 auto-mode))
2336 (choice :value ""
2337 (const :tag "Visit with Emacs" emacs)
2338 (const :tag "Use default" default)
2339 (const :tag "Use the system command" system)
2340 (string :tag "Command")
2341 (function :tag "Function")))))
2343 (defcustom org-doi-server-url "http://dx.doi.org/"
2344 "The URL of the DOI server."
2345 :type 'string
2346 :version "24.3"
2347 :group 'org-link-follow)
2349 (defgroup org-refile nil
2350 "Options concerning refiling entries in Org-mode."
2351 :tag "Org Refile"
2352 :group 'org)
2354 (defcustom org-directory "~/org"
2355 "Directory with Org files.
2356 This is just a default location to look for Org files. There is no need
2357 at all to put your files into this directory. It is used in the
2358 following situations:
2360 1. When a capture template specifies a target file that is not an
2361 absolute path. The path will then be interpreted relative to
2362 `org-directory'
2363 2. When the value of variable `org-agenda-files' is a single file, any
2364 relative paths in this file will be taken as relative to
2365 `org-directory'."
2366 :group 'org-refile
2367 :group 'org-capture
2368 :type 'directory)
2370 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2371 "Default target for storing notes.
2372 Used as a fall back file for org-capture.el, for templates that
2373 do not specify a target file."
2374 :group 'org-refile
2375 :group 'org-capture
2376 :type 'file)
2378 (defcustom org-goto-interface 'outline
2379 "The default interface to be used for `org-goto'.
2380 Allowed values are:
2381 outline The interface shows an outline of the relevant file
2382 and the correct heading is found by moving through
2383 the outline or by searching with incremental search.
2384 outline-path-completion Headlines in the current buffer are offered via
2385 completion. This is the interface also used by
2386 the refile command."
2387 :group 'org-refile
2388 :type '(choice
2389 (const :tag "Outline" outline)
2390 (const :tag "Outline-path-completion" outline-path-completion)))
2392 (defcustom org-goto-max-level 5
2393 "Maximum target level when running `org-goto' with refile interface."
2394 :group 'org-refile
2395 :type 'integer)
2397 (defcustom org-reverse-note-order nil
2398 "Non-nil means store new notes at the beginning of a file or entry.
2399 When nil, new notes will be filed to the end of a file or entry.
2400 This can also be a list with cons cells of regular expressions that
2401 are matched against file names, and values."
2402 :group 'org-capture
2403 :group 'org-refile
2404 :type '(choice
2405 (const :tag "Reverse always" t)
2406 (const :tag "Reverse never" nil)
2407 (repeat :tag "By file name regexp"
2408 (cons regexp boolean))))
2410 (defcustom org-log-refile nil
2411 "Information to record when a task is refiled.
2413 Possible values are:
2415 nil Don't add anything
2416 time Add a time stamp to the task
2417 note Prompt for a note and add it with template `org-log-note-headings'
2419 This option can also be set with on a per-file-basis with
2421 #+STARTUP: nologrefile
2422 #+STARTUP: logrefile
2423 #+STARTUP: lognoterefile
2425 You can have local logging settings for a subtree by setting the LOGGING
2426 property to one or more of these keywords.
2428 When bulk-refiling from the agenda, the value `note' is forbidden and
2429 will temporarily be changed to `time'."
2430 :group 'org-refile
2431 :group 'org-progress
2432 :version "24.1"
2433 :type '(choice
2434 (const :tag "No logging" nil)
2435 (const :tag "Record timestamp" time)
2436 (const :tag "Record timestamp with note." note)))
2438 (defcustom org-refile-targets nil
2439 "Targets for refiling entries with \\[org-refile].
2440 This is a list of cons cells. Each cell contains:
2441 - a specification of the files to be considered, either a list of files,
2442 or a symbol whose function or variable value will be used to retrieve
2443 a file name or a list of file names. If you use `org-agenda-files' for
2444 that, all agenda files will be scanned for targets. Nil means consider
2445 headings in the current buffer.
2446 - A specification of how to find candidate refile targets. This may be
2447 any of:
2448 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2449 This tag has to be present in all target headlines, inheritance will
2450 not be considered.
2451 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2452 todo keyword.
2453 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2454 headlines that are refiling targets.
2455 - a cons cell (:level . N). Any headline of level N is considered a target.
2456 Note that, when `org-odd-levels-only' is set, level corresponds to
2457 order in hierarchy, not to the number of stars.
2458 - a cons cell (:maxlevel . N). Any headline with level <= N is 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.
2462 Each element of this list generates a set of possible targets.
2463 The union of these sets is presented (with completion) to
2464 the user by `org-refile'.
2466 You can set the variable `org-refile-target-verify-function' to a function
2467 to verify each headline found by the simple criteria above.
2469 When this variable is nil, all top-level headlines in the current buffer
2470 are used, equivalent to the value `((nil . (:level . 1))'."
2471 :group 'org-refile
2472 :type '(repeat
2473 (cons
2474 (choice :value org-agenda-files
2475 (const :tag "All agenda files" org-agenda-files)
2476 (const :tag "Current buffer" nil)
2477 (function) (variable) (file))
2478 (choice :tag "Identify target headline by"
2479 (cons :tag "Specific tag" (const :value :tag) (string))
2480 (cons :tag "TODO keyword" (const :value :todo) (string))
2481 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2482 (cons :tag "Level number" (const :value :level) (integer))
2483 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2485 (defcustom org-refile-target-verify-function nil
2486 "Function to verify if the headline at point should be a refile target.
2487 The function will be called without arguments, with point at the
2488 beginning of the headline. It should return t and leave point
2489 where it is if the headline is a valid target for refiling.
2491 If the target should not be selected, the function must return nil.
2492 In addition to this, it may move point to a place from where the search
2493 should be continued. For example, the function may decide that the entire
2494 subtree of the current entry should be excluded and move point to the end
2495 of the subtree."
2496 :group 'org-refile
2497 :type '(choice
2498 (const nil)
2499 (function)))
2501 (defcustom org-refile-use-cache nil
2502 "Non-nil means cache refile targets to speed up the process.
2503 \\<org-mode-map>\
2504 The cache for a particular file will be updated automatically when
2505 the buffer has been killed, or when any of the marker used for flagging
2506 refile targets no longer points at a live buffer.
2507 If you have added new entries to a buffer that might themselves be targets,
2508 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2509 if you find that easier, \
2510 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2511 \\[org-refile]'."
2512 :group 'org-refile
2513 :version "24.1"
2514 :type 'boolean)
2516 (defcustom org-refile-use-outline-path nil
2517 "Non-nil means provide refile targets as paths.
2518 So a level 3 headline will be available as level1/level2/level3.
2520 When the value is `file', also include the file name (without directory)
2521 into the path. In this case, you can also stop the completion after
2522 the file name, to get entries inserted as top level in the file.
2524 When `full-file-path', include the full file path."
2525 :group 'org-refile
2526 :type '(choice
2527 (const :tag "Not" nil)
2528 (const :tag "Yes" t)
2529 (const :tag "Start with file name" file)
2530 (const :tag "Start with full file path" full-file-path)))
2532 (defcustom org-outline-path-complete-in-steps t
2533 "Non-nil means complete the outline path in hierarchical steps.
2534 When Org-mode uses the refile interface to select an outline path
2535 \(see variable `org-refile-use-outline-path'), the completion of
2536 the path can be done in a single go, or it can be done in steps down
2537 the headline hierarchy. Going in steps is probably the best if you
2538 do not use a special completion package like `ido' or `icicles'.
2539 However, when using these packages, going in one step can be very
2540 fast, while still showing the whole path to the entry."
2541 :group 'org-refile
2542 :type 'boolean)
2544 (defcustom org-refile-allow-creating-parent-nodes nil
2545 "Non-nil means allow the creation of new nodes as refile targets.
2546 New nodes are then created by adding \"/new node name\" to the completion
2547 of an existing node. When the value of this variable is `confirm',
2548 new node creation must be confirmed by the user (recommended).
2549 When nil, the completion must match an existing entry.
2551 Note that, if the new heading is not seen by the criteria
2552 listed in `org-refile-targets', multiple instances of the same
2553 heading would be created by trying again to file under the new
2554 heading."
2555 :group 'org-refile
2556 :type '(choice
2557 (const :tag "Never" nil)
2558 (const :tag "Always" t)
2559 (const :tag "Prompt for confirmation" confirm)))
2561 (defcustom org-refile-active-region-within-subtree nil
2562 "Non-nil means also refile active region within a subtree.
2564 By default `org-refile' doesn't allow refiling regions if they
2565 don't contain a set of subtrees, but it might be convenient to
2566 do so sometimes: in that case, the first line of the region is
2567 converted to a headline before refiling."
2568 :group 'org-refile
2569 :version "24.1"
2570 :type 'boolean)
2572 (defgroup org-todo nil
2573 "Options concerning TODO items in Org-mode."
2574 :tag "Org TODO"
2575 :group 'org)
2577 (defgroup org-progress nil
2578 "Options concerning Progress logging in Org-mode."
2579 :tag "Org Progress"
2580 :group 'org-time)
2582 (defvar org-todo-interpretation-widgets
2583 '((:tag "Sequence (cycling hits every state)" sequence)
2584 (:tag "Type (cycling directly to DONE)" type))
2585 "The available interpretation symbols for customizing `org-todo-keywords'.
2586 Interested libraries should add to this list.")
2588 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2589 "List of TODO entry keyword sequences and their interpretation.
2590 \\<org-mode-map>This is a list of sequences.
2592 Each sequence starts with a symbol, either `sequence' or `type',
2593 indicating if the keywords should be interpreted as a sequence of
2594 action steps, or as different types of TODO items. The first
2595 keywords are states requiring action - these states will select a headline
2596 for inclusion into the global TODO list Org-mode produces. If one of
2597 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2598 signify that no further action is necessary. If \"|\" is not found,
2599 the last keyword is treated as the only DONE state of the sequence.
2601 The command \\[org-todo] cycles an entry through these states, and one
2602 additional state where no keyword is present. For details about this
2603 cycling, see the manual.
2605 TODO keywords and interpretation can also be set on a per-file basis with
2606 the special #+SEQ_TODO and #+TYP_TODO lines.
2608 Each keyword can optionally specify a character for fast state selection
2609 \(in combination with the variable `org-use-fast-todo-selection')
2610 and specifiers for state change logging, using the same syntax that
2611 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2612 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2613 indicates to record a time stamp each time this state is selected.
2615 Each keyword may also specify if a timestamp or a note should be
2616 recorded when entering or leaving the state, by adding additional
2617 characters in the parenthesis after the keyword. This looks like this:
2618 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2619 record only the time of the state change. With X and Y being either
2620 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2621 Y when leaving the state if and only if the *target* state does not
2622 define X. You may omit any of the fast-selection key or X or /Y,
2623 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2625 For backward compatibility, this variable may also be just a list
2626 of keywords. In this case the interpretation (sequence or type) will be
2627 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2628 :group 'org-todo
2629 :group 'org-keywords
2630 :type '(choice
2631 (repeat :tag "Old syntax, just keywords"
2632 (string :tag "Keyword"))
2633 (repeat :tag "New syntax"
2634 (cons
2635 (choice
2636 :tag "Interpretation"
2637 ;;Quick and dirty way to see
2638 ;;`org-todo-interpretations'. This takes the
2639 ;;place of item arguments
2640 :convert-widget
2641 (lambda (widget)
2642 (widget-put widget
2643 :args (mapcar
2644 (lambda (x)
2645 (widget-convert
2646 (cons 'const x)))
2647 org-todo-interpretation-widgets))
2648 widget))
2649 (repeat
2650 (string :tag "Keyword"))))))
2652 (defvar-local org-todo-keywords-1 nil
2653 "All TODO and DONE keywords active in a buffer.")
2654 (defvar org-todo-keywords-for-agenda nil)
2655 (defvar org-done-keywords-for-agenda nil)
2656 (defvar org-todo-keyword-alist-for-agenda nil)
2657 (defvar org-tag-alist-for-agenda nil
2658 "Alist of all tags from all agenda files.")
2659 (defvar org-tag-groups-alist-for-agenda nil
2660 "Alist of all groups tags from all current agenda files.")
2661 (defvar-local org-tag-groups-alist nil)
2662 (defvar org-agenda-contributing-files nil)
2663 (defvar-local org-current-tag-alist nil
2664 "Alist of all tag groups in current buffer.
2665 This variable takes into consideration `org-tag-alist',
2666 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2667 (defvar-local org-not-done-keywords nil)
2668 (defvar-local org-done-keywords nil)
2669 (defvar-local org-todo-heads nil)
2670 (defvar-local org-todo-sets nil)
2671 (defvar-local org-todo-log-states nil)
2672 (defvar-local org-todo-kwd-alist nil)
2673 (defvar-local org-todo-key-alist nil)
2674 (defvar-local org-todo-key-trigger nil)
2676 (defcustom org-todo-interpretation 'sequence
2677 "Controls how TODO keywords are interpreted.
2678 This variable is in principle obsolete and is only used for
2679 backward compatibility, if the interpretation of todo keywords is
2680 not given already in `org-todo-keywords'. See that variable for
2681 more information."
2682 :group 'org-todo
2683 :group 'org-keywords
2684 :type '(choice (const sequence)
2685 (const type)))
2687 (defcustom org-use-fast-todo-selection t
2688 "\\<org-mode-map>\
2689 Non-nil means use the fast todo selection scheme with \\[org-todo].
2690 This variable describes if and under what circumstances the cycling
2691 mechanism for TODO keywords will be replaced by a single-key, direct
2692 selection scheme.
2694 When nil, fast selection is never used.
2696 When the symbol `prefix', it will be used when `org-todo' is called
2697 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2698 in an Org-mode buffer, and
2699 `\\[universal-argument] t' in an agenda buffer.
2701 When t, fast selection is used by default. In this case, the prefix
2702 argument forces cycling instead.
2704 In all cases, the special interface is only used if access keys have
2705 actually been assigned by the user, i.e. if keywords in the configuration
2706 are followed by a letter in parenthesis, like TODO(t)."
2707 :group 'org-todo
2708 :type '(choice
2709 (const :tag "Never" nil)
2710 (const :tag "By default" t)
2711 (const :tag "Only with C-u C-c C-t" prefix)))
2713 (defcustom org-provide-todo-statistics t
2714 "Non-nil means update todo statistics after insert and toggle.
2715 ALL-HEADLINES means update todo statistics by including headlines
2716 with no TODO keyword as well, counting them as not done.
2717 A list of TODO keywords means the same, but skip keywords that are
2718 not in this list.
2719 When set to a list of two lists, the first list contains keywords
2720 to consider as TODO keywords, the second list contains keywords
2721 to consider as DONE keywords.
2723 When this is set, todo statistics is updated in the parent of the
2724 current entry each time a todo state is changed."
2725 :group 'org-todo
2726 :type '(choice
2727 (const :tag "Yes, only for TODO entries" t)
2728 (const :tag "Yes, including all entries" all-headlines)
2729 (repeat :tag "Yes, for TODOs in this list"
2730 (string :tag "TODO keyword"))
2731 (list :tag "Yes, for TODOs and DONEs in these lists"
2732 (repeat (string :tag "TODO keyword"))
2733 (repeat (string :tag "DONE keyword")))
2734 (other :tag "No TODO statistics" nil)))
2736 (defcustom org-hierarchical-todo-statistics t
2737 "Non-nil means TODO statistics covers just direct children.
2738 When nil, all entries in the subtree are considered.
2739 This has only an effect if `org-provide-todo-statistics' is set.
2740 To set this to nil for only a single subtree, use a COOKIE_DATA
2741 property and include the word \"recursive\" into the value."
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-after-todo-state-change-hook nil
2746 "Hook which is run after the state of a TODO item was changed.
2747 The new state (a string with a TODO keyword, or nil) is available in the
2748 Lisp variable `org-state'."
2749 :group 'org-todo
2750 :type 'hook)
2752 (defvar org-blocker-hook nil
2753 "Hook for functions that are allowed to block a state change.
2755 Functions in this hook should not modify the buffer.
2756 Each function gets as its single argument a property list,
2757 see `org-trigger-hook' for more information about this list.
2759 If any of the functions in this hook returns nil, the state change
2760 is blocked.")
2762 (defvar org-trigger-hook nil
2763 "Hook for functions that are triggered by a state change.
2765 Each function gets as its single argument a property list with at
2766 least the following elements:
2768 (:type type-of-change :position pos-at-entry-start
2769 :from old-state :to new-state)
2771 Depending on the type, more properties may be present.
2773 This mechanism is currently implemented for:
2775 TODO state changes
2776 ------------------
2777 :type todo-state-change
2778 :from previous state (keyword as a string), or nil, or a symbol
2779 `todo' or `done', to indicate the general type of state.
2780 :to new state, like in :from")
2782 (defcustom org-enforce-todo-dependencies nil
2783 "Non-nil means undone TODO entries will block switching the parent to DONE.
2784 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2785 be blocked if any prior sibling is not yet done.
2786 Finally, if the parent is blocked because of ordered siblings of its own,
2787 the child will also be blocked."
2788 :set (lambda (var val)
2789 (set var val)
2790 (if val
2791 (add-hook 'org-blocker-hook
2792 'org-block-todo-from-children-or-siblings-or-parent)
2793 (remove-hook 'org-blocker-hook
2794 'org-block-todo-from-children-or-siblings-or-parent)))
2795 :group 'org-todo
2796 :type 'boolean)
2798 (defcustom org-enforce-todo-checkbox-dependencies nil
2799 "Non-nil means unchecked boxes will block switching the parent to DONE.
2800 When this is nil, checkboxes have no influence on switching TODO states.
2801 When non-nil, you first need to check off all check boxes before the TODO
2802 entry can be switched to DONE.
2803 This variable needs to be set before org.el is loaded, and you need to
2804 restart Emacs after a change to make the change effective. The only way
2805 to change is while Emacs is running is through the customize interface."
2806 :set (lambda (var val)
2807 (set var val)
2808 (if val
2809 (add-hook 'org-blocker-hook
2810 'org-block-todo-from-checkboxes)
2811 (remove-hook 'org-blocker-hook
2812 'org-block-todo-from-checkboxes)))
2813 :group 'org-todo
2814 :type 'boolean)
2816 (defcustom org-treat-insert-todo-heading-as-state-change nil
2817 "Non-nil means inserting a TODO heading is treated as state change.
2818 So when the command \\[org-insert-todo-heading] is used, state change
2819 logging will apply if appropriate. When nil, the new TODO item will
2820 be inserted directly, and no logging will take place."
2821 :group 'org-todo
2822 :type 'boolean)
2824 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2825 "Non-nil means switching TODO states with S-cursor counts as state change.
2826 This is the default behavior. However, setting this to nil allows a
2827 convenient way to select a TODO state and bypass any logging associated
2828 with that."
2829 :group 'org-todo
2830 :type 'boolean)
2832 (defcustom org-todo-state-tags-triggers nil
2833 "Tag changes that should be triggered by TODO state changes.
2834 This is a list. Each entry is
2836 (state-change (tag . flag) .......)
2838 State-change can be a string with a state, and empty string to indicate the
2839 state that has no TODO keyword, or it can be one of the symbols `todo'
2840 or `done', meaning any not-done or done state, respectively."
2841 :group 'org-todo
2842 :group 'org-tags
2843 :type '(repeat
2844 (cons (choice :tag "When changing to"
2845 (const :tag "Not-done state" todo)
2846 (const :tag "Done state" done)
2847 (string :tag "State"))
2848 (repeat
2849 (cons :tag "Tag action"
2850 (string :tag "Tag")
2851 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2853 (defcustom org-log-done nil
2854 "Information to record when a task moves to the DONE state.
2856 Possible values are:
2858 nil Don't add anything, just change the keyword
2859 time Add a time stamp to the task
2860 note Prompt for a note and add it with template `org-log-note-headings'
2862 This option can also be set with on a per-file-basis with
2864 #+STARTUP: nologdone
2865 #+STARTUP: logdone
2866 #+STARTUP: lognotedone
2868 You can have local logging settings for a subtree by setting the LOGGING
2869 property to one or more of these keywords."
2870 :group 'org-todo
2871 :group 'org-progress
2872 :type '(choice
2873 (const :tag "No logging" nil)
2874 (const :tag "Record CLOSED timestamp" time)
2875 (const :tag "Record CLOSED timestamp with note." note)))
2877 ;; Normalize old uses of org-log-done.
2878 (cond
2879 ((eq org-log-done t) (setq org-log-done 'time))
2880 ((and (listp org-log-done) (memq 'done org-log-done))
2881 (setq org-log-done 'note)))
2883 (defcustom org-log-reschedule nil
2884 "Information to record when the scheduling date of a tasks is modified.
2886 Possible values are:
2888 nil Don't add anything, just change the date
2889 time Add a time stamp to the task
2890 note Prompt for a note and add it with template `org-log-note-headings'
2892 This option can also be set with on a per-file-basis with
2894 #+STARTUP: nologreschedule
2895 #+STARTUP: logreschedule
2896 #+STARTUP: lognotereschedule"
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type '(choice
2900 (const :tag "No logging" nil)
2901 (const :tag "Record timestamp" time)
2902 (const :tag "Record timestamp with note." note)))
2904 (defcustom org-log-redeadline nil
2905 "Information to record when the deadline date of a tasks is modified.
2907 Possible values are:
2909 nil Don't add anything, just change the date
2910 time Add a time stamp to the task
2911 note Prompt for a note and add it with template `org-log-note-headings'
2913 This option can also be set with on a per-file-basis with
2915 #+STARTUP: nologredeadline
2916 #+STARTUP: logredeadline
2917 #+STARTUP: lognoteredeadline
2919 You can have local logging settings for a subtree by setting the LOGGING
2920 property to one or more of these keywords."
2921 :group 'org-todo
2922 :group 'org-progress
2923 :type '(choice
2924 (const :tag "No logging" nil)
2925 (const :tag "Record timestamp" time)
2926 (const :tag "Record timestamp with note." note)))
2928 (defcustom org-log-note-clock-out nil
2929 "Non-nil means record a note when clocking out of an item.
2930 This can also be configured on a per-file basis by adding one of
2931 the following lines anywhere in the buffer:
2933 #+STARTUP: lognoteclock-out
2934 #+STARTUP: nolognoteclock-out"
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type 'boolean)
2939 (defcustom org-log-done-with-time t
2940 "Non-nil means the CLOSED time stamp will contain date and time.
2941 When nil, only the date will be recorded."
2942 :group 'org-progress
2943 :type 'boolean)
2945 (defcustom org-log-note-headings
2946 '((done . "CLOSING NOTE %t")
2947 (state . "State %-12s from %-12S %t")
2948 (note . "Note taken on %t")
2949 (reschedule . "Rescheduled from %S on %t")
2950 (delschedule . "Not scheduled, was %S on %t")
2951 (redeadline . "New deadline from %S on %t")
2952 (deldeadline . "Removed deadline, was %S on %t")
2953 (refile . "Refiled on %t")
2954 (clock-out . ""))
2955 "Headings for notes added to entries.
2957 The value is an alist, with the car being a symbol indicating the
2958 note context, and the cdr is the heading to be used. The heading
2959 may also be the empty string. The following placeholders can be
2960 used:
2962 %t a time stamp.
2963 %T an active time stamp instead the default inactive one
2964 %d a short-format time stamp.
2965 %D an active short-format time stamp.
2966 %s the new TODO state or time stamp (inactive), in double quotes.
2967 %S the old TODO state or time stamp (inactive), in double quotes.
2968 %u the user name.
2969 %U full user name.
2971 In fact, it is not a good idea to change the `state' entry,
2972 because Agenda Log mode depends on the format of these entries."
2973 :group 'org-todo
2974 :group 'org-progress
2975 :type '(list :greedy t
2976 (cons (const :tag "Heading when closing an item" done) string)
2977 (cons (const :tag
2978 "Heading when changing todo state (todo sequence only)"
2979 state) string)
2980 (cons (const :tag "Heading when just taking a note" note) string)
2981 (cons (const :tag "Heading when rescheduling" reschedule) string)
2982 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2983 (cons (const :tag "Heading when changing deadline" redeadline) string)
2984 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2985 (cons (const :tag "Heading when refiling" refile) string)
2986 (cons (const :tag "Heading when clocking out" clock-out) string)))
2988 (unless (assq 'note org-log-note-headings)
2989 (push '(note . "%t") org-log-note-headings))
2991 (defcustom org-log-into-drawer nil
2992 "Non-nil means insert state change notes and time stamps into a drawer.
2993 When nil, state changes notes will be inserted after the headline and
2994 any scheduling and clock lines, but not inside a drawer.
2996 The value of this variable should be the name of the drawer to use.
2997 LOGBOOK is proposed as the default drawer for this purpose, you can
2998 also set this to a string to define the drawer of your choice.
3000 A value of t is also allowed, representing \"LOGBOOK\".
3002 A value of t or nil can also be set with on a per-file-basis with
3004 #+STARTUP: logdrawer
3005 #+STARTUP: nologdrawer
3007 If this variable is set, `org-log-state-notes-insert-after-drawers'
3008 will be ignored.
3010 You can set the property LOG_INTO_DRAWER to overrule this setting for
3011 a subtree.
3013 Do not check directly this variable in a Lisp program. Call
3014 function `org-log-into-drawer' instead."
3015 :group 'org-todo
3016 :group 'org-progress
3017 :type '(choice
3018 (const :tag "Not into a drawer" nil)
3019 (const :tag "LOGBOOK" t)
3020 (string :tag "Other")))
3022 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3024 (defun org-log-into-drawer ()
3025 "Name of the log drawer, as a string, or nil.
3026 This is the value of `org-log-into-drawer'. However, if the
3027 current entry has or inherits a LOG_INTO_DRAWER property, it will
3028 be used instead of the default value."
3029 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3030 (cond ((equal p "nil") nil)
3031 ((equal p "t") "LOGBOOK")
3032 ((stringp p) p)
3033 (p "LOGBOOK")
3034 ((stringp org-log-into-drawer) org-log-into-drawer)
3035 (org-log-into-drawer "LOGBOOK"))))
3037 (defcustom org-log-state-notes-insert-after-drawers nil
3038 "Non-nil means insert state change notes after any drawers in entry.
3039 Only the drawers that *immediately* follow the headline and the
3040 deadline/scheduled line are skipped.
3041 When nil, insert notes right after the heading and perhaps the line
3042 with deadline/scheduling if present.
3044 This variable will have no effect if `org-log-into-drawer' is
3045 set."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type 'boolean)
3050 (defcustom org-log-states-order-reversed t
3051 "Non-nil means the latest state note will be directly after heading.
3052 When nil, the state change notes will be ordered according to time.
3054 This option can also be set with on a per-file-basis with
3056 #+STARTUP: logstatesreversed
3057 #+STARTUP: nologstatesreversed"
3058 :group 'org-todo
3059 :group 'org-progress
3060 :type 'boolean)
3062 (defcustom org-todo-repeat-to-state nil
3063 "The TODO state to which a repeater should return the repeating task.
3064 By default this is the first task in a TODO sequence, or the previous state
3065 in a TODO_TYP set. But you can specify another task here.
3066 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3067 :group 'org-todo
3068 :version "24.1"
3069 :type '(choice (const :tag "Head of sequence" nil)
3070 (string :tag "Specific state")))
3072 (defcustom org-log-repeat 'time
3073 "Non-nil means record moving through the DONE state when triggering repeat.
3074 An auto-repeating task is immediately switched back to TODO when
3075 marked DONE. If you are not logging state changes (by adding \"@\"
3076 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3077 record a closing note, there will be no record of the task moving
3078 through DONE. This variable forces taking a note anyway.
3080 nil Don't force a record
3081 time Record a time stamp
3082 note Prompt for a note and add it with template `org-log-note-headings'
3084 This option can also be set with on a per-file-basis with
3086 #+STARTUP: nologrepeat
3087 #+STARTUP: logrepeat
3088 #+STARTUP: lognoterepeat
3090 You can have local logging settings for a subtree by setting the LOGGING
3091 property to one or more of these keywords."
3092 :group 'org-todo
3093 :group 'org-progress
3094 :type '(choice
3095 (const :tag "Don't force a record" nil)
3096 (const :tag "Force recording the DONE state" time)
3097 (const :tag "Force recording a note with the DONE state" note)))
3100 (defgroup org-priorities nil
3101 "Priorities in Org-mode."
3102 :tag "Org Priorities"
3103 :group 'org-todo)
3105 (defcustom org-enable-priority-commands t
3106 "Non-nil means priority commands are active.
3107 When nil, these commands will be disabled, so that you never accidentally
3108 set a priority."
3109 :group 'org-priorities
3110 :type 'boolean)
3112 (defcustom org-highest-priority ?A
3113 "The highest priority of TODO items. A character like ?A, ?B etc.
3114 Must have a smaller ASCII number than `org-lowest-priority'."
3115 :group 'org-priorities
3116 :type 'character)
3118 (defcustom org-lowest-priority ?C
3119 "The lowest priority of TODO items. A character like ?A, ?B etc.
3120 Must have a larger ASCII number than `org-highest-priority'."
3121 :group 'org-priorities
3122 :type 'character)
3124 (defcustom org-default-priority ?B
3125 "The default priority of TODO items.
3126 This is the priority an item gets if no explicit priority is given.
3127 When starting to cycle on an empty priority the first step in the cycle
3128 depends on `org-priority-start-cycle-with-default'. The resulting first
3129 step priority must not exceed the range from `org-highest-priority' to
3130 `org-lowest-priority' which means that `org-default-priority' has to be
3131 in this range exclusive or inclusive the range boundaries. Else the
3132 first step refuses to set the default and the second will fall back
3133 to (depending on the command used) the highest or lowest priority."
3134 :group 'org-priorities
3135 :type 'character)
3137 (defcustom org-priority-start-cycle-with-default t
3138 "Non-nil means start with default priority when starting to cycle.
3139 When this is nil, the first step in the cycle will be (depending on the
3140 command used) one higher or lower than the default priority.
3141 See also `org-default-priority'."
3142 :group 'org-priorities
3143 :type 'boolean)
3145 (defcustom org-get-priority-function nil
3146 "Function to extract the priority from a string.
3147 The string is normally the headline. If this is nil Org computes the
3148 priority from the priority cookie like [#A] in the headline. It returns
3149 an integer, increasing by 1000 for each priority level.
3150 The user can set a different function here, which should take a string
3151 as an argument and return the numeric priority."
3152 :group 'org-priorities
3153 :version "24.1"
3154 :type '(choice
3155 (const nil)
3156 (function)))
3158 (defgroup org-time nil
3159 "Options concerning time stamps and deadlines in Org-mode."
3160 :tag "Org Time"
3161 :group 'org)
3163 (defcustom org-time-stamp-rounding-minutes '(0 5)
3164 "Number of minutes to round time stamps to.
3165 \\<org-mode-map>\
3166 These are two values, the first applies when first creating a time stamp.
3167 The second applies when changing it with the commands `S-up' and `S-down'.
3168 When changing the time stamp, this means that it will change in steps
3169 of N minutes, as given by the second value.
3171 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3172 numbers should be factors of 60, so for example 5, 10, 15.
3174 When this is larger than 1, you can still force an exact time stamp by using
3175 a double prefix argument to a time stamp command like \
3176 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3177 and by using a prefix arg to `S-up/down' to specify the exact number
3178 of minutes to shift."
3179 :group 'org-time
3180 :get (lambda (var) ; Make sure both elements are there
3181 (if (integerp (default-value var))
3182 (list (default-value var) 5)
3183 (default-value var)))
3184 :type '(list
3185 (integer :tag "when inserting times")
3186 (integer :tag "when modifying times")))
3188 ;; Normalize old customizations of this variable.
3189 (when (integerp org-time-stamp-rounding-minutes)
3190 (setq org-time-stamp-rounding-minutes
3191 (list org-time-stamp-rounding-minutes
3192 org-time-stamp-rounding-minutes)))
3194 (defcustom org-display-custom-times nil
3195 "Non-nil means overlay custom formats over all time stamps.
3196 The formats are defined through the variable `org-time-stamp-custom-formats'.
3197 To turn this on on a per-file basis, insert anywhere in the file:
3198 #+STARTUP: customtime"
3199 :group 'org-time
3200 :set 'set-default
3201 :type 'sexp)
3202 (make-variable-buffer-local 'org-display-custom-times)
3204 (defcustom org-time-stamp-custom-formats
3205 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3206 "Custom formats for time stamps. See `format-time-string' for the syntax.
3207 These are overlaid over the default ISO format if the variable
3208 `org-display-custom-times' is set. Time like %H:%M should be at the
3209 end of the second format. The custom formats are also honored by export
3210 commands, if custom time display is turned on at the time of export."
3211 :group 'org-time
3212 :type 'sexp)
3214 (defun org-time-stamp-format (&optional long inactive)
3215 "Get the right format for a time string."
3216 (let ((f (if long (cdr org-time-stamp-formats)
3217 (car org-time-stamp-formats))))
3218 (if inactive
3219 (concat "[" (substring f 1 -1) "]")
3220 f)))
3222 (defcustom org-time-clocksum-format
3223 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3224 "The format string used when creating CLOCKSUM lines.
3225 This is also used when Org mode generates a time duration.
3227 The value can be a single format string containing two
3228 %-sequences, which will be filled with the number of hours and
3229 minutes in that order.
3231 Alternatively, the value can be a plist associating any of the
3232 keys :years, :months, :weeks, :days, :hours or :minutes with
3233 format strings. The time duration is formatted using only the
3234 time components that are needed and concatenating the results.
3235 If a time unit in absent, it falls back to the next smallest
3236 unit.
3238 The keys :require-years, :require-months, :require-days,
3239 :require-weeks, :require-hours, :require-minutes are also
3240 meaningful. A non-nil value for these keys indicates that the
3241 corresponding time component should always be included, even if
3242 its value is 0.
3245 For example,
3247 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3248 :require-minutes t)
3250 means durations longer than a day will be expressed in days,
3251 hours and minutes, and durations less than a day will always be
3252 expressed in hours and minutes (even for durations less than an
3253 hour).
3255 The value
3257 (:days \"%dd\" :minutes \"%dm\")
3259 means durations longer than a day will be expressed in days and
3260 minutes, and durations less than a day will be expressed entirely
3261 in minutes (even for durations longer than an hour)."
3262 :group 'org-time
3263 :group 'org-clock
3264 :version "24.4"
3265 :package-version '(Org . "8.0")
3266 :type '(choice (string :tag "Format string")
3267 (set :tag "Plist"
3268 (group :inline t (const :tag "Years" :years)
3269 (string :tag "Format string"))
3270 (group :inline t
3271 (const :tag "Always show years" :require-years)
3272 (const t))
3273 (group :inline t (const :tag "Months" :months)
3274 (string :tag "Format string"))
3275 (group :inline t
3276 (const :tag "Always show months" :require-months)
3277 (const t))
3278 (group :inline t (const :tag "Weeks" :weeks)
3279 (string :tag "Format string"))
3280 (group :inline t
3281 (const :tag "Always show weeks" :require-weeks)
3282 (const t))
3283 (group :inline t (const :tag "Days" :days)
3284 (string :tag "Format string"))
3285 (group :inline t
3286 (const :tag "Always show days" :require-days)
3287 (const t))
3288 (group :inline t (const :tag "Hours" :hours)
3289 (string :tag "Format string"))
3290 (group :inline t
3291 (const :tag "Always show hours" :require-hours)
3292 (const t))
3293 (group :inline t (const :tag "Minutes" :minutes)
3294 (string :tag "Format string"))
3295 (group :inline t
3296 (const :tag "Always show minutes" :require-minutes)
3297 (const t)))))
3299 (defcustom org-time-clocksum-use-fractional nil
3300 "When non-nil, \\[org-clock-display] uses fractional times.
3301 See `org-time-clocksum-format' for more on time clock formats."
3302 :group 'org-time
3303 :group 'org-clock
3304 :version "24.3"
3305 :type 'boolean)
3307 (defcustom org-time-clocksum-use-effort-durations nil
3308 "When non-nil, \\[org-clock-display] uses effort durations.
3309 E.g. by default, one day is considered to be a 8 hours effort,
3310 so a task that has been clocked for 16 hours will be displayed
3311 as during 2 days in the clock display or in the clocktable.
3313 See `org-effort-durations' on how to set effort durations
3314 and `org-time-clocksum-format' for more on time clock formats."
3315 :group 'org-time
3316 :group 'org-clock
3317 :version "24.4"
3318 :package-version '(Org . "8.0")
3319 :type 'boolean)
3321 (defcustom org-time-clocksum-fractional-format "%.2f"
3322 "The format string used when creating CLOCKSUM lines,
3323 or when Org mode generates a time duration, if
3324 `org-time-clocksum-use-fractional' is enabled.
3326 The value can be a single format string containing one
3327 %-sequence, which will be filled with the number of hours as
3328 a float.
3330 Alternatively, the value can be a plist associating any of the
3331 keys :years, :months, :weeks, :days, :hours or :minutes with
3332 a format string. The time duration is formatted using the
3333 largest time unit which gives a non-zero integer part. If all
3334 specified formats have zero integer part, the smallest time unit
3335 is used."
3336 :group 'org-time
3337 :type '(choice (string :tag "Format string")
3338 (set (group :inline t (const :tag "Years" :years)
3339 (string :tag "Format string"))
3340 (group :inline t (const :tag "Months" :months)
3341 (string :tag "Format string"))
3342 (group :inline t (const :tag "Weeks" :weeks)
3343 (string :tag "Format string"))
3344 (group :inline t (const :tag "Days" :days)
3345 (string :tag "Format string"))
3346 (group :inline t (const :tag "Hours" :hours)
3347 (string :tag "Format string"))
3348 (group :inline t (const :tag "Minutes" :minutes)
3349 (string :tag "Format string")))))
3351 (defcustom org-deadline-warning-days 14
3352 "Number of days before expiration during which a deadline becomes active.
3353 This variable governs the display in sparse trees and in the agenda.
3354 When 0 or negative, it means use this number (the absolute value of it)
3355 even if a deadline has a different individual lead time specified.
3357 Custom commands can set this variable in the options section."
3358 :group 'org-time
3359 :group 'org-agenda-daily/weekly
3360 :type 'integer)
3362 (defcustom org-scheduled-delay-days 0
3363 "Number of days before a scheduled item becomes active.
3364 This variable governs the display in sparse trees and in the agenda.
3365 The default value (i.e. 0) means: don't delay scheduled item.
3366 When negative, it means use this number (the absolute value of it)
3367 even if a scheduled item has a different individual delay time
3368 specified.
3370 Custom commands can set this variable in the options section."
3371 :group 'org-time
3372 :group 'org-agenda-daily/weekly
3373 :version "24.4"
3374 :package-version '(Org . "8.0")
3375 :type 'integer)
3377 (defcustom org-read-date-prefer-future t
3378 "Non-nil means assume future for incomplete date input from user.
3379 This affects the following situations:
3380 1. The user gives a month but not a year.
3381 For example, if it is April and you enter \"feb 2\", this will be read
3382 as Feb 2, *next* year. \"May 5\", however, will be this year.
3383 2. The user gives a day, but no month.
3384 For example, if today is the 15th, and you enter \"3\", Org-mode will
3385 read this as the third of *next* month. However, if you enter \"17\",
3386 it will be considered as *this* month.
3388 If you set this variable to the symbol `time', then also the following
3389 will work:
3391 3. If the user gives a time.
3392 If the time is before now, it will be interpreted as tomorrow.
3394 Currently none of this works for ISO week specifications.
3396 When this option is nil, the current day, month and year will always be
3397 used as defaults.
3399 See also `org-agenda-jump-prefer-future'."
3400 :group 'org-time
3401 :type '(choice
3402 (const :tag "Never" nil)
3403 (const :tag "Check month and day" t)
3404 (const :tag "Check month, day, and time" time)))
3406 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3407 "Should the agenda jump command prefer the future for incomplete dates?
3408 The default is to do the same as configured in `org-read-date-prefer-future'.
3409 But you can also set a deviating value here.
3410 This may t or nil, or the symbol `org-read-date-prefer-future'."
3411 :group 'org-agenda
3412 :group 'org-time
3413 :version "24.1"
3414 :type '(choice
3415 (const :tag "Use org-read-date-prefer-future"
3416 org-read-date-prefer-future)
3417 (const :tag "Never" nil)
3418 (const :tag "Always" t)))
3420 (defcustom org-read-date-force-compatible-dates t
3421 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3423 Depending on the system Emacs is running on, certain dates cannot
3424 be represented with the type used internally to represent time.
3425 Dates between 1970-1-1 and 2038-1-1 can always be represented
3426 correctly. Some systems allow for earlier dates, some for later,
3427 some for both. One way to find out it to insert any date into an
3428 Org buffer, putting the cursor on the year and hitting S-up and
3429 S-down to test the range.
3431 When this variable is set to t, the date/time prompt will not let
3432 you specify dates outside the 1970-2037 range, so it is certain that
3433 these dates will work in whatever version of Emacs you are
3434 running, and also that you can move a file from one Emacs implementation
3435 to another. WHenever Org is forcing the year for you, it will display
3436 a message and beep.
3438 When this variable is nil, Org will check if the date is
3439 representable in the specific Emacs implementation you are using.
3440 If not, it will force a year, usually the current year, and beep
3441 to remind you. Currently this setting is not recommended because
3442 the likelihood that you will open your Org files in an Emacs that
3443 has limited date range is not negligible.
3445 A workaround for this problem is to use diary sexp dates for time
3446 stamps outside of this range."
3447 :group 'org-time
3448 :version "24.1"
3449 :type 'boolean)
3451 (defcustom org-read-date-display-live t
3452 "Non-nil means display current interpretation of date prompt live.
3453 This display will be in an overlay, in the minibuffer."
3454 :group 'org-time
3455 :type 'boolean)
3457 (defcustom org-read-date-popup-calendar t
3458 "Non-nil means pop up a calendar when prompting for a date.
3459 In the calendar, the date can be selected with mouse-1. However, the
3460 minibuffer will also be active, and you can simply enter the date as well.
3461 When nil, only the minibuffer will be available."
3462 :group 'org-time
3463 :type 'boolean)
3464 (defvaralias 'org-popup-calendar-for-date-prompt
3465 'org-read-date-popup-calendar)
3467 (defcustom org-extend-today-until 0
3468 "The hour when your day really ends. Must be an integer.
3469 This has influence for the following applications:
3470 - When switching the agenda to \"today\". It it is still earlier than
3471 the time given here, the day recognized as TODAY is actually yesterday.
3472 - When a date is read from the user and it is still before the time given
3473 here, the current date and time will be assumed to be yesterday, 23:59.
3474 Also, timestamps inserted in capture templates follow this rule.
3476 IMPORTANT: This is a feature whose implementation is and likely will
3477 remain incomplete. Really, it is only here because past midnight seems to
3478 be the favorite working time of John Wiegley :-)"
3479 :group 'org-time
3480 :type 'integer)
3482 (defcustom org-use-effective-time nil
3483 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3484 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3485 \"effective time\" of any timestamps between midnight and 8am will be
3486 23:59 of the previous day."
3487 :group 'org-time
3488 :version "24.1"
3489 :type 'boolean)
3491 (defcustom org-use-last-clock-out-time-as-effective-time nil
3492 "When non-nil, use the last clock out time for `org-todo'.
3493 Note that this option has precedence over the combined use of
3494 `org-use-effective-time' and `org-extend-today-until'."
3495 :group 'org-time
3496 :version "24.4"
3497 :package-version '(Org . "8.0")
3498 :type 'boolean)
3500 (defcustom org-edit-timestamp-down-means-later nil
3501 "Non-nil means S-down will increase the time in a time stamp.
3502 When nil, S-up will increase."
3503 :group 'org-time
3504 :type 'boolean)
3506 (defcustom org-calendar-follow-timestamp-change t
3507 "Non-nil means make the calendar window follow timestamp changes.
3508 When a timestamp is modified and the calendar window is visible, it will be
3509 moved to the new date."
3510 :group 'org-time
3511 :type 'boolean)
3513 (defgroup org-tags nil
3514 "Options concerning tags in Org-mode."
3515 :tag "Org Tags"
3516 :group 'org)
3518 (defcustom org-tag-alist nil
3519 "Default tags available in Org files.
3521 The value of this variable is an alist. Associations either:
3523 (TAG)
3524 (TAG . SELECT)
3525 (SPECIAL)
3527 where TAG is a tag as a string, SELECT is a character, used to
3528 select that tag through the fast tag selection interface, and
3529 SPECIAL is one of the following keywords: `:startgroup',
3530 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3531 `:newline'. These keywords are used to define a hierarchy of
3532 tags. See manual for details.
3534 When this variable is nil, Org mode bases tag input on what is
3535 already in the buffer. The value can be overridden locally by
3536 using a TAGS keyword, e.g.,
3538 #+TAGS: tag1 tag2
3540 See also `org-tag-persistent-alist' to sidestep this behavior."
3541 :group 'org-tags
3542 :type '(repeat
3543 (choice
3544 (cons (string :tag "Tag name")
3545 (character :tag "Access char"))
3546 (const :tag "Start radio group" (:startgroup))
3547 (const :tag "Start tag group, non distinct" (:startgrouptag))
3548 (const :tag "Group tags delimiter" (:grouptags))
3549 (const :tag "End radio group" (:endgroup))
3550 (const :tag "End tag group, non distinct" (:endgrouptag))
3551 (const :tag "New line" (:newline)))))
3553 (defcustom org-tag-persistent-alist nil
3554 "Tags always available in Org files.
3556 The value of this variable is an alist. Associations either:
3558 (TAG)
3559 (TAG . SELECT)
3560 (SPECIAL)
3562 where TAG is a tag as a string, SELECT is a character, used to
3563 select that tag through the fast tag selection interface, and
3564 SPECIAL is one of the following keywords: `:startgroup',
3565 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3566 `:newline'. These keywords are used to define a hierarchy of
3567 tags. See manual for details.
3569 Unlike to `org-tag-alist', tags defined in this variable do not
3570 depend on a local TAGS keyword. Instead, to disable these tags
3571 on a per-file basis, insert anywhere in the file:
3573 #+STARTUP: noptag"
3574 :group 'org-tags
3575 :type '(repeat
3576 (choice
3577 (cons (string :tag "Tag name")
3578 (character :tag "Access char"))
3579 (const :tag "Start radio group" (:startgroup))
3580 (const :tag "Start tag group, non distinct" (:startgrouptag))
3581 (const :tag "Group tags delimiter" (:grouptags))
3582 (const :tag "End radio group" (:endgroup))
3583 (const :tag "End tag group, non distinct" (:endgrouptag))
3584 (const :tag "New line" (:newline)))))
3586 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3587 "If non-nil, always offer completion for all tags of all agenda files.
3588 Instead of customizing this variable directly, you might want to
3589 set it locally for capture buffers, because there no list of
3590 tags in that file can be created dynamically (there are none).
3592 (add-hook \\='org-capture-mode-hook
3593 (lambda ()
3594 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3595 :group 'org-tags
3596 :version "24.1"
3597 :type 'boolean)
3599 (defvar org-file-tags nil
3600 "List of tags that can be inherited by all entries in the file.
3601 The tags will be inherited if the variable `org-use-tag-inheritance'
3602 says they should be.
3603 This variable is populated from #+FILETAGS lines.")
3605 (defcustom org-use-fast-tag-selection 'auto
3606 "Non-nil means use fast tag selection scheme.
3607 This is a special interface to select and deselect tags with single keys.
3608 When nil, fast selection is never used.
3609 When the symbol `auto', fast selection is used if and only if selection
3610 characters for tags have been configured, either through the variable
3611 `org-tag-alist' or through a #+TAGS line in the buffer.
3612 When t, fast selection is always used and selection keys are assigned
3613 automatically if necessary."
3614 :group 'org-tags
3615 :type '(choice
3616 (const :tag "Always" t)
3617 (const :tag "Never" nil)
3618 (const :tag "When selection characters are configured" auto)))
3620 (defcustom org-fast-tag-selection-single-key nil
3621 "Non-nil means fast tag selection exits after first change.
3622 When nil, you have to press RET to exit it.
3623 During fast tag selection, you can toggle this flag with `C-c'.
3624 This variable can also have the value `expert'. In this case, the window
3625 displaying the tags menu is not even shown, until you press C-c again."
3626 :group 'org-tags
3627 :type '(choice
3628 (const :tag "No" nil)
3629 (const :tag "Yes" t)
3630 (const :tag "Expert" expert)))
3632 (defvar org-fast-tag-selection-include-todo nil
3633 "Non-nil means fast tags selection interface will also offer TODO states.
3634 This is an undocumented feature, you should not rely on it.")
3636 (defcustom org-tags-column -77
3637 "The column to which tags should be indented in a headline.
3638 If this number is positive, it specifies the column. If it is negative,
3639 it means that the tags should be flushright to that column. For example,
3640 -80 works well for a normal 80 character screen.
3641 When 0, place tags directly after headline text, with only one space in
3642 between."
3643 :group 'org-tags
3644 :type 'integer)
3646 (defcustom org-auto-align-tags t
3647 "Non-nil keeps tags aligned when modifying headlines.
3648 Some operations (i.e. demoting) change the length of a headline and
3649 therefore shift the tags around. With this option turned on, after
3650 each such operation the tags are again aligned to `org-tags-column'."
3651 :group 'org-tags
3652 :type 'boolean)
3654 (defcustom org-use-tag-inheritance t
3655 "Non-nil means tags in levels apply also for sublevels.
3656 When nil, only the tags directly given in a specific line apply there.
3657 This may also be a list of tags that should be inherited, or a regexp that
3658 matches tags that should be inherited. Additional control is possible
3659 with the variable `org-tags-exclude-from-inheritance' which gives an
3660 explicit list of tags to be excluded from inheritance, even if the value of
3661 `org-use-tag-inheritance' would select it for inheritance.
3663 If this option is t, a match early-on in a tree can lead to a large
3664 number of matches in the subtree when constructing the agenda or creating
3665 a sparse tree. If you only want to see the first match in a tree during
3666 a search, check out the variable `org-tags-match-list-sublevels'."
3667 :group 'org-tags
3668 :type '(choice
3669 (const :tag "Not" nil)
3670 (const :tag "Always" t)
3671 (repeat :tag "Specific tags" (string :tag "Tag"))
3672 (regexp :tag "Tags matched by regexp")))
3674 (defcustom org-tags-exclude-from-inheritance nil
3675 "List of tags that should never be inherited.
3676 This is a way to exclude a few tags from inheritance. For way to do
3677 the opposite, to actively allow inheritance for selected tags,
3678 see the variable `org-use-tag-inheritance'."
3679 :group 'org-tags
3680 :type '(repeat (string :tag "Tag")))
3682 (defun org-tag-inherit-p (tag)
3683 "Check if TAG is one that should be inherited."
3684 (cond
3685 ((member tag org-tags-exclude-from-inheritance) nil)
3686 ((eq org-use-tag-inheritance t) t)
3687 ((not org-use-tag-inheritance) nil)
3688 ((stringp org-use-tag-inheritance)
3689 (string-match org-use-tag-inheritance tag))
3690 ((listp org-use-tag-inheritance)
3691 (member tag org-use-tag-inheritance))
3692 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3694 (defcustom org-tags-match-list-sublevels t
3695 "Non-nil means list also sublevels of headlines matching a search.
3696 This variable applies to tags/property searches, and also to stuck
3697 projects because this search is based on a tags match as well.
3699 When set to the symbol `indented', sublevels are indented with
3700 leading dots.
3702 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3703 the sublevels of a headline matching a tag search often also match
3704 the same search. Listing all of them can create very long lists.
3705 Setting this variable to nil causes subtrees of a match to be skipped.
3707 This variable is semi-obsolete and probably should always be true. It
3708 is better to limit inheritance to certain tags using the variables
3709 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3710 :group 'org-tags
3711 :type '(choice
3712 (const :tag "No, don't list them" nil)
3713 (const :tag "Yes, do list them" t)
3714 (const :tag "List them, indented with leading dots" indented)))
3716 (defcustom org-tags-sort-function nil
3717 "When set, tags are sorted using this function as a comparator."
3718 :group 'org-tags
3719 :type '(choice
3720 (const :tag "No sorting" nil)
3721 (const :tag "Alphabetical" string<)
3722 (const :tag "Reverse alphabetical" string>)
3723 (function :tag "Custom function" nil)))
3725 (defvar org-tags-history nil
3726 "History of minibuffer reads for tags.")
3727 (defvar org-last-tags-completion-table nil
3728 "The last used completion table for tags.")
3729 (defvar org-after-tags-change-hook nil
3730 "Hook that is run after the tags in a line have changed.")
3732 (defgroup org-properties nil
3733 "Options concerning properties in Org-mode."
3734 :tag "Org Properties"
3735 :group 'org)
3737 (defcustom org-property-format "%-10s %s"
3738 "How property key/value pairs should be formatted by `indent-line'.
3739 When `indent-line' hits a property definition, it will format the line
3740 according to this format, mainly to make sure that the values are
3741 lined-up with respect to each other."
3742 :group 'org-properties
3743 :type 'string)
3745 (defcustom org-properties-postprocess-alist nil
3746 "Alist of properties and functions to adjust inserted values.
3747 Elements of this alist must be of the form
3749 ([string] [function])
3751 where [string] must be a property name and [function] must be a
3752 lambda expression: this lambda expression must take one argument,
3753 the value to adjust, and return the new value as a string.
3755 For example, this element will allow the property \"Remaining\"
3756 to be updated wrt the relation between the \"Effort\" property
3757 and the clock summary:
3759 ((\"Remaining\" (lambda(value)
3760 (let ((clocksum (org-clock-sum-current-item))
3761 (effort (org-duration-string-to-minutes
3762 (org-entry-get (point) \"Effort\"))))
3763 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3764 :group 'org-properties
3765 :version "24.1"
3766 :type '(alist :key-type (string :tag "Property")
3767 :value-type (function :tag "Function")))
3769 (defcustom org-use-property-inheritance nil
3770 "Non-nil means properties apply also for sublevels.
3772 This setting is chiefly used during property searches. Turning it on can
3773 cause significant overhead when doing a search, which is why it is not
3774 on by default.
3776 When nil, only the properties directly given in the current entry count.
3777 When t, every property is inherited. The value may also be a list of
3778 properties that should have inheritance, or a regular expression matching
3779 properties that should be inherited.
3781 However, note that some special properties use inheritance under special
3782 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3783 and the properties ending in \"_ALL\" when they are used as descriptor
3784 for valid values of a property.
3786 Note for programmers:
3787 When querying an entry with `org-entry-get', you can control if inheritance
3788 should be used. By default, `org-entry-get' looks only at the local
3789 properties. You can request inheritance by setting the inherit argument
3790 to t (to force inheritance) or to `selective' (to respect the setting
3791 in this variable)."
3792 :group 'org-properties
3793 :type '(choice
3794 (const :tag "Not" nil)
3795 (const :tag "Always" t)
3796 (repeat :tag "Specific properties" (string :tag "Property"))
3797 (regexp :tag "Properties matched by regexp")))
3799 (defun org-property-inherit-p (property)
3800 "Check if PROPERTY is one that should be inherited."
3801 (cond
3802 ((eq org-use-property-inheritance t) t)
3803 ((not org-use-property-inheritance) nil)
3804 ((stringp org-use-property-inheritance)
3805 (string-match org-use-property-inheritance property))
3806 ((listp org-use-property-inheritance)
3807 (member property org-use-property-inheritance))
3808 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3810 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3811 "The default column format, if no other format has been defined.
3812 This variable can be set on the per-file basis by inserting a line
3814 #+COLUMNS: %25ITEM ....."
3815 :group 'org-properties
3816 :type 'string)
3818 (defcustom org-columns-ellipses ".."
3819 "The ellipses to be used when a field in column view is truncated.
3820 When this is the empty string, as many characters as possible are shown,
3821 but then there will be no visual indication that the field has been truncated.
3822 When this is a string of length N, the last N characters of a truncated
3823 field are replaced by this string. If the column is narrower than the
3824 ellipses string, only part of the ellipses string will be shown."
3825 :group 'org-properties
3826 :type 'string)
3828 (defconst org-global-properties-fixed
3829 '(("VISIBILITY_ALL" . "folded children content all")
3830 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3831 "List of property/value pairs that can be inherited by any entry.
3833 These are fixed values, for the preset properties. The user variable
3834 that can be used to add to this list is `org-global-properties'.
3836 The entries in this list are cons cells where the car is a property
3837 name and cdr is a string with the value. If the value represents
3838 multiple items like an \"_ALL\" property, separate the items by
3839 spaces.")
3841 (defcustom org-global-properties nil
3842 "List of property/value pairs that can be inherited by any entry.
3844 This list will be combined with the constant `org-global-properties-fixed'.
3846 The entries in this list are cons cells where the car is a property
3847 name and cdr is a string with the value.
3849 You can set buffer-local values for the same purpose in the variable
3850 `org-file-properties' this by adding lines like
3852 #+PROPERTY: NAME VALUE"
3853 :group 'org-properties
3854 :type '(repeat
3855 (cons (string :tag "Property")
3856 (string :tag "Value"))))
3858 (defvar-local org-file-properties nil
3859 "List of property/value pairs that can be inherited by any entry.
3860 Valid for the current buffer.
3861 This variable is populated from #+PROPERTY lines.")
3863 (defgroup org-agenda nil
3864 "Options concerning agenda views in Org-mode."
3865 :tag "Org Agenda"
3866 :group 'org)
3868 (defvar-local org-category nil
3869 "Variable used by org files to set a category for agenda display.
3870 Such files should use a file variable to set it, for example
3872 # -*- mode: org; org-category: \"ELisp\"
3874 or contain a special line
3876 #+CATEGORY: ELisp
3878 If the file does not specify a category, then file's base name
3879 is used instead.")
3880 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3882 (defcustom org-agenda-files nil
3883 "The files to be used for agenda display.
3884 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3885 \\[org-remove-file]. You can also use customize to edit the list.
3887 If an entry is a directory, all files in that directory that are matched by
3888 `org-agenda-file-regexp' will be part of the file list.
3890 If the value of the variable is not a list but a single file name, then
3891 the list of agenda files is actually stored and maintained in that file, one
3892 agenda file per line. In this file paths can be given relative to
3893 `org-directory'. Tilde expansion and environment variable substitution
3894 are also made."
3895 :group 'org-agenda
3896 :type '(choice
3897 (repeat :tag "List of files and directories" file)
3898 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3900 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3901 "Regular expression to match files for `org-agenda-files'.
3902 If any element in the list in that variable contains a directory instead
3903 of a normal file, all files in that directory that are matched by this
3904 regular expression will be included."
3905 :group 'org-agenda
3906 :type 'regexp)
3908 (defcustom org-agenda-text-search-extra-files nil
3909 "List of extra files to be searched by text search commands.
3910 These files will be searched in addition to the agenda files by the
3911 commands `org-search-view' (`\\[org-agenda] s') \
3912 and `org-occur-in-agenda-files'.
3913 Note that these files will only be searched for text search commands,
3914 not for the other agenda views like todo lists, tag searches or the weekly
3915 agenda. This variable is intended to list notes and possibly archive files
3916 that should also be searched by these two commands.
3917 In fact, if the first element in the list is the symbol `agenda-archives',
3918 then all archive files of all agenda files will be added to the search
3919 scope."
3920 :group 'org-agenda
3921 :type '(set :greedy t
3922 (const :tag "Agenda Archives" agenda-archives)
3923 (repeat :inline t (file))))
3925 (defvaralias 'org-agenda-multi-occur-extra-files
3926 'org-agenda-text-search-extra-files)
3928 (defcustom org-agenda-skip-unavailable-files nil
3929 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3930 A nil value means to remove them, after a query, from the list."
3931 :group 'org-agenda
3932 :type 'boolean)
3934 (defcustom org-calendar-to-agenda-key [?c]
3935 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3936 The command `org-calendar-goto-agenda' will be bound to this key. The
3937 default is the character `c' because then `c' can be used to switch back and
3938 forth between agenda and calendar."
3939 :group 'org-agenda
3940 :type 'sexp)
3942 (defcustom org-calendar-insert-diary-entry-key [?i]
3943 "The key to be installed in `calendar-mode-map' for adding diary entries.
3944 This option is irrelevant until `org-agenda-diary-file' has been configured
3945 to point to an Org-mode file. When that is the case, the command
3946 `org-agenda-diary-entry' will be bound to the key given here, by default
3947 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3948 if you want to continue doing this, you need to change this to a different
3949 key."
3950 :group 'org-agenda
3951 :type 'sexp)
3953 (defcustom org-agenda-diary-file 'diary-file
3954 "File to which to add new entries with the `i' key in agenda and calendar.
3955 When this is the symbol `diary-file', the functionality in the Emacs
3956 calendar will be used to add entries to the `diary-file'. But when this
3957 points to a file, `org-agenda-diary-entry' will be used instead."
3958 :group 'org-agenda
3959 :type '(choice
3960 (const :tag "The standard Emacs diary file" diary-file)
3961 (file :tag "Special Org file diary entries")))
3963 (eval-after-load "calendar"
3964 '(progn
3965 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3966 'org-calendar-goto-agenda)
3967 (add-hook 'calendar-mode-hook
3968 (lambda ()
3969 (unless (eq org-agenda-diary-file 'diary-file)
3970 (define-key calendar-mode-map
3971 org-calendar-insert-diary-entry-key
3972 'org-agenda-diary-entry))))))
3974 (defgroup org-latex nil
3975 "Options for embedding LaTeX code into Org-mode."
3976 :tag "Org LaTeX"
3977 :group 'org)
3979 (defcustom org-format-latex-options
3980 '(:foreground default :background default :scale 1.0
3981 :html-foreground "Black" :html-background "Transparent"
3982 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3983 "Options for creating images from LaTeX fragments.
3984 This is a property list with the following properties:
3985 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3986 `default' means use the foreground of the default face.
3987 `auto' means use the foreground from the text face.
3988 :background the background color, or \"Transparent\".
3989 `default' means use the background of the default face.
3990 `auto' means use the background from the text face.
3991 :scale a scaling factor for the size of the images, to get more pixels
3992 :html-foreground, :html-background, :html-scale
3993 the same numbers for HTML export.
3994 :matchers a list indicating which matchers should be used to
3995 find LaTeX fragments. Valid members of this list are:
3996 \"begin\" find environments
3997 \"$1\" find single characters surrounded by $.$
3998 \"$\" find math expressions surrounded by $...$
3999 \"$$\" find math expressions surrounded by $$....$$
4000 \"\\(\" find math expressions surrounded by \\(...\\)
4001 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4002 :group 'org-latex
4003 :type 'plist)
4005 (defcustom org-format-latex-signal-error t
4006 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4007 When nil, just push out a message."
4008 :group 'org-latex
4009 :version "24.1"
4010 :type 'boolean)
4012 (defcustom org-latex-to-mathml-jar-file nil
4013 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4014 Use this to specify additional executable file say a jar file.
4016 When using MathToWeb as the converter, specify the full-path to
4017 your mathtoweb.jar file."
4018 :group 'org-latex
4019 :version "24.1"
4020 :type '(choice
4021 (const :tag "None" nil)
4022 (file :tag "JAR file" :must-match t)))
4024 (defcustom org-latex-to-mathml-convert-command nil
4025 "Command to convert LaTeX fragments to MathML.
4026 Replace format-specifiers in the command as noted below and use
4027 `shell-command' to convert LaTeX to MathML.
4028 %j: Executable file in fully expanded form as specified by
4029 `org-latex-to-mathml-jar-file'.
4030 %I: Input LaTeX file in fully expanded form.
4031 %i: The latex fragment to be converted.
4032 %o: Output MathML file.
4034 This command is used by `org-create-math-formula'.
4036 When using MathToWeb as the converter, set this option to
4037 \"java -jar %j -unicode -force -df %o %I\".
4039 When using LaTeXML set this option to
4040 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type '(choice
4044 (const :tag "None" nil)
4045 (string :tag "\nShell command")))
4047 (defcustom org-preview-latex-default-process 'dvipng
4048 "The default process to convert LaTeX fragments to image files.
4049 All available processes and theirs documents can be found in
4050 `org-preview-latex-process-alist', which see."
4051 :group 'org-latex
4052 :version "25.2"
4053 :package-version '(Org . "9.0")
4054 :type 'symbol)
4056 (defcustom org-preview-latex-process-alist
4057 '((dvipng
4058 :programs ("latex" "dvipng" "gs")
4059 :description "dvi > png"
4060 :message "you need to install the programs: latex, dvipng and ghostscript."
4061 :image-input-type "dvi"
4062 :image-output-type "png"
4063 :image-size-adjust (1.0 . 1.0)
4064 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4065 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4066 (dvisvgm
4067 :programs ("latex" "dvisvgm" "gs")
4068 :description "dvi > svg"
4069 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4070 :use-xcolor t
4071 :image-input-type "dvi"
4072 :image-output-type "svg"
4073 :image-size-adjust (1.7 . 1.5)
4074 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4075 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4076 (imagemagick
4077 :programs ("latex" "convert" "gs")
4078 :description "pdf > png"
4079 :message
4080 "you need to install the programs: latex, imagemagick and ghostscript."
4081 :use-xcolor t
4082 :image-input-type "pdf"
4083 :image-output-type "png"
4084 :image-size-adjust (1.0 . 1.0)
4085 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4086 :image-converter
4087 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4088 "Definitions of external processes for LaTeX previewing.
4089 Org mode can use some external commands to generate TeX snippet's images for
4090 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4091 `org-create-formula-image' how to call them.
4093 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4094 PROPERTIES accepts the following attributes:
4096 :programs list of strings, required programs.
4097 :description string, describe the process.
4098 :message string, message it when required programs cannot be found.
4099 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4100 :image-output-type string, output file type of image converter (e.g., \"png\").
4101 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4102 deal with background and foreground color of image.
4103 Otherwise, dvipng style background and foregroud color
4104 format are generated. You may then refer to them in
4105 command options with \"%F\" and \"%B\".
4106 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4107 image size showed in buffer and the cdr element is for
4108 HTML file. This option is only useful for process
4109 developers, users should use variable
4110 `org-format-latex-options' instead.
4111 :post-clean list of strings, files matched are to be cleaned up once
4112 the image is generated. When nil, the files with \".dvi\",
4113 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4114 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4115 be cleaned up.
4116 :latex-header list of strings, the LaTeX header of the snippet file.
4117 When nil, the fallback value is used instead, which is
4118 controlled by `org-format-latex-header',
4119 `org-latex-default-packages-alist' and
4120 `org-latex-packages-alist', which see.
4121 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4122 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4123 replaced with values defined below.
4124 :image-converter list of image converter commands strings. Each of them is
4125 given to the shell and supports any of the following
4126 place-holders defined below.
4128 Place-holders used by `:image-converter' and `:latex-compiler':
4130 %f input file name.
4131 %b base name of input file.
4132 %o base directory of input file.
4134 Place-holders only used by `:image-converter':
4136 %F foreground of image
4137 %B background of image
4138 %D dpi, which is used to adjust image size by some processing commands.
4139 %S the image size scale ratio, which is used to adjust image size by some
4140 processing commands."
4141 :group 'org-latex
4142 :version "25.2"
4143 :package-version '(Org . "9.0")
4144 :type '(alist :tag "LaTeX to image backends"
4145 :value-type (plist)))
4147 (defcustom org-preview-latex-image-directory "ltximg/"
4148 "Path to store latex preview images.
4149 A relative path here creates many directories relative to the
4150 processed org files paths. An absolute path puts all preview
4151 images at the same place."
4152 :group 'org-latex
4153 :version "25.1"
4154 :package-version '(Org . "9.0")
4155 :type 'string)
4157 (defun org-format-latex-mathml-available-p ()
4158 "Return t if `org-latex-to-mathml-convert-command' is usable."
4159 (save-match-data
4160 (when (and (boundp 'org-latex-to-mathml-convert-command)
4161 org-latex-to-mathml-convert-command)
4162 (let ((executable (car (split-string
4163 org-latex-to-mathml-convert-command))))
4164 (when (executable-find executable)
4165 (if (string-match
4166 "%j" org-latex-to-mathml-convert-command)
4167 (file-readable-p org-latex-to-mathml-jar-file)
4168 t))))))
4170 (defcustom org-format-latex-header "\\documentclass{article}
4171 \\usepackage[usenames]{color}
4172 \[PACKAGES]
4173 \[DEFAULT-PACKAGES]
4174 \\pagestyle{empty} % do not remove
4175 % The settings below are copied from fullpage.sty
4176 \\setlength{\\textwidth}{\\paperwidth}
4177 \\addtolength{\\textwidth}{-3cm}
4178 \\setlength{\\oddsidemargin}{1.5cm}
4179 \\addtolength{\\oddsidemargin}{-2.54cm}
4180 \\setlength{\\evensidemargin}{\\oddsidemargin}
4181 \\setlength{\\textheight}{\\paperheight}
4182 \\addtolength{\\textheight}{-\\headheight}
4183 \\addtolength{\\textheight}{-\\headsep}
4184 \\addtolength{\\textheight}{-\\footskip}
4185 \\addtolength{\\textheight}{-3cm}
4186 \\setlength{\\topmargin}{1.5cm}
4187 \\addtolength{\\topmargin}{-2.54cm}"
4188 "The document header used for processing LaTeX fragments.
4189 It is imperative that this header make sure that no page number
4190 appears on the page. The package defined in the variables
4191 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4192 will either replace the placeholder \"[PACKAGES]\" in this
4193 header, or they will be appended."
4194 :group 'org-latex
4195 :type 'string)
4197 (defun org-set-packages-alist (var val)
4198 "Set the packages alist and make sure it has 3 elements per entry."
4199 (set var (mapcar (lambda (x)
4200 (if (and (consp x) (= (length x) 2))
4201 (list (car x) (nth 1 x) t)
4203 val)))
4205 (defun org-get-packages-alist (var)
4206 "Get the packages alist and make sure it has 3 elements per entry."
4207 (mapcar (lambda (x)
4208 (if (and (consp x) (= (length x) 2))
4209 (list (car x) (nth 1 x) t)
4211 (default-value var)))
4213 (defcustom org-latex-default-packages-alist
4214 '(("AUTO" "inputenc" t ("pdflatex"))
4215 ("T1" "fontenc" t ("pdflatex"))
4216 ("" "graphicx" t)
4217 ("" "grffile" t)
4218 ("" "longtable" nil)
4219 ("" "wrapfig" nil)
4220 ("" "rotating" nil)
4221 ("normalem" "ulem" t)
4222 ("" "amsmath" t)
4223 ("" "textcomp" t)
4224 ("" "amssymb" t)
4225 ("" "capt-of" nil)
4226 ("" "hyperref" nil))
4227 "Alist of default packages to be inserted in the header.
4229 Change this only if one of the packages here causes an
4230 incompatibility with another package you are using.
4232 The packages in this list are needed by one part or another of
4233 Org mode to function properly:
4235 - inputenc, fontenc: for basic font and character selection
4236 - graphicx: for including images
4237 - grffile: allow periods and spaces in graphics file names
4238 - longtable: For multipage tables
4239 - wrapfig: for figure placement
4240 - rotating: for sideways figures and tables
4241 - ulem: for underline and strike-through
4242 - amsmath: for subscript and superscript and math environments
4243 - textcomp, amssymb: for various symbols used
4244 for interpreting the entities in `org-entities'. You can skip
4245 some of these packages if you don't use any of their symbols.
4246 - capt-of: for captions outside of floats
4247 - hyperref: for cross references
4249 Therefore you should not modify this variable unless you know
4250 what you are doing. The one reason to change it anyway is that
4251 you might be loading some other package that conflicts with one
4252 of the default packages. Each element is either a cell or
4253 a string.
4255 A cell is of the format
4257 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4259 If SNIPPET-FLAG is non-nil, the package also needs to be included
4260 when compiling LaTeX snippets into images for inclusion into
4261 non-LaTeX output. COMPILERS is a list of compilers that should
4262 include the package, see `org-latex-compiler'. If the document
4263 compiler is not in the list, and the list is non-nil, the package
4264 will not be inserted in the final document.
4266 A string will be inserted as-is in the header of the document."
4267 :group 'org-latex
4268 :group 'org-export-latex
4269 :set 'org-set-packages-alist
4270 :get 'org-get-packages-alist
4271 :version "25.1"
4272 :package-version '(Org . "8.3")
4273 :type '(repeat
4274 (choice
4275 (list :tag "options/package pair"
4276 (string :tag "options")
4277 (string :tag "package")
4278 (boolean :tag "Snippet"))
4279 (string :tag "A line of LaTeX"))))
4281 (defcustom org-latex-packages-alist nil
4282 "Alist of packages to be inserted in every LaTeX header.
4284 These will be inserted after `org-latex-default-packages-alist'.
4285 Each element is either a cell or a string.
4287 A cell is of the format:
4289 (\"options\" \"package\" SNIPPET-FLAG)
4291 SNIPPET-FLAG, when non-nil, indicates that this package is also
4292 needed when turning LaTeX snippets into images for inclusion into
4293 non-LaTeX output.
4295 A string will be inserted as-is in the header of the document.
4297 Make sure that you only list packages here which:
4299 - you want in every file;
4300 - do not conflict with the setup in `org-format-latex-header';
4301 - do not conflict with the default packages in
4302 `org-latex-default-packages-alist'."
4303 :group 'org-latex
4304 :group 'org-export-latex
4305 :set 'org-set-packages-alist
4306 :get 'org-get-packages-alist
4307 :type '(repeat
4308 (choice
4309 (list :tag "options/package pair"
4310 (string :tag "options")
4311 (string :tag "package")
4312 (boolean :tag "Snippet"))
4313 (string :tag "A line of LaTeX"))))
4315 (defgroup org-appearance nil
4316 "Settings for Org-mode appearance."
4317 :tag "Org Appearance"
4318 :group 'org)
4320 (defcustom org-level-color-stars-only nil
4321 "Non-nil means fontify only the stars in each headline.
4322 When nil, the entire headline is fontified.
4323 Changing it requires restart of `font-lock-mode' to become effective
4324 also in regions already fontified."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-hide-leading-stars nil
4329 "Non-nil means hide the first N-1 stars in a headline.
4330 This works by using the face `org-hide' for these stars. This
4331 face is white for a light background, and black for a dark
4332 background. You may have to customize the face `org-hide' to
4333 make this work.
4334 Changing it requires restart of `font-lock-mode' to become effective
4335 also in regions already fontified.
4336 You may also set this on a per-file basis by adding one of the following
4337 lines to the buffer:
4339 #+STARTUP: hidestars
4340 #+STARTUP: showstars"
4341 :group 'org-appearance
4342 :type 'boolean)
4344 (defcustom org-hidden-keywords nil
4345 "List of symbols corresponding to keywords to be hidden the org buffer.
4346 For example, a value \\='(title) for this list will make the document's title
4347 appear in the buffer without the initial #+TITLE: keyword."
4348 :group 'org-appearance
4349 :version "24.1"
4350 :type '(set (const :tag "#+AUTHOR" author)
4351 (const :tag "#+DATE" date)
4352 (const :tag "#+EMAIL" email)
4353 (const :tag "#+TITLE" title)))
4355 (defcustom org-custom-properties nil
4356 "List of properties (as strings) with a special meaning.
4357 The default use of these custom properties is to let the user
4358 hide them with `org-toggle-custom-properties-visibility'."
4359 :group 'org-properties
4360 :group 'org-appearance
4361 :version "24.3"
4362 :type '(repeat (string :tag "Property Name")))
4364 (defcustom org-fontify-done-headline nil
4365 "Non-nil means change the face of a headline if it is marked DONE.
4366 Normally, only the TODO/DONE keyword indicates the state of a headline.
4367 When this is non-nil, the headline after the keyword is set to the
4368 `org-headline-done' as an additional indication."
4369 :group 'org-appearance
4370 :type 'boolean)
4372 (defcustom org-fontify-emphasized-text t
4373 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4374 Changing this variable requires a restart of Emacs to take effect."
4375 :group 'org-appearance
4376 :type 'boolean)
4378 (defcustom org-fontify-whole-heading-line nil
4379 "Non-nil means fontify the whole line for headings.
4380 This is useful when setting a background color for the
4381 org-level-* faces."
4382 :group 'org-appearance
4383 :type 'boolean)
4385 (defcustom org-highlight-latex-and-related nil
4386 "Non-nil means highlight LaTeX related syntax in the buffer.
4387 When non nil, the value should be a list containing any of the
4388 following symbols:
4389 `latex' Highlight LaTeX snippets and environments.
4390 `script' Highlight subscript and superscript.
4391 `entities' Highlight entities."
4392 :group 'org-appearance
4393 :version "24.4"
4394 :package-version '(Org . "8.0")
4395 :type '(choice
4396 (const :tag "No highlighting" nil)
4397 (set :greedy t :tag "Highlight"
4398 (const :tag "LaTeX snippets and environments" latex)
4399 (const :tag "Subscript and superscript" script)
4400 (const :tag "Entities" entities))))
4402 (defcustom org-hide-emphasis-markers nil
4403 "Non-nil mean font-lock should hide the emphasis marker characters."
4404 :group 'org-appearance
4405 :type 'boolean)
4407 (defcustom org-hide-macro-markers nil
4408 "Non-nil mean font-lock should hide the brackets marking macro calls."
4409 :group 'org-appearance
4410 :type 'boolean)
4412 (defcustom org-pretty-entities nil
4413 "Non-nil means show entities as UTF8 characters.
4414 When nil, the \\name form remains in the buffer."
4415 :group 'org-appearance
4416 :version "24.1"
4417 :type 'boolean)
4419 (defcustom org-pretty-entities-include-sub-superscripts t
4420 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4421 :group 'org-appearance
4422 :version "24.1"
4423 :type 'boolean)
4425 (defvar org-emph-re nil
4426 "Regular expression for matching emphasis.
4427 After a match, the match groups contain these elements:
4428 0 The match of the full regular expression, including the characters
4429 before and after the proper match
4430 1 The character before the proper match, or empty at beginning of line
4431 2 The proper match, including the leading and trailing markers
4432 3 The leading marker like * or /, indicating the type of highlighting
4433 4 The text between the emphasis markers, not including the markers
4434 5 The character after the match, empty at the end of a line")
4435 (defvar org-verbatim-re nil
4436 "Regular expression for matching verbatim text.")
4437 (defvar org-emphasis-regexp-components) ; defined just below
4438 (defvar org-emphasis-alist) ; defined just below
4439 (defun org-set-emph-re (var val)
4440 "Set variable and compute the emphasis regular expression."
4441 (set var val)
4442 (when (and (boundp 'org-emphasis-alist)
4443 (boundp 'org-emphasis-regexp-components)
4444 org-emphasis-alist org-emphasis-regexp-components)
4445 (let* ((e org-emphasis-regexp-components)
4446 (pre (car e))
4447 (post (nth 1 e))
4448 (border (nth 2 e))
4449 (body (nth 3 e))
4450 (nl (nth 4 e))
4451 (body1 (concat body "*?"))
4452 (markers (mapconcat 'car org-emphasis-alist ""))
4453 (vmarkers (mapconcat
4454 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4455 org-emphasis-alist "")))
4456 ;; make sure special characters appear at the right position in the class
4457 (if (string-match "\\^" markers)
4458 (setq markers (concat (replace-match "" t t markers) "^")))
4459 (if (string-match "-" markers)
4460 (setq markers (concat (replace-match "" t t markers) "-")))
4461 (if (string-match "\\^" vmarkers)
4462 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4463 (if (string-match "-" vmarkers)
4464 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4465 (if (> nl 0)
4466 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4467 (int-to-string nl) "\\}")))
4468 ;; Make the regexp
4469 (setq org-emph-re
4470 (concat "\\([" pre "]\\|^\\)"
4471 "\\("
4472 "\\([" markers "]\\)"
4473 "\\("
4474 "[^" border "]\\|"
4475 "[^" border "]"
4476 body1
4477 "[^" border "]"
4478 "\\)"
4479 "\\3\\)"
4480 "\\([" post "]\\|$\\)"))
4481 (setq org-verbatim-re
4482 (concat "\\([" pre "]\\|^\\)"
4483 "\\("
4484 "\\([" vmarkers "]\\)"
4485 "\\("
4486 "[^" border "]\\|"
4487 "[^" border "]"
4488 body1
4489 "[^" border "]"
4490 "\\)"
4491 "\\3\\)"
4492 "\\([" post "]\\|$\\)")))))
4494 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4495 ;; set this option proved cumbersome. See this message/thread:
4496 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4497 (defvar org-emphasis-regexp-components
4498 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4499 "Components used to build the regular expression for emphasis.
4500 This is a list with five entries. Terminology: In an emphasis string
4501 like \" *strong word* \", we call the initial space PREMATCH, the final
4502 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4503 and \"trong wor\" is the body. The different components in this variable
4504 specify what is allowed/forbidden in each part:
4506 pre Chars allowed as prematch. Beginning of line will be allowed too.
4507 post Chars allowed as postmatch. End of line will be allowed too.
4508 border The chars *forbidden* as border characters.
4509 body-regexp A regexp like \".\" to match a body character. Don't use
4510 non-shy groups here, and don't allow newline here.
4511 newline The maximum number of newlines allowed in an emphasis exp.
4513 You need to reload Org or to restart Emacs after customizing this.")
4515 (defcustom org-emphasis-alist
4516 '(("*" bold)
4517 ("/" italic)
4518 ("_" underline)
4519 ("=" org-verbatim verbatim)
4520 ("~" org-code verbatim)
4521 ("+" (:strike-through t)))
4522 "Alist of characters and faces to emphasize text.
4523 Text starting and ending with a special character will be emphasized,
4524 for example *bold*, _underlined_ and /italic/. This variable sets the
4525 marker characters and the face to be used by font-lock for highlighting
4526 in Org-mode Emacs buffers.
4528 You need to reload Org or to restart Emacs after customizing this."
4529 :group 'org-appearance
4530 :set 'org-set-emph-re
4531 :version "24.4"
4532 :package-version '(Org . "8.0")
4533 :type '(repeat
4534 (list
4535 (string :tag "Marker character")
4536 (choice
4537 (face :tag "Font-lock-face")
4538 (plist :tag "Face property list"))
4539 (option (const verbatim)))))
4541 (defvar org-protecting-blocks '("src" "example" "export")
4542 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4543 This is needed for font-lock setup.")
4545 ;;; Functions and variables from their packages
4546 ;; Declared here to avoid compiler warnings
4547 (defvar mark-active)
4549 ;; Various packages
4550 (declare-function calc-eval "calc" (str &optional separator &rest args))
4551 (declare-function calendar-forward-day "cal-move" (arg))
4552 (declare-function calendar-goto-date "cal-move" (date))
4553 (declare-function calendar-goto-today "cal-move" ())
4554 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4555 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4556 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4557 (declare-function cdlatex-tab "ext:cdlatex" ())
4558 (declare-function dired-get-filename
4559 "dired"
4560 (&optional localp no-error-if-not-filep))
4561 (declare-function iswitchb-read-buffer
4562 "iswitchb"
4563 (prompt &optional
4564 default require-match _predicate start matches-set))
4565 (declare-function org-agenda-change-all-lines
4566 "org-agenda"
4567 (newhead hdmarker &optional fixface just-this))
4568 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4569 "org-agenda"
4570 (&optional end))
4571 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4572 (declare-function org-agenda-format-item
4573 "org-agenda"
4574 (extra txt &optional level category tags dotime
4575 remove-re habitp))
4576 (declare-function org-agenda-maybe-redo "org-agenda" ())
4577 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4578 (declare-function org-agenda-save-markers-for-cut-and-paste
4579 "org-agenda"
4580 (beg end))
4581 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4582 (declare-function org-agenda-skip "org-agenda" ())
4583 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4584 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4585 (declare-function org-indent-mode "org-indent" (&optional arg))
4586 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4587 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4588 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4589 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4590 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4591 (declare-function parse-time-string "parse-time" (string))
4592 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4593 (declare-function table--at-cell-p
4594 "table"
4595 (position &optional object at-column))
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-table-recognize-table.el ()
4634 "If there is a table.el table nearby, recognize it and move into it."
4635 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4636 (beginning-of-line)
4637 (unless (or (looking-at org-table-dataline-regexp)
4638 (not (looking-at org-table1-hline-regexp)))
4639 (forward-line)
4640 (when (looking-at org-table-any-border-regexp)
4641 (forward-line -2)))
4642 (if (re-search-forward "|" (org-table-end t) t)
4643 (progn
4644 (require 'table)
4645 (if (table--at-cell-p (point)) t
4646 (message "recognizing table.el table...")
4647 (table-recognize-table)
4648 (message "recognizing table.el table...done")))
4649 (error "This should not happen"))))
4650 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4651 (make-obsolete 'org-table-recognize-table.el
4652 "please notify the org mailing list if you use this function."
4653 "Org 9.0")
4655 (defun org-at-table-hline-p ()
4656 "Non-nil when point is inside a hline in a table.
4657 Assume point is already in a table. If `org-enable-table-editor'
4658 is nil, return nil unconditionally."
4659 (and org-enable-table-editor
4660 (save-excursion
4661 (beginning-of-line)
4662 (looking-at org-table-hline-regexp))))
4664 (defun org-table-map-tables (function &optional quietly)
4665 "Apply FUNCTION to the start of all tables in the buffer."
4666 (save-excursion
4667 (save-restriction
4668 (widen)
4669 (goto-char (point-min))
4670 (while (re-search-forward org-table-any-line-regexp nil t)
4671 (unless quietly
4672 (message "Mapping tables: %d%%"
4673 (floor (* 100.0 (point)) (buffer-size))))
4674 (beginning-of-line 1)
4675 (when (and (looking-at org-table-line-regexp)
4676 ;; Exclude tables in src/example/verbatim/clocktable blocks
4677 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4678 (save-excursion (funcall function))
4679 (or (looking-at org-table-line-regexp)
4680 (forward-char 1)))
4681 (re-search-forward org-table-any-border-regexp nil 1))))
4682 (unless quietly (message "Mapping tables: done")))
4684 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4685 (declare-function org-clock-update-mode-line "org-clock" ())
4686 (declare-function org-resolve-clocks "org-clock"
4687 (&optional also-non-dangling-p prompt last-valid))
4689 (defun org-at-TBLFM-p (&optional pos)
4690 "Non-nil when point (or POS) is in #+TBLFM line."
4691 (save-excursion
4692 (goto-char (or pos (point)))
4693 (beginning-of-line)
4694 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4695 (eq (org-element-type (org-element-at-point)) 'table))))
4697 (defvar org-clock-start-time)
4698 (defvar org-clock-marker (make-marker)
4699 "Marker recording the last clock-in.")
4700 (defvar org-clock-hd-marker (make-marker)
4701 "Marker recording the last clock-in, but the headline position.")
4702 (defvar org-clock-heading ""
4703 "The heading of the current clock entry.")
4704 (defun org-clock-is-active ()
4705 "Return the buffer where the clock is currently running.
4706 Return nil if no clock is running."
4707 (marker-buffer org-clock-marker))
4709 (defun org-check-running-clock ()
4710 "Check if the current buffer contains the running clock.
4711 If yes, offer to stop it and to save the buffer with the changes."
4712 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4713 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4714 (buffer-name))))
4715 (org-clock-out)
4716 (when (y-or-n-p "Save changed buffer?")
4717 (save-buffer))))
4719 (defun org-clocktable-try-shift (dir n)
4720 "Check if this line starts a clock table, if yes, shift the time block."
4721 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4722 (org-clocktable-shift dir n)))
4724 ;;;###autoload
4725 (defun org-clock-persistence-insinuate ()
4726 "Set up hooks for clock persistence."
4727 (require 'org-clock)
4728 (add-hook 'org-mode-hook 'org-clock-load)
4729 (add-hook 'kill-emacs-hook 'org-clock-save))
4731 (defgroup org-archive nil
4732 "Options concerning archiving in Org-mode."
4733 :tag "Org Archive"
4734 :group 'org-structure)
4736 (defcustom org-archive-location "%s_archive::"
4737 "The location where subtrees should be archived.
4739 The value of this variable is a string, consisting of two parts,
4740 separated by a double-colon. The first part is a filename and
4741 the second part is a headline.
4743 When the filename is omitted, archiving happens in the same file.
4744 %s in the filename will be replaced by the current file
4745 name (without the directory part). Archiving to a different file
4746 is useful to keep archived entries from contributing to the
4747 Org-mode Agenda.
4749 The archived entries will be filed as subtrees of the specified
4750 headline. When the headline is omitted, the subtrees are simply
4751 filed away at the end of the file, as top-level entries. Also in
4752 the heading you can use %s to represent the file name, this can be
4753 useful when using the same archive for a number of different files.
4755 Here are a few examples:
4756 \"%s_archive::\"
4757 If the current file is Projects.org, archive in file
4758 Projects.org_archive, as top-level trees. This is the default.
4760 \"::* Archived Tasks\"
4761 Archive in the current file, under the top-level headline
4762 \"* Archived Tasks\".
4764 \"~/org/archive.org::\"
4765 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4767 \"~/org/archive.org::* From %s\"
4768 Archive in file ~/org/archive.org (absolute path), under headlines
4769 \"From FILENAME\" where file name is the current file name.
4771 \"~/org/datetree.org::datetree/* Finished Tasks\"
4772 The \"datetree/\" string is special, signifying to archive
4773 items to the datetree. Items are placed in either the CLOSED
4774 date of the item, or the current date if there is no CLOSED date.
4775 The heading will be a subentry to the current date. There doesn't
4776 need to be a heading, but there always needs to be a slash after
4777 datetree. For example, to store archived items directly in the
4778 datetree, use \"~/org/datetree.org::datetree/\".
4780 \"basement::** Finished Tasks\"
4781 Archive in file ./basement (relative path), as level 3 trees
4782 below the level 2 heading \"** Finished Tasks\".
4784 You may set this option on a per-file basis by adding to the buffer a
4785 line like
4787 #+ARCHIVE: basement::** Finished Tasks
4789 You may also define it locally for a subtree by setting an ARCHIVE property
4790 in the entry. If such a property is found in an entry, or anywhere up
4791 the hierarchy, it will be used."
4792 :group 'org-archive
4793 :type 'string)
4795 (defcustom org-agenda-skip-archived-trees t
4796 "Non-nil means the agenda will skip any items located in archived trees.
4797 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4798 variable is no longer recommended, you should leave it at the value t.
4799 Instead, use the key `v' to cycle the archives-mode in the agenda."
4800 :group 'org-archive
4801 :group 'org-agenda-skip
4802 :type 'boolean)
4804 (defcustom org-columns-skip-archived-trees t
4805 "Non-nil means ignore archived trees when creating column view."
4806 :group 'org-archive
4807 :group 'org-properties
4808 :type 'boolean)
4810 (defcustom org-cycle-open-archived-trees nil
4811 "Non-nil means `org-cycle' will open archived trees.
4812 An archived tree is a tree marked with the tag ARCHIVE.
4813 When nil, archived trees will stay folded. You can still open them with
4814 normal outline commands like `show-all', but not with the cycling commands."
4815 :group 'org-archive
4816 :group 'org-cycle
4817 :type 'boolean)
4819 (defcustom org-sparse-tree-open-archived-trees nil
4820 "Non-nil means sparse tree construction shows matches in archived trees.
4821 When nil, matches in these trees are highlighted, but the trees are kept in
4822 collapsed state."
4823 :group 'org-archive
4824 :group 'org-sparse-trees
4825 :type 'boolean)
4827 (defcustom org-sparse-tree-default-date-type nil
4828 "The default date type when building a sparse tree.
4829 When this is nil, a date is a scheduled or a deadline timestamp.
4830 Otherwise, these types are allowed:
4832 all: all timestamps
4833 active: only active timestamps (<...>)
4834 inactive: only inactive timestamps ([...])
4835 scheduled: only scheduled timestamps
4836 deadline: only deadline timestamps"
4837 :type '(choice (const :tag "Scheduled or deadline" nil)
4838 (const :tag "All timestamps" all)
4839 (const :tag "Only active timestamps" active)
4840 (const :tag "Only inactive timestamps" inactive)
4841 (const :tag "Only scheduled timestamps" scheduled)
4842 (const :tag "Only deadline timestamps" deadline)
4843 (const :tag "Only closed timestamps" closed))
4844 :version "25.1"
4845 :package-version '(Org . "8.3")
4846 :group 'org-sparse-trees)
4848 (defun org-cycle-hide-archived-subtrees (state)
4849 "Re-hide all archived subtrees after a visibility state change."
4850 (when (and (not org-cycle-open-archived-trees)
4851 (not (memq state '(overview folded))))
4852 (save-excursion
4853 (let* ((globalp (memq state '(contents all)))
4854 (beg (if globalp (point-min) (point)))
4855 (end (if globalp (point-max) (org-end-of-subtree t))))
4856 (org-hide-archived-subtrees beg end)
4857 (goto-char beg)
4858 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4859 (message "%s" (substitute-command-keys
4860 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4862 (defun org-force-cycle-archived ()
4863 "Cycle subtree even if it is archived."
4864 (interactive)
4865 (setq this-command 'org-cycle)
4866 (let ((org-cycle-open-archived-trees t))
4867 (call-interactively 'org-cycle)))
4869 (defun org-hide-archived-subtrees (beg end)
4870 "Re-hide all archived subtrees after a visibility state change."
4871 (org-with-wide-buffer
4872 (let ((case-fold-search nil)
4873 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4874 (goto-char beg)
4875 ;; Include headline point is currently on.
4876 (beginning-of-line)
4877 (while (and (< (point) end) (re-search-forward re end t))
4878 (when (member org-archive-tag (org-get-tags))
4879 (org-flag-subtree t)
4880 (org-end-of-subtree t))))))
4882 (declare-function outline-end-of-heading "outline" ())
4883 (declare-function outline-flag-region "outline" (from to flag))
4884 (defun org-flag-subtree (flag)
4885 (save-excursion
4886 (org-back-to-heading t)
4887 (outline-end-of-heading)
4888 (outline-flag-region (point)
4889 (progn (org-end-of-subtree t) (point))
4890 flag)))
4892 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4894 ;; Declare Column View Code
4896 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4897 (declare-function org-columns-compute "org-colview" (property))
4899 ;; Declare ID code
4901 (declare-function org-id-store-link "org-id")
4902 (declare-function org-id-locations-load "org-id")
4903 (declare-function org-id-locations-save "org-id")
4904 (defvar org-id-track-globally)
4906 ;;; Variables for pre-computed regular expressions, all buffer local
4908 (defvar-local org-todo-regexp nil
4909 "Matches any of the TODO state keywords.")
4910 (defvar-local org-not-done-regexp nil
4911 "Matches any of the TODO state keywords except the last one.")
4912 (defvar-local org-not-done-heading-regexp nil
4913 "Matches a TODO headline that is not done.")
4914 (defvar-local org-todo-line-regexp nil
4915 "Matches a headline and puts TODO state into group 2 if present.")
4916 (defvar-local org-complex-heading-regexp nil
4917 "Matches a headline and puts everything into groups:
4918 group 1: the stars
4919 group 2: The todo keyword, maybe
4920 group 3: Priority cookie
4921 group 4: True headline
4922 group 5: Tags")
4923 (defvar-local org-complex-heading-regexp-format nil
4924 "Printf format to make regexp to match an exact headline.
4925 This regexp will match the headline of any node which has the
4926 exact headline text that is put into the format, but may have any
4927 TODO state, priority and tags.")
4928 (defvar-local org-todo-line-tags-regexp nil
4929 "Matches a headline and puts TODO state into group 2 if present.
4930 Also put tags into group 4 if tags are present.")
4932 (defconst org-plain-time-of-day-regexp
4933 (concat
4934 "\\(\\<[012]?[0-9]"
4935 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4936 "\\(--?"
4937 "\\(\\<[012]?[0-9]"
4938 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4939 "\\)?")
4940 "Regular expression to match a plain time or time range.
4941 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4942 groups carry important information:
4943 0 the full match
4944 1 the first time, range or not
4945 8 the second time, if it is a range.")
4947 (defconst org-plain-time-extension-regexp
4948 (concat
4949 "\\(\\<[012]?[0-9]"
4950 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4951 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4952 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4953 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4954 groups carry important information:
4955 0 the full match
4956 7 hours of duration
4957 9 minutes of duration")
4959 (defconst org-stamp-time-of-day-regexp
4960 (concat
4961 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4962 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4963 "\\(--?"
4964 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4965 "Regular expression to match a timestamp time or time range.
4966 After a match, the following groups carry important information:
4967 0 the full match
4968 1 date plus weekday, for back referencing to make sure both times are on the same day
4969 2 the first time, range or not
4970 4 the second time, if it is a range.")
4972 (defconst org-startup-options
4973 '(("fold" org-startup-folded t)
4974 ("overview" org-startup-folded t)
4975 ("nofold" org-startup-folded nil)
4976 ("showall" org-startup-folded nil)
4977 ("showeverything" org-startup-folded showeverything)
4978 ("content" org-startup-folded content)
4979 ("indent" org-startup-indented t)
4980 ("noindent" org-startup-indented nil)
4981 ("hidestars" org-hide-leading-stars t)
4982 ("showstars" org-hide-leading-stars nil)
4983 ("odd" org-odd-levels-only t)
4984 ("oddeven" org-odd-levels-only nil)
4985 ("align" org-startup-align-all-tables t)
4986 ("noalign" org-startup-align-all-tables nil)
4987 ("inlineimages" org-startup-with-inline-images t)
4988 ("noinlineimages" org-startup-with-inline-images nil)
4989 ("latexpreview" org-startup-with-latex-preview t)
4990 ("nolatexpreview" org-startup-with-latex-preview nil)
4991 ("customtime" org-display-custom-times t)
4992 ("logdone" org-log-done time)
4993 ("lognotedone" org-log-done note)
4994 ("nologdone" org-log-done nil)
4995 ("lognoteclock-out" org-log-note-clock-out t)
4996 ("nolognoteclock-out" org-log-note-clock-out nil)
4997 ("logrepeat" org-log-repeat state)
4998 ("lognoterepeat" org-log-repeat note)
4999 ("logdrawer" org-log-into-drawer t)
5000 ("nologdrawer" org-log-into-drawer nil)
5001 ("logstatesreversed" org-log-states-order-reversed t)
5002 ("nologstatesreversed" org-log-states-order-reversed nil)
5003 ("nologrepeat" org-log-repeat nil)
5004 ("logreschedule" org-log-reschedule time)
5005 ("lognotereschedule" org-log-reschedule note)
5006 ("nologreschedule" org-log-reschedule nil)
5007 ("logredeadline" org-log-redeadline time)
5008 ("lognoteredeadline" org-log-redeadline note)
5009 ("nologredeadline" org-log-redeadline nil)
5010 ("logrefile" org-log-refile time)
5011 ("lognoterefile" org-log-refile note)
5012 ("nologrefile" org-log-refile nil)
5013 ("fninline" org-footnote-define-inline t)
5014 ("nofninline" org-footnote-define-inline nil)
5015 ("fnlocal" org-footnote-section nil)
5016 ("fnauto" org-footnote-auto-label t)
5017 ("fnprompt" org-footnote-auto-label nil)
5018 ("fnconfirm" org-footnote-auto-label confirm)
5019 ("fnplain" org-footnote-auto-label plain)
5020 ("fnadjust" org-footnote-auto-adjust t)
5021 ("nofnadjust" org-footnote-auto-adjust nil)
5022 ("constcgs" constants-unit-system cgs)
5023 ("constSI" constants-unit-system SI)
5024 ("noptag" org-tag-persistent-alist nil)
5025 ("hideblocks" org-hide-block-startup t)
5026 ("nohideblocks" org-hide-block-startup nil)
5027 ("beamer" org-startup-with-beamer-mode t)
5028 ("entitiespretty" org-pretty-entities t)
5029 ("entitiesplain" org-pretty-entities nil))
5030 "Variable associated with STARTUP options for org-mode.
5031 Each element is a list of three items: the startup options (as written
5032 in the #+STARTUP line), the corresponding variable, and the value to set
5033 this variable to if the option is found. An optional forth element PUSH
5034 means to push this value onto the list in the variable.")
5036 (defcustom org-group-tags t
5037 "When non-nil (the default), use group tags.
5038 This can be turned on/off through `org-toggle-tags-groups'."
5039 :group 'org-tags
5040 :group 'org-startup
5041 :type 'boolean)
5043 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5045 (defun org-toggle-tags-groups ()
5046 "Toggle support for group tags.
5047 Support for group tags is controlled by the option
5048 `org-group-tags', which is non-nil by default."
5049 (interactive)
5050 (setq org-group-tags (not org-group-tags))
5051 (cond ((and (derived-mode-p 'org-agenda-mode)
5052 org-group-tags)
5053 (org-agenda-redo))
5054 ((derived-mode-p 'org-mode)
5055 (let ((org-inhibit-startup t)) (org-mode))))
5056 (message "Groups tags support has been turned %s"
5057 (if org-group-tags "on" "off")))
5059 (defun org-set-regexps-and-options (&optional tags-only)
5060 "Precompute regular expressions used in the current buffer.
5061 When optional argument TAGS-ONLY is non-nil, only compute tags
5062 related expressions."
5063 (when (derived-mode-p 'org-mode)
5064 (let ((alist (org--setup-collect-keywords
5065 (org-make-options-regexp
5066 (append '("FILETAGS" "TAGS" "SETUPFILE")
5067 (and (not tags-only)
5068 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5069 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5070 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5071 ;; Startup options. Get this early since it does change
5072 ;; behavior for other options (e.g., tags).
5073 (let ((startup (cdr (assq 'startup alist))))
5074 (dolist (option startup)
5075 (let ((entry (assoc-string option org-startup-options t)))
5076 (when entry
5077 (let ((var (nth 1 entry))
5078 (val (nth 2 entry)))
5079 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5080 (unless (listp (symbol-value var))
5081 (set (make-local-variable var) nil))
5082 (add-to-list var val)))))))
5083 (setq-local org-file-tags
5084 (mapcar #'org-add-prop-inherited
5085 (cdr (assq 'filetags alist))))
5086 (setq org-current-tag-alist
5087 (append org-tag-persistent-alist
5088 (let ((tags (cdr (assq 'tags alist))))
5089 (if tags (org-tag-string-to-alist tags)
5090 org-tag-alist))))
5091 (setq org-tag-groups-alist
5092 (org-tag-alist-to-groups org-current-tag-alist))
5093 (unless tags-only
5094 ;; File properties.
5095 (setq-local org-file-properties (cdr (assq 'property alist)))
5096 ;; Archive location.
5097 (let ((archive (cdr (assq 'archive alist))))
5098 (when archive (setq-local org-archive-location archive)))
5099 ;; Category.
5100 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5101 (when cat
5102 (setq-local org-category (intern cat))
5103 (setq-local org-file-properties
5104 (org--update-property-plist
5105 "CATEGORY" cat org-file-properties))))
5106 ;; Columns.
5107 (let ((column (cdr (assq 'columns alist))))
5108 (when column (setq-local org-columns-default-format column)))
5109 ;; Constants.
5110 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5111 ;; Link abbreviations.
5112 (let ((links (cdr (assq 'link alist))))
5113 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5114 ;; Priorities.
5115 (let ((priorities (cdr (assq 'priorities alist))))
5116 (when priorities
5117 (setq-local org-highest-priority (nth 0 priorities))
5118 (setq-local org-lowest-priority (nth 1 priorities))
5119 (setq-local org-default-priority (nth 2 priorities))))
5120 ;; Scripts.
5121 (let ((scripts (assq 'scripts alist)))
5122 (when scripts
5123 (setq-local org-use-sub-superscripts (cdr scripts))))
5124 ;; TODO keywords.
5125 (setq-local org-todo-kwd-alist nil)
5126 (setq-local org-todo-key-alist nil)
5127 (setq-local org-todo-key-trigger nil)
5128 (setq-local org-todo-keywords-1 nil)
5129 (setq-local org-done-keywords nil)
5130 (setq-local org-todo-heads nil)
5131 (setq-local org-todo-sets nil)
5132 (setq-local org-todo-log-states nil)
5133 (let ((todo-sequences
5134 (or (nreverse (cdr (assq 'todo alist)))
5135 (let ((d (default-value 'org-todo-keywords)))
5136 (if (not (stringp (car d))) d
5137 ;; XXX: Backward compatibility code.
5138 (list (cons org-todo-interpretation d)))))))
5139 (dolist (sequence todo-sequences)
5140 (let* ((sequence (or (run-hook-with-args-until-success
5141 'org-todo-setup-filter-hook sequence)
5142 sequence))
5143 (sequence-type (car sequence))
5144 (keywords (cdr sequence))
5145 (sep (member "|" keywords))
5146 names alist)
5147 (dolist (k (remove "|" keywords))
5148 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5150 (error "Invalid TODO keyword %s" k))
5151 (let ((name (match-string 1 k))
5152 (key (match-string 2 k))
5153 (log (org-extract-log-state-settings k)))
5154 (push name names)
5155 (push (cons name (and key (string-to-char key))) alist)
5156 (when log (push log org-todo-log-states))))
5157 (let* ((names (nreverse names))
5158 (done (if sep (org-remove-keyword-keys (cdr sep))
5159 (last names)))
5160 (head (car names))
5161 (tail (list sequence-type head (car done) (org-last done))))
5162 (add-to-list 'org-todo-heads head 'append)
5163 (push names org-todo-sets)
5164 (setq org-done-keywords (append org-done-keywords done nil))
5165 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5166 (setq org-todo-key-alist
5167 (append org-todo-key-alist
5168 (and alist
5169 (append '((:startgroup))
5170 (nreverse alist)
5171 '((:endgroup))))))
5172 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5173 (setq org-todo-sets (nreverse org-todo-sets)
5174 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5175 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5176 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5177 ;; Compute the regular expressions and other local variables.
5178 ;; Using `org-outline-regexp-bol' would complicate them much,
5179 ;; because of the fixed white space at the end of that string.
5180 (unless org-done-keywords
5181 (setq org-done-keywords
5182 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5183 (setq org-not-done-keywords
5184 (org-delete-all org-done-keywords
5185 (copy-sequence org-todo-keywords-1))
5186 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5187 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5188 org-not-done-heading-regexp
5189 (format org-heading-keyword-regexp-format org-not-done-regexp)
5190 org-todo-line-regexp
5191 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5192 org-complex-heading-regexp
5193 (concat "^\\(\\*+\\)"
5194 "\\(?: +" org-todo-regexp "\\)?"
5195 "\\(?: +\\(\\[#.\\]\\)\\)?"
5196 "\\(?: +\\(.*?\\)\\)??"
5197 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5198 "[ \t]*$")
5199 org-complex-heading-regexp-format
5200 (concat "^\\(\\*+\\)"
5201 "\\(?: +" org-todo-regexp "\\)?"
5202 "\\(?: +\\(\\[#.\\]\\)\\)?"
5203 "\\(?: +"
5204 ;; Stats cookies can be stuck to body.
5205 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5206 "\\(%s\\)"
5207 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5208 "\\)"
5209 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5210 "[ \t]*$")
5211 org-todo-line-tags-regexp
5212 (concat "^\\(\\*+\\)"
5213 "\\(?: +" org-todo-regexp "\\)?"
5214 "\\(?: +\\(.*?\\)\\)??"
5215 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5216 "[ \t]*$"))
5217 (org-compute-latex-and-related-regexp)))))
5219 (defun org--setup-collect-keywords (regexp &optional files alist)
5220 "Return setup keywords values as an alist.
5222 REGEXP matches a subset of setup keywords. FILES is a list of
5223 file names already visited. It is used to avoid circular setup
5224 files. ALIST, when non-nil, is the alist computed so far.
5226 Return value contains the following keys: `archive', `category',
5227 `columns', `constants', `filetags', `link', `priorities',
5228 `property', `scripts', `startup', `tags' and `todo'."
5229 (org-with-wide-buffer
5230 (goto-char (point-min))
5231 (let ((case-fold-search t))
5232 (while (re-search-forward regexp nil t)
5233 (let ((element (org-element-at-point)))
5234 (when (eq (org-element-type element) 'keyword)
5235 (let ((key (org-element-property :key element))
5236 (value (org-element-property :value element)))
5237 (cond
5238 ((equal key "ARCHIVE")
5239 (when (org-string-nw-p value)
5240 (push (cons 'archive value) alist)))
5241 ((equal key "CATEGORY") (push (cons 'category value) alist))
5242 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5243 ((equal key "CONSTANTS")
5244 (let* ((constants (assq 'constants alist))
5245 (store (cdr constants)))
5246 (dolist (pair (org-split-string value))
5247 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5248 pair)
5249 (let* ((name (match-string 1 pair))
5250 (value (match-string 2 pair))
5251 (old (assoc name store)))
5252 (if old (setcdr old value)
5253 (push (cons name value) store)))))
5254 (if constants (setcdr constants store)
5255 (push (cons 'constants store) alist))))
5256 ((equal key "FILETAGS")
5257 (when (org-string-nw-p value)
5258 (let ((old (assq 'filetags alist))
5259 (new (apply #'nconc
5260 (mapcar (lambda (x) (org-split-string x ":"))
5261 (org-split-string value)))))
5262 (if old (setcdr old (append new (cdr old)))
5263 (push (cons 'filetags new) alist)))))
5264 ((equal key "LINK")
5265 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5266 (let ((links (assq 'link alist))
5267 (pair (cons (match-string-no-properties 1 value)
5268 (match-string-no-properties 2 value))))
5269 (if links (push pair (cdr links))
5270 (push (list 'link pair) alist)))))
5271 ((equal key "OPTIONS")
5272 (when (and (org-string-nw-p value)
5273 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5274 (push (cons 'scripts (read (match-string 1 value))) alist)))
5275 ((equal key "PRIORITIES")
5276 (push (cons 'priorities
5277 (let ((prio (org-split-string value)))
5278 (if (< (length prio) 3) '(?A ?C ?B)
5279 (mapcar #'string-to-char prio))))
5280 alist))
5281 ((equal key "PROPERTY")
5282 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5283 (let* ((property (assq 'property alist))
5284 (value (org--update-property-plist
5285 (match-string-no-properties 1 value)
5286 (match-string-no-properties 2 value)
5287 (cdr property))))
5288 (if property (setcdr property value)
5289 (push (cons 'property value) alist)))))
5290 ((equal key "STARTUP")
5291 (let ((startup (assq 'startup alist)))
5292 (if startup
5293 (setcdr startup
5294 (append (cdr startup) (org-split-string value)))
5295 (push (cons 'startup (org-split-string value)) alist))))
5296 ((equal key "TAGS")
5297 (let ((tag-cell (assq 'tags alist)))
5298 (if tag-cell
5299 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5300 (push (cons 'tags value) alist))))
5301 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5302 (let ((todo (assq 'todo alist))
5303 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5304 (org-split-string value))))
5305 (if todo (push value (cdr todo))
5306 (push (list 'todo value) alist))))
5307 ((equal key "SETUPFILE")
5308 (unless buffer-read-only ; Do not check in Gnus messages.
5309 (let ((f (and (org-string-nw-p value)
5310 (expand-file-name
5311 (org-remove-double-quotes value)))))
5312 (when (and f (file-readable-p f) (not (member f files)))
5313 (with-temp-buffer
5314 (setq default-directory (file-name-directory f))
5315 (insert-file-contents f)
5316 (setq alist
5317 ;; Fake Org mode to benefit from cache
5318 ;; without recurring needlessly.
5319 (let ((major-mode 'org-mode))
5320 (org--setup-collect-keywords
5321 regexp (cons f files) alist)))))))))))))))
5322 alist)
5324 (defun org-tag-string-to-alist (s)
5325 "Return tag alist associated to string S.
5326 S is a value for TAGS keyword or produced with
5327 `org-tag-alist-to-string'. Return value is an alist suitable for
5328 `org-tag-alist' or `org-tag-persistent-alist'."
5329 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5330 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5331 "\\|{.+?}\\)" ; regular expression
5332 "\\(?:(\\(.\\))\\)?\\'"))
5333 alist group-flag)
5334 (dolist (tokens lines (cdr (nreverse alist)))
5335 (push '(:newline) alist)
5336 (while tokens
5337 (let ((token (pop tokens)))
5338 (pcase token
5339 ("{"
5340 (push '(:startgroup) alist)
5341 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5342 ("}"
5343 (push '(:endgroup) alist)
5344 (setq group-flag nil))
5345 ("["
5346 (push '(:startgrouptag) alist)
5347 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5348 ("]"
5349 (push '(:endgrouptag) alist)
5350 (setq group-flag nil))
5351 (":"
5352 (push '(:grouptags) alist))
5353 ((guard (string-match tag-re token))
5354 (let ((tag (match-string 1 token))
5355 (key (and (match-beginning 2)
5356 (string-to-char (match-string 2 token)))))
5357 ;; Push all tags in groups, no matter if they already
5358 ;; appear somewhere else in the list.
5359 (when (or group-flag (not (assoc tag alist)))
5360 (push (cons tag key) alist))))))))))
5362 (defun org-tag-alist-to-string (alist &optional skip-key)
5363 "Return tag string associated to ALIST.
5365 ALIST is an alist, as defined in `org-tag-alist' or
5366 `org-tag-persistent-alist', or produced with
5367 `org-tag-string-to-alist'.
5369 Return value is a string suitable as a value for \"TAGS\"
5370 keyword.
5372 When optional argument SKIP-KEY is non-nil, skip selection keys
5373 next to tags."
5374 (mapconcat (lambda (token)
5375 (pcase token
5376 (`(:startgroup) "{")
5377 (`(:endgroup) "}")
5378 (`(:startgrouptag) "[")
5379 (`(:endgrouptag) "]")
5380 (`(:grouptags) ":")
5381 (`(:newline) "\\n")
5382 ((and
5383 (guard (not skip-key))
5384 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5385 (format "%s(%c)" tag key))
5386 (`(,(and tag (pred stringp)) . ,_) tag)
5387 (_ (user-error "Invalid tag token: %S" token))))
5388 alist
5389 " "))
5391 (defun org-tag-alist-to-groups (alist)
5392 "Return group alist from tag ALIST.
5393 ALIST is an alist, as defined in `org-tag-alist' or
5394 `org-tag-persistent-alist', or produced with
5395 `org-tag-string-to-alist'. Return value is an alist following
5396 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5397 a string, summarizing TAGS, as a list of strings."
5398 (let (groups group-status current-group)
5399 (dolist (token alist (nreverse groups))
5400 (pcase token
5401 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5402 (`(,(or :endgroup :endgrouptag))
5403 (when (eq group-status 'append)
5404 (push (nreverse current-group) groups))
5405 (setq group-status nil))
5406 (`(:grouptags) (setq group-status 'append))
5407 ((and `(,tag . ,_) (guard group-status))
5408 (if (eq group-status 'append) (push tag current-group)
5409 (setq current-group (list tag))))
5410 (_ nil)))))
5412 (defun org-file-contents (file &optional noerror)
5413 "Return the contents of FILE, as a string."
5414 (if (and file (file-readable-p file))
5415 (with-temp-buffer
5416 (insert-file-contents file)
5417 (buffer-string))
5418 (funcall (if noerror 'message 'error)
5419 "Cannot read file \"%s\"%s"
5420 file
5421 (let ((from (buffer-file-name (buffer-base-buffer))))
5422 (if from (concat " (referenced in file \"" from "\")") "")))))
5424 (defun org-extract-log-state-settings (x)
5425 "Extract the log state setting from a TODO keyword string.
5426 This will extract info from a string like \"WAIT(w@/!)\"."
5427 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5428 (let ((kw (match-string 1 x))
5429 (log1 (and (match-end 3) (match-string 3 x)))
5430 (log2 (and (match-end 4) (match-string 4 x))))
5431 (and (or log1 log2)
5432 (list kw
5433 (and log1 (if (equal log1 "!") 'time 'note))
5434 (and log2 (if (equal log2 "!") 'time 'note)))))))
5436 (defun org-remove-keyword-keys (list)
5437 "Remove a pair of parenthesis at the end of each string in LIST."
5438 (mapcar (lambda (x)
5439 (if (string-match "(.*)$" x)
5440 (substring x 0 (match-beginning 0))
5442 list))
5444 (defun org-assign-fast-keys (alist)
5445 "Assign fast keys to a keyword-key alist.
5446 Respect keys that are already there."
5447 (let (new e (alt ?0))
5448 (while (setq e (pop alist))
5449 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5450 (cdr e)) ;; Key already assigned.
5451 (push e new)
5452 (let ((clist (string-to-list (downcase (car e))))
5453 (used (append new alist)))
5454 (when (= (car clist) ?@)
5455 (pop clist))
5456 (while (and clist (rassoc (car clist) used))
5457 (pop clist))
5458 (unless clist
5459 (while (rassoc alt used)
5460 (cl-incf alt)))
5461 (push (cons (car e) (or (car clist) alt)) new))))
5462 (nreverse new)))
5464 ;;; Some variables used in various places
5466 (defvar org-window-configuration nil
5467 "Used in various places to store a window configuration.")
5468 (defvar org-selected-window nil
5469 "Used in various places to store a window configuration.")
5470 (defvar org-finish-function nil
5471 "Function to be called when `C-c C-c' is used.
5472 This is for getting out of special buffers like capture.")
5473 (defvar org-last-state)
5475 ;; Defined somewhere in this file, but used before definition.
5476 (defvar org-entities) ;; defined in org-entities.el
5477 (defvar org-struct-menu)
5478 (defvar org-org-menu)
5479 (defvar org-tbl-menu)
5481 ;;;; Define the Org-mode
5483 ;; We use a before-change function to check if a table might need
5484 ;; an update.
5485 (defvar org-table-may-need-update t
5486 "Indicates that a table might need an update.
5487 This variable is set by `org-before-change-function'.
5488 `org-table-align' sets it back to nil.")
5489 (defun org-before-change-function (_beg _end)
5490 "Every change indicates that a table might need an update."
5491 (setq org-table-may-need-update t))
5492 (defvar org-mode-map)
5493 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5494 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5495 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5496 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5497 (defvar org-table-buffer-is-an nil)
5499 (defvar bidi-paragraph-direction)
5500 (defvar buffer-face-mode-face)
5502 (require 'outline)
5504 ;; Other stuff we need.
5505 (require 'time-date)
5506 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5507 (require 'easymenu)
5508 (autoload 'easy-menu-add "easymenu")
5509 (require 'overlay)
5511 ;; (require 'org-macs) moved higher up in the file before it is first used
5512 (require 'org-entities)
5513 ;; (require 'org-compat) moved higher up in the file before it is first used
5514 (require 'org-faces)
5515 (require 'org-list)
5516 (require 'org-pcomplete)
5517 (require 'org-src)
5518 (require 'org-footnote)
5519 (require 'org-macro)
5521 ;; babel
5522 (require 'ob)
5524 ;;;###autoload
5525 (define-derived-mode org-mode outline-mode "Org"
5526 "Outline-based notes management and organizer, alias
5527 \"Carsten's outline-mode for keeping track of everything.\"
5529 Org-mode develops organizational tasks around a NOTES file which
5530 contains information about projects as plain text. Org-mode is
5531 implemented on top of outline-mode, which is ideal to keep the content
5532 of large files well structured. It supports ToDo items, deadlines and
5533 time stamps, which magically appear in the diary listing of the Emacs
5534 calendar. Tables are easily created with a built-in table editor.
5535 Plain text URL-like links connect to websites, emails (VM), Usenet
5536 messages (Gnus), BBDB entries, and any files related to the project.
5537 For printing and sharing of notes, an Org-mode file (or a part of it)
5538 can be exported as a structured ASCII or HTML file.
5540 The following commands are available:
5542 \\{org-mode-map}"
5544 ;; Get rid of Outline menus, they are not needed
5545 ;; Need to do this here because define-derived-mode sets up
5546 ;; the keymap so late. Still, it is a waste to call this each time
5547 ;; we switch another buffer into Org mode.
5548 (define-key org-mode-map [menu-bar headings] 'undefined)
5549 (define-key org-mode-map [menu-bar hide] 'undefined)
5550 (define-key org-mode-map [menu-bar show] 'undefined)
5552 (org-load-modules-maybe)
5553 (org-install-agenda-files-menu)
5554 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5555 (add-to-invisibility-spec '(org-cwidth))
5556 (add-to-invisibility-spec '(org-hide-block . t))
5557 (setq-local outline-regexp org-outline-regexp)
5558 (setq-local outline-level 'org-outline-level)
5559 (setq bidi-paragraph-direction 'left-to-right)
5560 (when (and org-ellipsis
5561 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5562 (fboundp 'make-glyph-code))
5563 (unless org-display-table
5564 (setq org-display-table (make-display-table)))
5565 (set-display-table-slot
5566 org-display-table 4
5567 (vconcat (mapcar
5568 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5569 org-ellipsis)))
5570 (if (stringp org-ellipsis) org-ellipsis "..."))))
5571 (setq buffer-display-table org-display-table))
5572 (org-set-regexps-and-options)
5573 (org-set-font-lock-defaults)
5574 (when (and org-tag-faces (not org-tags-special-faces-re))
5575 ;; tag faces set outside customize.... force initialization.
5576 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5577 ;; Calc embedded
5578 (setq-local calc-embedded-open-mode "# ")
5579 ;; Modify a few syntax entries
5580 (modify-syntax-entry ?@ "w")
5581 (modify-syntax-entry ?\" "\"")
5582 (modify-syntax-entry ?\\ "_")
5583 (modify-syntax-entry ?~ "_")
5584 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5585 ;; Activate before-change-function
5586 (setq-local org-table-may-need-update t)
5587 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5588 ;; Check for running clock before killing a buffer
5589 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5590 ;; Initialize macros templates.
5591 (org-macro-initialize-templates)
5592 ;; Initialize radio targets.
5593 (org-update-radio-target-regexp)
5594 ;; Indentation.
5595 (setq-local indent-line-function 'org-indent-line)
5596 (setq-local indent-region-function 'org-indent-region)
5597 ;; Filling and auto-filling.
5598 (org-setup-filling)
5599 ;; Comments.
5600 (org-setup-comments-handling)
5601 ;; Initialize cache.
5602 (org-element-cache-reset)
5603 ;; Beginning/end of defun
5604 (setq-local beginning-of-defun-function 'org-backward-element)
5605 (setq-local end-of-defun-function
5606 (lambda ()
5607 (if (not (org-at-heading-p))
5608 (org-forward-element)
5609 (org-forward-element)
5610 (forward-char -1))))
5611 ;; Next error for sparse trees
5612 (setq-local next-error-function 'org-occur-next-match)
5613 ;; Make sure dependence stuff works reliably, even for users who set it
5614 ;; too late :-(
5615 (if org-enforce-todo-dependencies
5616 (add-hook 'org-blocker-hook
5617 'org-block-todo-from-children-or-siblings-or-parent)
5618 (remove-hook 'org-blocker-hook
5619 'org-block-todo-from-children-or-siblings-or-parent))
5620 (if org-enforce-todo-checkbox-dependencies
5621 (add-hook 'org-blocker-hook
5622 'org-block-todo-from-checkboxes)
5623 (remove-hook 'org-blocker-hook
5624 'org-block-todo-from-checkboxes))
5626 ;; Align options lines
5627 (setq-local
5628 align-mode-rules-list
5629 '((org-in-buffer-settings
5630 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5631 (modes . '(org-mode)))))
5633 ;; Imenu
5634 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5636 ;; Make isearch reveal context
5637 (setq-local outline-isearch-open-invisible-function
5638 (lambda (&rest _) (org-show-context 'isearch)))
5640 ;; Setup the pcomplete hooks
5641 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5642 (setq-local pcomplete-command-name-function 'org-command-at-point)
5643 (setq-local pcomplete-default-completion-function 'ignore)
5644 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5645 (setq-local pcomplete-termination-string "")
5646 (setq-local buffer-face-mode-face 'org-default)
5648 ;; If empty file that did not turn on Org mode automatically, make
5649 ;; it to.
5650 (when (and org-insert-mode-line-in-empty-file
5651 (called-interactively-p 'any)
5652 (= (point-min) (point-max)))
5653 (insert "# -*- mode: org -*-\n\n"))
5654 (unless org-inhibit-startup
5655 (org-unmodified
5656 (when org-startup-with-beamer-mode (org-beamer-mode))
5657 (when org-startup-align-all-tables
5658 (org-table-map-tables #'org-table-align t))
5659 (when org-startup-with-inline-images (org-display-inline-images))
5660 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5661 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5662 (when org-startup-truncated (setq truncate-lines t))
5663 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5664 (org-refresh-effort-properties)))
5665 ;; Try to set `org-hide' face correctly.
5666 (let ((foreground (org-find-invisible-foreground)))
5667 (when foreground
5668 (set-face-foreground 'org-hide foreground))))
5670 ;; Update `customize-package-emacs-version-alist'
5671 (add-to-list 'customize-package-emacs-version-alist
5672 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5673 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5674 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5676 (defvar org-mode-transpose-word-syntax-table
5677 (let ((st (make-syntax-table text-mode-syntax-table)))
5678 (dolist (c org-emphasis-alist st)
5679 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5681 (when (fboundp 'abbrev-table-put)
5682 (abbrev-table-put org-mode-abbrev-table
5683 :parents (list text-mode-abbrev-table)))
5685 (defun org-find-invisible-foreground ()
5686 (let ((candidates (remove
5687 "unspecified-bg"
5688 (nconc
5689 (list (face-background 'default)
5690 (face-background 'org-default))
5691 (mapcar
5692 (lambda (alist)
5693 (when (boundp alist)
5694 (cdr (assoc 'background-color (symbol-value alist)))))
5695 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5696 (list (face-foreground 'org-hide))))))
5697 (car (remove nil candidates))))
5699 (defun org-current-time (&optional rounding-minutes past)
5700 "Current time, possibly rounded to ROUNDING-MINUTES.
5701 When ROUNDING-MINUTES is not an integer, fall back on the car of
5702 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5703 the rounding returns a past time."
5704 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5705 (car org-time-stamp-rounding-minutes)))
5706 (time (decode-time)) res)
5707 (if (< r 1)
5708 (current-time)
5709 (setq res
5710 (apply 'encode-time
5711 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5712 (nthcdr 2 time))))
5713 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5714 (seconds-to-time (- (float-time res) (* r 60)))
5715 res))))
5717 (defun org-today ()
5718 "Return today date, considering `org-extend-today-until'."
5719 (time-to-days
5720 (time-subtract (current-time)
5721 (list 0 (* 3600 org-extend-today-until) 0))))
5723 ;;;; Font-Lock stuff, including the activators
5725 (defvar org-mouse-map (make-sparse-keymap))
5726 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5727 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5728 (when org-mouse-1-follows-link
5729 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5730 (when org-tab-follows-link
5731 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5732 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5734 (require 'font-lock)
5736 (defconst org-non-link-chars "]\t\n\r<>")
5737 (defvar org-link-types-re nil
5738 "Matches a link that has a url-like prefix like \"http:\"")
5739 (defvar org-link-re-with-space nil
5740 "Matches a link with spaces, optional angular brackets around it.")
5741 (defvar org-link-re-with-space2 nil
5742 "Matches a link with spaces, optional angular brackets around it.")
5743 (defvar org-link-re-with-space3 nil
5744 "Matches a link with spaces, only for internal part in bracket links.")
5745 (defvar org-angle-link-re nil
5746 "Matches link with angular brackets, spaces are allowed.")
5747 (defvar org-plain-link-re nil
5748 "Matches plain link, without spaces.")
5749 (defvar org-bracket-link-regexp nil
5750 "Matches a link in double brackets.")
5751 (defvar org-bracket-link-analytic-regexp nil
5752 "Regular expression used to analyze links.
5753 Here is what the match groups contain after a match:
5754 1: http:
5755 2: http
5756 3: path
5757 4: [desc]
5758 5: desc")
5759 (defvar org-bracket-link-analytic-regexp++ nil
5760 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5761 (defvar org-any-link-re nil
5762 "Regular expression matching any link.")
5764 (defconst org-match-sexp-depth 3
5765 "Number of stacked braces for sub/superscript matching.")
5767 (defun org-create-multibrace-regexp (left right n)
5768 "Create a regular expression which will match a balanced sexp.
5769 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5770 as single character strings.
5771 The regexp returned will match the entire expression including the
5772 delimiters. It will also define a single group which contains the
5773 match except for the outermost delimiters. The maximum depth of
5774 stacked delimiters is N. Escaping delimiters is not possible."
5775 (let* ((nothing (concat "[^" left right "]*?"))
5776 (or "\\|")
5777 (re nothing)
5778 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5779 (while (> n 1)
5780 (setq n (1- n)
5781 re (concat re or next)
5782 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5783 (concat left "\\(" re "\\)" right)))
5785 (defconst org-match-substring-regexp
5786 (concat
5787 "\\(\\S-\\)\\([_^]\\)\\("
5788 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5789 "\\|"
5790 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5791 "\\|"
5792 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5793 "The regular expression matching a sub- or superscript.")
5795 (defconst org-match-substring-with-braces-regexp
5796 (concat
5797 "\\(\\S-\\)\\([_^]\\)"
5798 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5799 "The regular expression matching a sub- or superscript, forcing braces.")
5801 (defun org-make-link-regexps ()
5802 "Update the link regular expressions.
5803 This should be called after the variable `org-link-parameters' has changed."
5804 (let ((types-re (regexp-opt (org-link-types) t)))
5805 (setq org-link-types-re
5806 (concat "\\`" types-re ":")
5807 org-link-re-with-space
5808 (concat "<?" types-re ":"
5809 "\\([^" org-non-link-chars " ]"
5810 "[^" org-non-link-chars "]*"
5811 "[^" org-non-link-chars " ]\\)>?")
5812 org-link-re-with-space2
5813 (concat "<?" types-re ":"
5814 "\\([^" org-non-link-chars " ]"
5815 "[^\t\n\r]*"
5816 "[^" org-non-link-chars " ]\\)>?")
5817 org-link-re-with-space3
5818 (concat "<?" types-re ":"
5819 "\\([^" org-non-link-chars " ]"
5820 "[^\t\n\r]*\\)")
5821 org-angle-link-re
5822 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5823 types-re)
5824 org-plain-link-re
5825 (concat
5826 "\\<" types-re ":"
5827 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5828 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5829 org-bracket-link-regexp
5830 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5831 org-bracket-link-analytic-regexp
5832 (concat
5833 "\\[\\["
5834 "\\(" types-re ":\\)?"
5835 "\\([^]]+\\)"
5836 "\\]"
5837 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5838 "\\]")
5839 org-bracket-link-analytic-regexp++
5840 (concat
5841 "\\[\\["
5842 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5843 "\\([^]]+\\)"
5844 "\\]"
5845 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5846 "\\]")
5847 org-any-link-re
5848 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5849 org-angle-link-re "\\)\\|\\("
5850 org-plain-link-re "\\)"))))
5852 (org-make-link-regexps)
5854 (defvar org-emph-face nil)
5856 (defun org-do-emphasis-faces (limit)
5857 "Run through the buffer and emphasize strings."
5858 (let (rtn a)
5859 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5860 (let* ((border (char-after (match-beginning 3)))
5861 (bre (regexp-quote (char-to-string border))))
5862 (when (and (not (= border (char-after (match-beginning 4))))
5863 (not (string-match-p (concat bre ".*" bre)
5864 (replace-regexp-in-string
5865 "\n" " "
5866 (substring (match-string 2) 1 -1)))))
5867 (setq rtn t)
5868 (setq a (assoc (match-string 3) org-emphasis-alist))
5869 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5870 'face
5871 (nth 1 a))
5872 (and (nth 2 a)
5873 (org-remove-flyspell-overlays-in
5874 (match-beginning 0) (match-end 0)))
5875 (add-text-properties (match-beginning 2) (match-end 2)
5876 '(font-lock-multiline t org-emphasis t))
5877 (when org-hide-emphasis-markers
5878 (add-text-properties (match-end 4) (match-beginning 5)
5879 '(invisible org-link))
5880 (add-text-properties (match-beginning 3) (match-end 3)
5881 '(invisible org-link)))))
5882 (goto-char (1+ (match-beginning 0))))
5883 rtn))
5885 (defun org-emphasize (&optional char)
5886 "Insert or change an emphasis, i.e. a font like bold or italic.
5887 If there is an active region, change that region to a new emphasis.
5888 If there is no region, just insert the marker characters and position
5889 the cursor between them.
5890 CHAR should be the marker character. If it is a space, it means to
5891 remove the emphasis of the selected region.
5892 If CHAR is not given (for example in an interactive call) it will be
5893 prompted for."
5894 (interactive)
5895 (let ((erc org-emphasis-regexp-components)
5896 (string "") beg end move s)
5897 (if (org-region-active-p)
5898 (setq beg (region-beginning)
5899 end (region-end)
5900 string (buffer-substring beg end))
5901 (setq move t))
5903 (unless char
5904 (message "Emphasis marker or tag: [%s]"
5905 (mapconcat #'car org-emphasis-alist ""))
5906 (setq char (read-char-exclusive)))
5907 (if (equal char ?\s)
5908 (setq s ""
5909 move nil)
5910 (unless (assoc (char-to-string char) org-emphasis-alist)
5911 (user-error "No such emphasis marker: \"%c\"" char))
5912 (setq s (char-to-string char)))
5913 (while (and (> (length string) 1)
5914 (equal (substring string 0 1) (substring string -1))
5915 (assoc (substring string 0 1) org-emphasis-alist))
5916 (setq string (substring string 1 -1)))
5917 (setq string (concat s string s))
5918 (when beg (delete-region beg end))
5919 (unless (or (bolp)
5920 (string-match (concat "[" (nth 0 erc) "\n]")
5921 (char-to-string (char-before (point)))))
5922 (insert " "))
5923 (unless (or (eobp)
5924 (string-match (concat "[" (nth 1 erc) "\n]")
5925 (char-to-string (char-after (point)))))
5926 (insert " ") (backward-char 1))
5927 (insert string)
5928 (and move (backward-char 1))))
5930 (defconst org-nonsticky-props
5931 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5933 (defsubst org-rear-nonsticky-at (pos)
5934 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5936 (defun org-activate-plain-links (limit)
5937 "Add link properties for plain links."
5938 (when (and (re-search-forward org-plain-link-re limit t)
5939 (not (org-in-src-block-p)))
5941 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5942 'face))
5943 (link (match-string-no-properties 0))
5944 (type (match-string-no-properties 1))
5945 (path (match-string-no-properties 2))
5946 (link-start (match-beginning 0))
5947 (link-end (match-end 0))
5948 (link-face (org-link-get-parameter type :face))
5949 (help-echo (org-link-get-parameter type :help-echo))
5950 (htmlize-link (org-link-get-parameter type :htmlize-link))
5951 (activate-func (org-link-get-parameter type :activate-func)))
5952 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5953 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5954 (add-text-properties (match-beginning 0) (match-end 0)
5955 (list
5956 'mouse-face (or (org-link-get-parameter type :mouse-face)
5957 'highlight)
5958 'face (cond
5959 ;; A function that returns a face
5960 ((functionp link-face)
5961 (funcall link-face path))
5962 ;; a face
5963 ((facep link-face)
5964 link-face)
5965 ;; An anonymous face
5966 ((consp link-face)
5967 link-face)
5968 ;; default
5970 'org-link))
5971 'help-echo (cond
5972 ((stringp help-echo)
5973 help-echo)
5974 ((functionp help-echo)
5975 help-echo)
5977 (concat "LINK: "
5978 (save-match-data
5979 (org-link-unescape link)))))
5980 'htmlize-link (cond
5981 ((functionp htmlize-link)
5982 (funcall htmlize-link path))
5984 `(:uri ,link)))
5985 'keymap (or (org-link-get-parameter type :keymap)
5986 org-mouse-map)
5987 'org-link-start (match-beginning 0)))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when activate-func
5990 (funcall activate-func link-start link-end path nil))
5991 t))))
5993 (defun org-activate-code (limit)
5994 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (remove-text-properties (match-beginning 0) (match-end 0)
5997 '(display t invisible t intangible t))
6000 (defcustom org-src-fontify-natively t
6001 "When non-nil, fontify code in code blocks.
6002 See also the `org-block' face."
6003 :type 'boolean
6004 :version "24.4"
6005 :package-version '(Org . "8.3")
6006 :group 'org-appearance
6007 :group 'org-babel)
6009 (defcustom org-allow-promoting-top-level-subtree nil
6010 "When non-nil, allow promoting a top level subtree.
6011 The leading star of the top level headline will be replaced
6012 by a #."
6013 :type 'boolean
6014 :version "24.1"
6015 :group 'org-appearance)
6017 (defun org-fontify-meta-lines-and-blocks (limit)
6018 (condition-case nil
6019 (org-fontify-meta-lines-and-blocks-1 limit)
6020 (error (message "org-mode fontification error in %S at %d"
6021 (current-buffer)
6022 (line-number-at-pos)))))
6024 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6025 "Fontify #+ lines and blocks."
6026 (let ((case-fold-search t))
6027 (when (re-search-forward
6028 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6029 limit t)
6030 (let ((beg (match-beginning 0))
6031 (block-start (match-end 0))
6032 (block-end nil)
6033 (lang (match-string 7))
6034 (beg1 (line-beginning-position 2))
6035 (dc1 (downcase (match-string 2)))
6036 (dc3 (downcase (match-string 3)))
6037 end end1 quoting block-type)
6038 (cond
6039 ((and (match-end 4) (equal dc3 "+begin"))
6040 ;; Truly a block
6041 (setq block-type (downcase (match-string 5))
6042 quoting (member block-type org-protecting-blocks))
6043 (when (re-search-forward
6044 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6045 nil t) ;; on purpose, we look further than LIMIT
6046 (setq end (min (point-max) (match-end 0))
6047 end1 (min (point-max) (1- (match-beginning 0))))
6048 (setq block-end (match-beginning 0))
6049 (when quoting
6050 (org-remove-flyspell-overlays-in beg1 end1)
6051 (remove-text-properties beg end
6052 '(display t invisible t intangible t)))
6053 (add-text-properties
6054 beg end '(font-lock-fontified t font-lock-multiline t))
6055 (add-text-properties beg beg1 '(face org-meta-line))
6056 (org-remove-flyspell-overlays-in beg beg1)
6057 (add-text-properties ; For end_src
6058 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6059 (org-remove-flyspell-overlays-in end1 end)
6060 (cond
6061 ((and lang (not (string= lang "")) org-src-fontify-natively)
6062 (org-src-font-lock-fontify-block lang block-start block-end)
6063 (add-text-properties beg1 block-end '(src-block t)))
6064 (quoting
6065 (add-text-properties beg1 (min (point-max) (1+ end1))
6066 (list 'face
6067 (list :inherit
6068 (let ((face-name
6069 (intern (format "org-block-%s" lang))))
6070 (append (and (facep face-name) (list face-name))
6071 '(org-block))))))) ; end of source block
6072 ((not org-fontify-quote-and-verse-blocks))
6073 ((string= block-type "quote")
6074 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6075 ((string= block-type "verse")
6076 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6077 (add-text-properties beg beg1 '(face org-block-begin-line))
6078 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6079 '(face org-block-end-line))
6081 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6082 (org-remove-flyspell-overlays-in
6083 (match-beginning 0)
6084 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6085 (add-text-properties
6086 beg (match-end 3)
6087 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6088 '(font-lock-fontified t invisible t)
6089 '(font-lock-fontified t face org-document-info-keyword)))
6090 (add-text-properties
6091 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6092 (if (string-equal dc1 "+title:")
6093 '(font-lock-fontified t face org-document-title)
6094 '(font-lock-fontified t face org-document-info))))
6095 ((equal dc1 "+caption:")
6096 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6097 (remove-text-properties (match-beginning 0) (match-end 0)
6098 '(display t invisible t intangible t))
6099 (add-text-properties (match-beginning 1) (match-end 3)
6100 '(font-lock-fontified t face org-meta-line))
6101 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6102 '(font-lock-fontified t face org-block))
6104 ((member dc3 '(" " ""))
6105 (org-remove-flyspell-overlays-in beg (match-end 0))
6106 (add-text-properties
6107 beg (match-end 0)
6108 '(font-lock-fontified t face font-lock-comment-face)))
6109 (t ;; just any other in-buffer setting, but not indented
6110 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6111 (remove-text-properties (match-beginning 0) (match-end 0)
6112 '(display t invisible t intangible t))
6113 (add-text-properties beg (match-end 0)
6114 '(font-lock-fontified t face org-meta-line))
6115 t))))))
6117 (defun org-fontify-drawers (limit)
6118 "Fontify drawers."
6119 (when (re-search-forward org-drawer-regexp limit t)
6120 (add-text-properties
6121 (match-beginning 0) (match-end 0)
6122 '(font-lock-fontified t face org-special-keyword))
6123 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6126 (defun org-fontify-macros (limit)
6127 "Fontify macros."
6128 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6129 (add-text-properties
6130 (match-beginning 0) (match-end 0)
6131 '(font-lock-fontified t face org-macro))
6132 (when org-hide-macro-markers
6133 (add-text-properties (match-end 2) (match-beginning 2)
6134 '(invisible t))
6135 (add-text-properties (match-beginning 1) (match-end 1)
6136 '(invisible t)))
6137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6140 (defun org-activate-angle-links (limit)
6141 "Add text properties for angle links."
6142 (when (and (re-search-forward org-angle-link-re limit t)
6143 (not (org-in-src-block-p)))
6144 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6145 (add-text-properties (match-beginning 0) (match-end 0)
6146 (list 'mouse-face 'highlight
6147 'keymap org-mouse-map
6148 'font-lock-multiline t))
6149 (org-rear-nonsticky-at (match-end 0))
6152 (defun org-activate-footnote-links (limit)
6153 "Add text properties for footnotes."
6154 (let ((fn (org-footnote-next-reference-or-definition limit)))
6155 (when fn
6156 (let* ((beg (nth 1 fn))
6157 (end (nth 2 fn))
6158 (label (car fn))
6159 (referencep (/= (line-beginning-position) beg)))
6160 (when (and referencep (nth 3 fn))
6161 (save-excursion
6162 (goto-char beg)
6163 (search-forward (or label "fn:"))
6164 (org-remove-flyspell-overlays-in beg (match-end 0))))
6165 (add-text-properties beg end
6166 (list 'mouse-face 'highlight
6167 'keymap org-mouse-map
6168 'help-echo
6169 (if referencep "Footnote reference"
6170 "Footnote definition")
6171 'font-lock-fontified t
6172 'font-lock-multiline t
6173 'face 'org-footnote))))))
6175 (defun org-activate-bracket-links (limit)
6176 "Add text properties for bracketed links."
6177 (when (and (re-search-forward org-bracket-link-regexp limit t)
6178 (not (org-in-src-block-p)))
6179 (let* ((hl (match-string-no-properties 1))
6180 (type (save-match-data
6181 (and (string-match org-plain-link-re hl)
6182 (match-string-no-properties 1 hl))))
6183 (path (save-match-data
6184 (and (string-match org-plain-link-re hl)
6185 (match-string-no-properties 2 hl))))
6186 (link-start (match-beginning 0))
6187 (link-end (match-end 0))
6188 (bracketp t)
6189 (help-echo (org-link-get-parameter type :help-echo))
6190 (help (cond
6191 ((stringp help-echo)
6192 help-echo)
6193 ((functionp help-echo)
6194 help-echo)
6196 (concat "LINK: "
6197 (save-match-data
6198 (org-link-unescape hl))))))
6199 (link-face (org-link-get-parameter type :face))
6200 (face (cond
6201 ;; A function that returns a face
6202 ((functionp link-face)
6203 (funcall link-face path))
6204 ;; a face
6205 ((facep link-face)
6206 link-face)
6207 ;; An anonymous face
6208 ((consp link-face)
6209 link-face)
6210 ;; default
6212 'org-link)))
6213 (keymap (or (org-link-get-parameter type :keymap)
6214 org-mouse-map))
6215 (mouse-face (or (org-link-get-parameter type :mouse-face)
6216 'highlight))
6217 (htmlize (org-link-get-parameter type :htmlize-link))
6218 (htmlize-link (cond
6219 ((functionp htmlize)
6220 (funcall htmlize))
6222 `(:uri ,(format "%s:%s" type path)))))
6223 (activate-func (org-link-get-parameter type :activate-func))
6224 ;; invisible part
6225 (ip (list 'invisible (or
6226 (org-link-get-parameter type :display)
6227 'org-link)
6228 'face face
6229 'keymap keymap
6230 'mouse-face mouse-face
6231 'font-lock-multiline t
6232 'help-echo help
6233 'htmlize-link htmlize-link))
6234 ;; visible part
6235 (vp (list 'keymap keymap
6236 'face face
6237 'mouse-face mouse-face
6238 'font-lock-multiline t
6239 'help-echo help
6240 'htmlize-link htmlize-link)))
6241 ;; We need to remove the invisible property here. Table narrowing
6242 ;; may have made some of this invisible.
6243 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6244 (remove-text-properties (match-beginning 0) (match-end 0)
6245 '(invisible nil))
6246 (if (match-end 3)
6247 (progn
6248 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6249 (org-rear-nonsticky-at (match-beginning 3))
6250 (add-text-properties (match-beginning 3) (match-end 3) vp)
6251 (org-rear-nonsticky-at (match-end 3))
6252 (add-text-properties (match-end 3) (match-end 0) ip)
6253 (org-rear-nonsticky-at (match-end 0)))
6254 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6255 (org-rear-nonsticky-at (match-beginning 1))
6256 (add-text-properties (match-beginning 1) (match-end 1) vp)
6257 (org-rear-nonsticky-at (match-end 1))
6258 (add-text-properties (match-end 1) (match-end 0) ip)
6259 (org-rear-nonsticky-at (match-end 0)))
6260 (when activate-func
6261 (funcall activate-func link-start link-end path bracketp))
6262 t)))
6264 (defun org-activate-dates (limit)
6265 "Add text properties for dates."
6266 (when (and (re-search-forward org-tsr-regexp-both limit t)
6267 (not (equal (char-before (match-beginning 0)) 91)))
6268 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6269 (add-text-properties (match-beginning 0) (match-end 0)
6270 (list 'mouse-face 'highlight
6271 'keymap org-mouse-map))
6272 (org-rear-nonsticky-at (match-end 0))
6273 (when org-display-custom-times
6274 (if (match-end 3)
6275 (org-display-custom-time (match-beginning 3) (match-end 3))
6276 (org-display-custom-time (match-beginning 1) (match-end 1))))
6279 (defvar-local org-target-link-regexp nil
6280 "Regular expression matching radio targets in plain text.")
6282 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6283 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6284 border border border))
6285 "Regular expression matching a link target.")
6287 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6288 "Regular expression matching a radio target.")
6290 (defconst org-any-target-regexp
6291 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6292 "Regular expression matching any target.")
6294 (defun org-activate-target-links (limit)
6295 "Add text properties for target matches."
6296 (when org-target-link-regexp
6297 (let ((case-fold-search t))
6298 (when (re-search-forward org-target-link-regexp limit t)
6299 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6300 (add-text-properties (match-beginning 1) (match-end 1)
6301 (list 'mouse-face 'highlight
6302 'keymap org-mouse-map
6303 'help-echo "Radio target link"
6304 'org-linked-text t))
6305 (org-rear-nonsticky-at (match-end 1))
6306 t))))
6308 (defun org-update-radio-target-regexp ()
6309 "Find all radio targets in this file and update the regular expression.
6310 Also refresh fontification if needed."
6311 (interactive)
6312 (let ((old-regexp org-target-link-regexp)
6313 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6314 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6315 (targets
6316 (org-with-wide-buffer
6317 (goto-char (point-min))
6318 (let (rtn)
6319 (while (re-search-forward org-radio-target-regexp nil t)
6320 ;; Make sure point is really within the object.
6321 (backward-char)
6322 (let ((obj (org-element-context)))
6323 (when (eq (org-element-type obj) 'radio-target)
6324 (cl-pushnew (org-element-property :value obj) rtn
6325 :test #'equal))))
6326 rtn))))
6327 (setq org-target-link-regexp
6328 (and targets
6329 (concat before-re
6330 (mapconcat
6331 (lambda (x)
6332 (replace-regexp-in-string
6333 " +" "\\s-+" (regexp-quote x) t t))
6334 targets
6335 "\\|")
6336 after-re)))
6337 (unless (equal old-regexp org-target-link-regexp)
6338 ;; Clean-up cache.
6339 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6340 ((not org-target-link-regexp) old-regexp)
6342 (concat before-re
6343 (mapconcat
6344 (lambda (re)
6345 (substring re (length before-re)
6346 (- (length after-re))))
6347 (list old-regexp org-target-link-regexp)
6348 "\\|")
6349 after-re)))))
6350 (org-with-wide-buffer
6351 (goto-char (point-min))
6352 (while (re-search-forward regexp nil t)
6353 (org-element-cache-refresh (match-beginning 1)))))
6354 ;; Re fontify buffer.
6355 (when (memq 'radio org-highlight-links)
6356 (org-restart-font-lock)))))
6358 (defun org-hide-wide-columns (limit)
6359 (let (s e)
6360 (setq s (text-property-any (point) (or limit (point-max))
6361 'org-cwidth t))
6362 (when s
6363 (setq e (next-single-property-change s 'org-cwidth))
6364 (add-text-properties s e '(invisible org-cwidth))
6365 (goto-char e)
6366 t)))
6368 (defvar org-latex-and-related-regexp nil
6369 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6371 (defun org-compute-latex-and-related-regexp ()
6372 "Compute regular expression for LaTeX, entities and sub/superscript.
6373 Result depends on variable `org-highlight-latex-and-related'."
6374 (setq-local
6375 org-latex-and-related-regexp
6376 (let* ((re-sub
6377 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6378 ((eq org-use-sub-superscripts '{})
6379 (list org-match-substring-with-braces-regexp))
6380 (org-use-sub-superscripts (list org-match-substring-regexp))))
6381 (re-latex
6382 (when (memq 'latex org-highlight-latex-and-related)
6383 (let ((matchers (plist-get org-format-latex-options :matchers)))
6384 (delq nil
6385 (mapcar (lambda (x)
6386 (and (member (car x) matchers) (nth 1 x)))
6387 org-latex-regexps)))))
6388 (re-entities
6389 (when (memq 'entities org-highlight-latex-and-related)
6390 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6391 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6393 (defun org-do-latex-and-related (limit)
6394 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6395 LIMIT bounds the search for syntax to highlight. Stop at first
6396 highlighted object, if any. Return t if some highlighting was
6397 done, nil otherwise."
6398 (when (org-string-nw-p org-latex-and-related-regexp)
6399 (catch 'found
6400 (while (re-search-forward org-latex-and-related-regexp limit t)
6401 (unless
6402 (cl-some
6403 (lambda (f)
6404 (memq f '(org-code org-verbatim underline org-special-keyword)))
6405 (save-excursion
6406 (goto-char (1+ (match-beginning 0)))
6407 (face-at-point nil t)))
6408 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6409 '(?_ ?^))
6411 0)))
6412 (font-lock-prepend-text-property
6413 (+ offset (match-beginning 0)) (match-end 0)
6414 'face 'org-latex-and-related)
6415 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6416 '(font-lock-multiline t)))
6417 (throw 'found t)))
6418 nil)))
6420 (defun org-restart-font-lock ()
6421 "Restart `font-lock-mode', to force refontification."
6422 (when (and (boundp 'font-lock-mode) font-lock-mode)
6423 (font-lock-mode -1)
6424 (font-lock-mode 1)))
6426 (defun org-activate-tags (limit)
6427 (when (re-search-forward
6428 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6429 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6430 (add-text-properties (match-beginning 1) (match-end 1)
6431 (list 'mouse-face 'highlight
6432 'keymap org-mouse-map))
6433 (org-rear-nonsticky-at (match-end 1))
6436 (defun org-outline-level ()
6437 "Compute the outline level of the heading at point.
6439 If this is called at a normal headline, the level is the number
6440 of stars. Use `org-reduced-level' to remove the effect of
6441 `org-odd-levels'. Unlike to `org-current-level', this function
6442 takes into consideration inlinetasks."
6443 (org-with-wide-buffer
6444 (end-of-line)
6445 (if (re-search-backward org-outline-regexp-bol nil t)
6446 (1- (- (match-end 0) (match-beginning 0)))
6447 0)))
6449 (defvar org-font-lock-keywords nil)
6451 (defsubst org-re-property (property &optional literal allow-null value)
6452 "Return a regexp matching a PROPERTY line.
6454 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6455 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6456 non-nil, match properties even without a value.
6458 Match group 3 is set to the value when it exists. If there is no
6459 value and ALLOW-NULL is non-nil, it is set to the empty string.
6461 With optional argument VALUE, match only property lines with
6462 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6463 unless LITERAL is non-nil."
6464 (concat
6465 "^\\(?4:[ \t]*\\)"
6466 (format "\\(?1::\\(?2:%s\\):\\)"
6467 (if literal property (regexp-quote property)))
6468 (cond (value
6469 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6470 (if literal value (regexp-quote value))))
6471 (allow-null
6472 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6474 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6476 (defconst org-property-re
6477 (org-re-property "\\S-+" 'literal t)
6478 "Regular expression matching a property line.
6479 There are four matching groups:
6480 1: :PROPKEY: including the leading and trailing colon,
6481 2: PROPKEY without the leading and trailing colon,
6482 3: PROPVAL without leading or trailing spaces,
6483 4: the indentation of the current line,
6484 5: trailing whitespace.")
6486 (defvar org-font-lock-hook nil
6487 "Functions to be called for special font lock stuff.")
6489 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6491 (defvar org-font-lock-set-keywords-hook nil
6492 "Functions that can manipulate `org-font-lock-extra-keywords'.
6493 This is called after `org-font-lock-extra-keywords' is defined, but before
6494 it is installed to be used by font lock. This can be useful if something
6495 needs to be inserted at a specific position in the font-lock sequence.")
6497 (defun org-font-lock-hook (limit)
6498 "Run `org-font-lock-hook' within LIMIT."
6499 (run-hook-with-args 'org-font-lock-hook limit))
6501 (defun org-set-font-lock-defaults ()
6502 "Set font lock defaults for the current buffer."
6503 (let* ((em org-fontify-emphasized-text)
6504 (lk org-highlight-links)
6505 (org-font-lock-extra-keywords
6506 (list
6507 ;; Call the hook
6508 '(org-font-lock-hook)
6509 ;; Headlines
6510 `(,(if org-fontify-whole-heading-line
6511 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6512 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6513 (1 (org-get-level-face 1))
6514 (2 (org-get-level-face 2))
6515 (3 (org-get-level-face 3)))
6516 ;; Table lines
6517 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6518 (1 'org-table t))
6519 ;; Table internals
6520 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6521 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6522 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6523 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6524 ;; Drawers
6525 '(org-fontify-drawers)
6526 ;; Properties
6527 (list org-property-re
6528 '(1 'org-special-keyword t)
6529 '(3 'org-property-value t))
6530 ;; Links
6531 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6532 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6533 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6534 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6535 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6536 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6537 (when (memq 'footnote lk) '(org-activate-footnote-links))
6538 ;; Targets.
6539 (list org-any-target-regexp '(0 'org-target t))
6540 ;; Diary sexps.
6541 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6542 ;; Macro
6543 '(org-fontify-macros)
6544 '(org-hide-wide-columns (0 nil append))
6545 ;; TODO keyword
6546 (list (format org-heading-keyword-regexp-format
6547 org-todo-regexp)
6548 '(2 (org-get-todo-face 2) t))
6549 ;; DONE
6550 (if org-fontify-done-headline
6551 (list (format org-heading-keyword-regexp-format
6552 (concat
6553 "\\(?:"
6554 (mapconcat 'regexp-quote org-done-keywords "\\|")
6555 "\\)"))
6556 '(2 'org-headline-done t))
6557 nil)
6558 ;; Priorities
6559 '(org-font-lock-add-priority-faces)
6560 ;; Tags
6561 '(org-font-lock-add-tag-faces)
6562 ;; Tags groups
6563 (when (and org-group-tags org-tag-groups-alist)
6564 (list (concat org-outline-regexp-bol ".+\\(:"
6565 (regexp-opt (mapcar 'car org-tag-groups-alist))
6566 ":\\).*$")
6567 '(1 'org-tag-group prepend)))
6568 ;; Special keywords
6569 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6570 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6571 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6572 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6573 ;; Emphasis
6574 (when em '(org-do-emphasis-faces))
6575 ;; Checkboxes
6576 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6577 1 'org-checkbox prepend)
6578 (when (cdr (assq 'checkbox org-list-automatic-rules))
6579 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6580 (0 (org-get-checkbox-statistics-face) t)))
6581 ;; Description list items
6582 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6583 1 'org-list-dt prepend)
6584 ;; ARCHIVEd headings
6585 (list (concat
6586 org-outline-regexp-bol
6587 "\\(.*:" org-archive-tag ":.*\\)")
6588 '(1 'org-archived prepend))
6589 ;; Specials
6590 '(org-do-latex-and-related)
6591 '(org-fontify-entities)
6592 '(org-raise-scripts)
6593 ;; Code
6594 '(org-activate-code (1 'org-code t))
6595 ;; COMMENT
6596 (list (format
6597 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6598 org-todo-regexp
6599 org-comment-string)
6600 '(9 'org-special-keyword t))
6601 ;; Blocks and meta lines
6602 '(org-fontify-meta-lines-and-blocks))))
6603 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6604 (run-hooks 'org-font-lock-set-keywords-hook)
6605 ;; Now set the full font-lock-keywords
6606 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6607 (setq-local font-lock-defaults
6608 '(org-font-lock-keywords t nil nil backward-paragraph))
6609 (kill-local-variable 'font-lock-keywords)
6610 nil))
6612 (defun org-toggle-pretty-entities ()
6613 "Toggle the composition display of entities as UTF8 characters."
6614 (interactive)
6615 (setq-local org-pretty-entities (not org-pretty-entities))
6616 (org-restart-font-lock)
6617 (if org-pretty-entities
6618 (message "Entities are now displayed as UTF8 characters")
6619 (save-restriction
6620 (widen)
6621 (decompose-region (point-min) (point-max))
6622 (message "Entities are now displayed as plain text"))))
6624 (defvar-local org-custom-properties-overlays nil
6625 "List of overlays used for custom properties.")
6627 (defun org-toggle-custom-properties-visibility ()
6628 "Display or hide properties in `org-custom-properties'."
6629 (interactive)
6630 (if org-custom-properties-overlays
6631 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6632 (setq org-custom-properties-overlays nil))
6633 (when org-custom-properties
6634 (org-with-wide-buffer
6635 (goto-char (point-min))
6636 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6637 (while (re-search-forward regexp nil t)
6638 (let ((end (cdr (save-match-data (org-get-property-block)))))
6639 (when (and end (< (point) end))
6640 ;; Hide first custom property in current drawer.
6641 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6642 (overlay-put o 'invisible t)
6643 (overlay-put o 'org-custom-property t)
6644 (push o org-custom-properties-overlays))
6645 ;; Hide additional custom properties in the same drawer.
6646 (while (re-search-forward regexp end t)
6647 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6648 (overlay-put o 'invisible t)
6649 (overlay-put o 'org-custom-property t)
6650 (push o org-custom-properties-overlays)))))
6651 ;; Each entry is limited to a single property drawer.
6652 (outline-next-heading)))))))
6654 (defun org-fontify-entities (limit)
6655 "Find an entity to fontify."
6656 (let (ee)
6657 (when org-pretty-entities
6658 (catch 'match
6659 ;; "\_ "-family is left out on purpose. Only the first one,
6660 ;; i.e., "\_ ", could be fontified anyway, and it would be
6661 ;; confusing when adding a second white space character.
6662 (while (re-search-forward
6663 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6664 limit t)
6665 (when (and (not (org-at-comment-p))
6666 (setq ee (org-entity-get (match-string 1)))
6667 (= (length (nth 6 ee)) 1))
6668 (let* ((end (if (equal (match-string 2) "{}")
6669 (match-end 2)
6670 (match-end 1))))
6671 (add-text-properties
6672 (match-beginning 0) end
6673 (list 'font-lock-fontified t))
6674 (compose-region (match-beginning 0) end
6675 (nth 6 ee) nil)
6676 (backward-char 1)
6677 (throw 'match t))))
6678 nil))))
6680 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6681 "Fontify string S like in Org-mode."
6682 (with-temp-buffer
6683 (insert s)
6684 (let ((org-odd-levels-only odd-levels))
6685 (org-mode)
6686 (org-font-lock-ensure)
6687 (buffer-string))))
6689 (defvar org-m nil)
6690 (defvar org-l nil)
6691 (defvar org-f nil)
6692 (defun org-get-level-face (n)
6693 "Get the right face for match N in font-lock matching of headlines."
6694 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6695 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6696 (if org-cycle-level-faces
6697 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6698 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6699 (cond
6700 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6701 ((eq n 2) org-f)
6702 (t (unless org-level-color-stars-only org-f))))
6704 (defun org-face-from-face-or-color (context inherit face-or-color)
6705 "Create a face list that inherits INHERIT, but sets the foreground color.
6706 When FACE-OR-COLOR is not a string, just return it."
6707 (if (stringp face-or-color)
6708 (list :inherit inherit
6709 (cdr (assoc context org-faces-easy-properties))
6710 face-or-color)
6711 face-or-color))
6713 (defun org-get-todo-face (kwd)
6714 "Get the right face for a TODO keyword KWD.
6715 If KWD is a number, get the corresponding match group."
6716 (when (numberp kwd) (setq kwd (match-string kwd)))
6717 (or (org-face-from-face-or-color
6718 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6719 (and (member kwd org-done-keywords) 'org-done)
6720 'org-todo))
6722 (defun org-get-priority-face (priority)
6723 "Get the right face for PRIORITY.
6724 PRIORITY is a character."
6725 (or (org-face-from-face-or-color
6726 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6727 'org-priority))
6729 (defun org-get-tag-face (tag)
6730 "Get the right face for TAG.
6731 If TAG is a number, get the corresponding match group."
6732 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6733 (or (org-face-from-face-or-color
6734 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6735 'org-tag)))
6737 (defun org-font-lock-add-priority-faces (limit)
6738 "Add the special priority faces."
6739 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6740 (add-text-properties
6741 (match-beginning 1) (match-end 1)
6742 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6743 'font-lock-fontified t))))
6745 (defun org-font-lock-add-tag-faces (limit)
6746 "Add the special tag faces."
6747 (when (and org-tag-faces org-tags-special-faces-re)
6748 (while (re-search-forward org-tags-special-faces-re limit t)
6749 (add-text-properties (match-beginning 1) (match-end 1)
6750 (list 'face (org-get-tag-face 1)
6751 'font-lock-fontified t))
6752 (backward-char 1))))
6754 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6755 "Remove fontification and activation overlays from links."
6756 (font-lock-default-unfontify-region beg end)
6757 (let* ((buffer-undo-list t)
6758 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6759 (inhibit-modification-hooks t)
6760 deactivate-mark buffer-file-name buffer-file-truename)
6761 (decompose-region beg end)
6762 (remove-text-properties beg end
6763 '(mouse-face t keymap t org-linked-text t
6764 invisible t intangible t
6765 org-emphasis t))
6766 (org-remove-font-lock-display-properties beg end)))
6768 (defconst org-script-display '(((raise -0.3) (height 0.7))
6769 ((raise 0.3) (height 0.7))
6770 ((raise -0.5))
6771 ((raise 0.5)))
6772 "Display properties for showing superscripts and subscripts.")
6774 (defun org-remove-font-lock-display-properties (beg end)
6775 "Remove specific display properties that have been added by font lock.
6776 The will remove the raise properties that are used to show superscripts
6777 and subscripts."
6778 (let (next prop)
6779 (while (< beg end)
6780 (setq next (next-single-property-change beg 'display nil end)
6781 prop (get-text-property beg 'display))
6782 (when (member prop org-script-display)
6783 (put-text-property beg next 'display nil))
6784 (setq beg next))))
6786 (defun org-raise-scripts (limit)
6787 "Add raise properties to sub/superscripts."
6788 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6789 (re-search-forward
6790 (if (eq org-use-sub-superscripts t)
6791 org-match-substring-regexp
6792 org-match-substring-with-braces-regexp)
6793 limit t))
6794 (let* ((pos (point)) table-p comment-p
6795 (mpos (match-beginning 3))
6796 (emph-p (get-text-property mpos 'org-emphasis))
6797 (link-p (get-text-property mpos 'mouse-face))
6798 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6799 (goto-char (point-at-bol))
6800 (setq table-p (looking-at-p org-table-dataline-regexp)
6801 comment-p (looking-at-p "^[ \t]*#[ +]"))
6802 (goto-char pos)
6803 ;; Handle a_b^c
6804 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6805 (unless (or comment-p emph-p link-p keyw-p)
6806 (put-text-property (match-beginning 3) (match-end 0)
6807 'display
6808 (if (equal (char-after (match-beginning 2)) ?^)
6809 (nth (if table-p 3 1) org-script-display)
6810 (nth (if table-p 2 0) org-script-display)))
6811 (add-text-properties (match-beginning 2) (match-end 2)
6812 (list 'invisible t
6813 'org-dwidth t 'org-dwidth-n 1))
6814 (if (and (eq (char-after (match-beginning 3)) ?{)
6815 (eq (char-before (match-end 3)) ?}))
6816 (progn
6817 (add-text-properties
6818 (match-beginning 3) (1+ (match-beginning 3))
6819 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6820 (add-text-properties
6821 (1- (match-end 3)) (match-end 3)
6822 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6823 t)))
6825 ;;;; Visibility cycling, including org-goto and indirect buffer
6827 ;;; Cycling
6829 (defvar-local org-cycle-global-status nil)
6830 (put 'org-cycle-global-status 'org-state t)
6831 (defvar-local org-cycle-subtree-status nil)
6832 (put 'org-cycle-subtree-status 'org-state t)
6834 (defvar org-inlinetask-min-level)
6836 (defun org-unlogged-message (&rest args)
6837 "Display a message, but avoid logging it in the *Messages* buffer."
6838 (let ((message-log-max nil))
6839 (apply 'message args)))
6841 ;;;###autoload
6842 (defun org-cycle (&optional arg)
6843 "TAB-action and visibility cycling for Org-mode.
6845 This is the command invoked in Org-mode by the TAB key. Its main purpose
6846 is outline visibility cycling, but it also invokes other actions
6847 in special contexts.
6849 - When this function is called with a prefix argument, rotate the entire
6850 buffer through 3 states (global cycling)
6851 1. OVERVIEW: Show only top-level headlines.
6852 2. CONTENTS: Show all headlines of all levels, but no body text.
6853 3. SHOW ALL: Show everything.
6854 With a double \\[universal-argument] prefix argument, \
6855 switch to the startup visibility,
6856 determined by the variable `org-startup-folded', and by any VISIBILITY
6857 properties in the buffer.
6858 With a triple \\[universal-argument] prefix argument, \
6859 show the entire buffer, including any drawers.
6861 - When inside a table, re-align the table and move to the next field.
6863 - When point is at the beginning of a headline, rotate the subtree started
6864 by this line through 3 different states (local cycling)
6865 1. FOLDED: Only the main headline is shown.
6866 2. CHILDREN: The main headline and the direct children are shown.
6867 From this state, you can move to one of the children
6868 and zoom in further.
6869 3. SUBTREE: Show the entire subtree, including body text.
6870 If there is no subtree, switch directly from CHILDREN to FOLDED.
6872 - When point is at the beginning of an empty headline and the variable
6873 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6874 of the headline by demoting and promoting it to likely levels. This
6875 speeds up creation document structure by pressing TAB once or several
6876 times right after creating a new headline.
6878 - When there is a numeric prefix, go up to a heading with level ARG, do
6879 a `show-subtree' and return to the previous cursor position. If ARG
6880 is negative, go up that many levels.
6882 - When point is not at the beginning of a headline, execute the global
6883 binding for TAB, which is re-indenting the line. See the option
6884 `org-cycle-emulate-tab' for details.
6886 - Special case: if point is at the beginning of the buffer and there is
6887 no headline in line 1, this function will act as if called with prefix arg
6888 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6889 But only if also the variable `org-cycle-global-at-bob' is t."
6890 (interactive "P")
6891 (org-load-modules-maybe)
6892 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6893 (and org-cycle-level-after-item/entry-creation
6894 (or (org-cycle-level)
6895 (org-cycle-item-indentation))))
6896 (let* ((limit-level
6897 (or org-cycle-max-level
6898 (and (boundp 'org-inlinetask-min-level)
6899 org-inlinetask-min-level
6900 (1- org-inlinetask-min-level))))
6901 (nstars (and limit-level
6902 (if org-odd-levels-only
6903 (and limit-level (1- (* limit-level 2)))
6904 limit-level)))
6905 (org-outline-regexp
6906 (if (not (derived-mode-p 'org-mode))
6907 outline-regexp
6908 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6909 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6910 (not (looking-at org-outline-regexp))))
6911 (org-cycle-hook
6912 (if bob-special
6913 (delq 'org-optimize-window-after-visibility-change
6914 (copy-sequence org-cycle-hook))
6915 org-cycle-hook))
6916 (pos (point)))
6918 (when (or bob-special (equal arg '(4)))
6919 ;; special case: use global cycling
6920 (setq arg t))
6922 (cond
6924 ((equal arg '(16))
6925 (setq last-command 'dummy)
6926 (org-set-startup-visibility)
6927 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6929 ((equal arg '(64))
6930 (outline-show-all)
6931 (org-unlogged-message "Entire buffer visible, including drawers"))
6933 ;; Try cdlatex TAB completion
6934 ((org-try-cdlatex-tab))
6936 ;; Table: enter it or move to the next field.
6937 ((org-at-table-p 'any)
6938 (if (org-at-table.el-p)
6939 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6940 Use \\[org-edit-special] to edit table.el tables"))
6941 (if arg (org-table-edit-field t)
6942 (org-table-justify-field-maybe)
6943 (call-interactively 'org-table-next-field))))
6945 ((run-hook-with-args-until-success
6946 'org-tab-after-check-for-table-hook))
6948 ;; Global cycling: delegate to `org-cycle-internal-global'.
6949 ((eq arg t) (org-cycle-internal-global))
6951 ;; Drawers: delegate to `org-flag-drawer'.
6952 ((save-excursion
6953 (beginning-of-line 1)
6954 (looking-at org-drawer-regexp))
6955 (org-flag-drawer ; toggle block visibility
6956 (not (get-char-property (match-end 0) 'invisible))))
6958 ;; Show-subtree, ARG levels up from here.
6959 ((integerp arg)
6960 (save-excursion
6961 (org-back-to-heading)
6962 (outline-up-heading (if (< arg 0) (- arg)
6963 (- (funcall outline-level) arg)))
6964 (org-show-subtree)))
6966 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6967 ((and (featurep 'org-inlinetask)
6968 (org-inlinetask-at-task-p)
6969 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6970 (org-inlinetask-toggle-visibility))
6972 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6973 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6974 (save-excursion (move-beginning-of-line 1)
6975 (looking-at org-outline-regexp)))
6976 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6977 (org-cycle-internal-local))
6979 ;; From there: TAB emulation and template completion.
6980 (buffer-read-only (org-back-to-heading))
6982 ((run-hook-with-args-until-success
6983 'org-tab-after-check-for-cycling-hook))
6985 ((org-try-structure-completion))
6987 ((run-hook-with-args-until-success
6988 'org-tab-before-tab-emulation-hook))
6990 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6991 (or (not (bolp))
6992 (not (looking-at org-outline-regexp))))
6993 (call-interactively (global-key-binding "\t")))
6995 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6996 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6997 (or (and (eq org-cycle-emulate-tab 'white)
6998 (= (match-end 0) (point-at-eol)))
6999 (and (eq org-cycle-emulate-tab 'whitestart)
7000 (>= (match-end 0) pos))))
7002 (eq org-cycle-emulate-tab t))
7003 (call-interactively (global-key-binding "\t")))
7005 (t (save-excursion
7006 (org-back-to-heading)
7007 (org-cycle)))))))
7009 (defun org-cycle-internal-global ()
7010 "Do the global cycling action."
7011 ;; Hack to avoid display of messages for .org attachments in Gnus
7012 (let ((ga (string-match "\\*fontification" (buffer-name))))
7013 (cond
7014 ((and (eq last-command this-command)
7015 (eq org-cycle-global-status 'overview))
7016 ;; We just created the overview - now do table of contents
7017 ;; This can be slow in very large buffers, so indicate action
7018 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7019 (unless ga (org-unlogged-message "CONTENTS..."))
7020 (org-content)
7021 (unless ga (org-unlogged-message "CONTENTS...done"))
7022 (setq org-cycle-global-status 'contents)
7023 (run-hook-with-args 'org-cycle-hook 'contents))
7025 ((and (eq last-command this-command)
7026 (eq org-cycle-global-status 'contents))
7027 ;; We just showed the table of contents - now show everything
7028 (run-hook-with-args 'org-pre-cycle-hook 'all)
7029 (outline-show-all)
7030 (unless ga (org-unlogged-message "SHOW ALL"))
7031 (setq org-cycle-global-status 'all)
7032 (run-hook-with-args 'org-cycle-hook 'all))
7035 ;; Default action: go to overview
7036 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7037 (org-overview)
7038 (unless ga (org-unlogged-message "OVERVIEW"))
7039 (setq org-cycle-global-status 'overview)
7040 (run-hook-with-args 'org-cycle-hook 'overview)))))
7042 (defvar org-called-with-limited-levels nil
7043 "Non-nil when `org-with-limited-levels' is currently active.")
7045 (defun org-cycle-internal-local ()
7046 "Do the local cycling action."
7047 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7048 ;; First, determine end of headline (EOH), end of subtree or item
7049 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7050 (save-excursion
7051 (if (org-at-item-p)
7052 (progn
7053 (beginning-of-line)
7054 (setq struct (org-list-struct))
7055 (setq eoh (point-at-eol))
7056 (setq eos (org-list-get-item-end-before-blank (point) struct))
7057 (setq has-children (org-list-has-child-p (point) struct)))
7058 (org-back-to-heading)
7059 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7060 (setq eos (save-excursion (org-end-of-subtree t t)
7061 (when (bolp) (backward-char)) (point)))
7062 (setq has-children
7063 (or (save-excursion
7064 (let ((level (funcall outline-level)))
7065 (outline-next-heading)
7066 (and (org-at-heading-p t)
7067 (> (funcall outline-level) level))))
7068 (save-excursion
7069 (org-list-search-forward (org-item-beginning-re) eos t)))))
7070 ;; Determine end invisible part of buffer (EOL)
7071 (beginning-of-line 2)
7072 (while (and (not (eobp)) ;This is like `next-line'.
7073 (get-char-property (1- (point)) 'invisible))
7074 (goto-char (next-single-char-property-change (point) 'invisible))
7075 (and (eolp) (beginning-of-line 2)))
7076 (setq eol (point)))
7077 ;; Find out what to do next and set `this-command'
7078 (cond
7079 ((= eos eoh)
7080 ;; Nothing is hidden behind this heading
7081 (unless (org-before-first-heading-p)
7082 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7083 (org-unlogged-message "EMPTY ENTRY")
7084 (setq org-cycle-subtree-status nil)
7085 (save-excursion
7086 (goto-char eos)
7087 (outline-next-heading)
7088 (when (outline-invisible-p) (org-flag-heading nil))))
7089 ((and (or (>= eol eos)
7090 (not (string-match "\\S-" (buffer-substring eol eos))))
7091 (or has-children
7092 (not (setq children-skipped
7093 org-cycle-skip-children-state-if-no-children))))
7094 ;; Entire subtree is hidden in one line: children view
7095 (unless (org-before-first-heading-p)
7096 (run-hook-with-args 'org-pre-cycle-hook 'children))
7097 (if (org-at-item-p)
7098 (org-list-set-item-visibility (point-at-bol) struct 'children)
7099 (org-show-entry)
7100 (org-with-limited-levels (org-show-children))
7101 ;; FIXME: This slows down the func way too much.
7102 ;; How keep drawers hidden in subtree anyway?
7103 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7104 ;; (org-cycle-hide-drawers 'subtree))
7106 ;; Fold every list in subtree to top-level items.
7107 (when (eq org-cycle-include-plain-lists 'integrate)
7108 (save-excursion
7109 (org-back-to-heading)
7110 (while (org-list-search-forward (org-item-beginning-re) eos t)
7111 (beginning-of-line 1)
7112 (let* ((struct (org-list-struct))
7113 (prevs (org-list-prevs-alist struct))
7114 (end (org-list-get-bottom-point struct)))
7115 (dolist (e (org-list-get-all-items (point) struct prevs))
7116 (org-list-set-item-visibility e struct 'folded))
7117 (goto-char (if (< end eos) end eos)))))))
7118 (org-unlogged-message "CHILDREN")
7119 (save-excursion
7120 (goto-char eos)
7121 (outline-next-heading)
7122 (when (outline-invisible-p) (org-flag-heading nil)))
7123 (setq org-cycle-subtree-status 'children)
7124 (unless (org-before-first-heading-p)
7125 (run-hook-with-args 'org-cycle-hook 'children)))
7126 ((or children-skipped
7127 (and (eq last-command this-command)
7128 (eq org-cycle-subtree-status 'children)))
7129 ;; We just showed the children, or no children are there,
7130 ;; now show everything.
7131 (unless (org-before-first-heading-p)
7132 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7133 (outline-flag-region eoh eos nil)
7134 (org-unlogged-message
7135 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7136 (setq org-cycle-subtree-status 'subtree)
7137 (unless (org-before-first-heading-p)
7138 (run-hook-with-args 'org-cycle-hook 'subtree)))
7140 ;; Default action: hide the subtree.
7141 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7142 (outline-flag-region eoh eos t)
7143 (org-unlogged-message "FOLDED")
7144 (setq org-cycle-subtree-status 'folded)
7145 (unless (org-before-first-heading-p)
7146 (run-hook-with-args 'org-cycle-hook 'folded))))))
7148 ;;;###autoload
7149 (defun org-global-cycle (&optional arg)
7150 "Cycle the global visibility. For details see `org-cycle'.
7151 With \\[universal-argument] prefix arg, switch to startup visibility.
7152 With a numeric prefix, show all headlines up to that level."
7153 (interactive "P")
7154 (let ((org-cycle-include-plain-lists
7155 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7156 (cond
7157 ((integerp arg)
7158 (outline-show-all)
7159 (outline-hide-sublevels arg)
7160 (setq org-cycle-global-status 'contents))
7161 ((equal arg '(4))
7162 (org-set-startup-visibility)
7163 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7165 (org-cycle '(4))))))
7167 (defun org-set-startup-visibility ()
7168 "Set the visibility required by startup options and properties."
7169 (cond
7170 ((eq org-startup-folded t)
7171 (org-overview))
7172 ((eq org-startup-folded 'content)
7173 (org-content))
7174 ((or (eq org-startup-folded 'showeverything)
7175 (eq org-startup-folded nil))
7176 (outline-show-all)))
7177 (unless (eq org-startup-folded 'showeverything)
7178 (when org-hide-block-startup (org-hide-block-all))
7179 (org-set-visibility-according-to-property 'no-cleanup)
7180 (org-cycle-hide-archived-subtrees 'all)
7181 (org-cycle-hide-drawers 'all)
7182 (org-cycle-show-empty-lines t)))
7184 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7185 "Switch subtree visibilities according to :VISIBILITY: property."
7186 (interactive)
7187 (org-with-wide-buffer
7188 (goto-char (point-min))
7189 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7190 (if (not (org-at-property-p)) (outline-next-heading)
7191 (let ((state (match-string 3)))
7192 (save-excursion
7193 (org-back-to-heading t)
7194 (outline-hide-subtree)
7195 (org-reveal)
7196 (cond
7197 ((equal state "folded")
7198 (outline-hide-subtree))
7199 ((equal state "children")
7200 (org-show-hidden-entry)
7201 (org-show-children))
7202 ((equal state "content")
7203 (save-excursion
7204 (save-restriction
7205 (org-narrow-to-subtree)
7206 (org-content))))
7207 ((member state '("all" "showall"))
7208 (outline-show-subtree)))))))
7209 (unless no-cleanup
7210 (org-cycle-hide-archived-subtrees 'all)
7211 (org-cycle-hide-drawers 'all)
7212 (org-cycle-show-empty-lines 'all))))
7214 ;; This function uses outline-regexp instead of the more fundamental
7215 ;; org-outline-regexp so that org-cycle-global works outside of Org
7216 ;; buffers, where outline-regexp is needed.
7217 (defun org-overview ()
7218 "Switch to overview mode, showing only top-level headlines.
7219 This shows all headlines with a level equal or greater than the level
7220 of the first headline in the buffer. This is important, because if the
7221 first headline is not level one, then (hide-sublevels 1) gives confusing
7222 results."
7223 (interactive)
7224 (save-excursion
7225 (let ((level
7226 (save-excursion
7227 (goto-char (point-min))
7228 (when (re-search-forward (concat "^" outline-regexp) nil t)
7229 (goto-char (match-beginning 0))
7230 (funcall outline-level)))))
7231 (and level (outline-hide-sublevels level)))))
7233 (defun org-content (&optional arg)
7234 "Show all headlines in the buffer, like a table of contents.
7235 With numerical argument N, show content up to level N."
7236 (interactive "P")
7237 (org-overview)
7238 (save-excursion
7239 ;; Visit all headings and show their offspring
7240 (and (integerp arg) (org-overview))
7241 (goto-char (point-max))
7242 (catch 'exit
7243 (while (and (progn (condition-case nil
7244 (outline-previous-visible-heading 1)
7245 (error (goto-char (point-min))))
7247 (looking-at org-outline-regexp))
7248 (if (integerp arg)
7249 (org-show-children (1- arg))
7250 (outline-show-branches))
7251 (when (bobp) (throw 'exit nil))))))
7253 (defun org-optimize-window-after-visibility-change (state)
7254 "Adjust the window after a change in outline visibility.
7255 This function is the default value of the hook `org-cycle-hook'."
7256 (when (get-buffer-window (current-buffer))
7257 (cond
7258 ((eq state 'content) nil)
7259 ((eq state 'all) nil)
7260 ((eq state 'folded) nil)
7261 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7262 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7264 (defun org-remove-empty-overlays-at (pos)
7265 "Remove outline overlays that do not contain non-white stuff."
7266 (dolist (o (overlays-at pos))
7267 (and (eq 'outline (overlay-get o 'invisible))
7268 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7269 (overlay-end o))))
7270 (delete-overlay o))))
7272 (defun org-clean-visibility-after-subtree-move ()
7273 "Fix visibility issues after moving a subtree."
7274 ;; First, find a reasonable region to look at:
7275 ;; Start two siblings above, end three below
7276 (let* ((beg (save-excursion
7277 (and (org-get-last-sibling)
7278 (org-get-last-sibling))
7279 (point)))
7280 (end (save-excursion
7281 (and (org-get-next-sibling)
7282 (org-get-next-sibling)
7283 (org-get-next-sibling))
7284 (if (org-at-heading-p)
7285 (point-at-eol)
7286 (point))))
7287 (level (looking-at "\\*+"))
7288 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7289 (save-excursion
7290 (save-restriction
7291 (narrow-to-region beg end)
7292 (when re
7293 ;; Properly fold already folded siblings
7294 (goto-char (point-min))
7295 (while (re-search-forward re nil t)
7296 (when (and (not (outline-invisible-p))
7297 (save-excursion
7298 (goto-char (point-at-eol)) (outline-invisible-p)))
7299 (outline-hide-entry))))
7300 (org-cycle-show-empty-lines 'overview)
7301 (org-cycle-hide-drawers 'overview)))))
7303 (defun org-cycle-show-empty-lines (state)
7304 "Show empty lines above all visible headlines.
7305 The region to be covered depends on STATE when called through
7306 `org-cycle-hook'. Lisp program can use t for STATE to get the
7307 entire buffer covered. Note that an empty line is only shown if there
7308 are at least `org-cycle-separator-lines' empty lines before the headline."
7309 (when (/= org-cycle-separator-lines 0)
7310 (save-excursion
7311 (let* ((n (abs org-cycle-separator-lines))
7312 (re (cond
7313 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7314 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7315 (t (let ((ns (number-to-string (- n 2))))
7316 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7317 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7318 beg end)
7319 (cond
7320 ((memq state '(overview contents t))
7321 (setq beg (point-min) end (point-max)))
7322 ((memq state '(children folded))
7323 (setq beg (point)
7324 end (progn (org-end-of-subtree t t)
7325 (line-beginning-position 2)))))
7326 (when beg
7327 (goto-char beg)
7328 (while (re-search-forward re end t)
7329 (unless (get-char-property (match-end 1) 'invisible)
7330 (let ((e (match-end 1))
7331 (b (if (>= org-cycle-separator-lines 0)
7332 (match-beginning 1)
7333 (save-excursion
7334 (goto-char (match-beginning 0))
7335 (skip-chars-backward " \t\n")
7336 (line-end-position)))))
7337 (outline-flag-region b e nil))))))))
7338 ;; Never hide empty lines at the end of the file.
7339 (save-excursion
7340 (goto-char (point-max))
7341 (outline-previous-heading)
7342 (outline-end-of-heading)
7343 (when (and (looking-at "[ \t\n]+")
7344 (= (match-end 0) (point-max)))
7345 (outline-flag-region (point) (match-end 0) nil))))
7347 (defun org-show-empty-lines-in-parent ()
7348 "Move to the parent and re-show empty lines before visible headlines."
7349 (save-excursion
7350 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7351 (org-cycle-show-empty-lines context))))
7353 (defun org-files-list ()
7354 "Return `org-agenda-files' list, plus all open org-mode files.
7355 This is useful for operations that need to scan all of a user's
7356 open and agenda-wise Org files."
7357 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7358 (dolist (buf (buffer-list))
7359 (with-current-buffer buf
7360 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7361 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7362 files))
7364 (defsubst org-entry-beginning-position ()
7365 "Return the beginning position of the current entry."
7366 (save-excursion (org-back-to-heading t) (point)))
7368 (defsubst org-entry-end-position ()
7369 "Return the end position of the current entry."
7370 (save-excursion (outline-next-heading) (point)))
7372 (defun org-cycle-hide-drawers (state &optional exceptions)
7373 "Re-hide all drawers after a visibility state change.
7374 When non-nil, optional argument EXCEPTIONS is a list of strings
7375 specifying which drawers should not be hidden."
7376 (when (and (derived-mode-p 'org-mode)
7377 (not (memq state '(overview folded contents))))
7378 (save-excursion
7379 (let* ((globalp (memq state '(contents all)))
7380 (beg (if globalp (point-min) (point)))
7381 (end (if globalp (point-max)
7382 (if (eq state 'children)
7383 (save-excursion (outline-next-heading) (point))
7384 (org-end-of-subtree t)))))
7385 (goto-char beg)
7386 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7387 (unless (member-ignore-case (match-string 1) exceptions)
7388 (let ((drawer (org-element-at-point)))
7389 (when (memq (org-element-type drawer) '(drawer property-drawer))
7390 (org-flag-drawer t drawer)
7391 ;; Make sure to skip drawer entirely or we might flag
7392 ;; it another time when matching its ending line with
7393 ;; `org-drawer-regexp'.
7394 (goto-char (org-element-property :end drawer))))))))))
7396 (defun org-flag-drawer (flag &optional element)
7397 "When FLAG is non-nil, hide the drawer we are at.
7398 Otherwise make it visible. When optional argument ELEMENT is
7399 a parsed drawer, as returned by `org-element-at-point', hide or
7400 show that drawer instead."
7401 (let ((drawer (or element
7402 (and (save-excursion
7403 (beginning-of-line)
7404 (looking-at-p org-drawer-regexp))
7405 (org-element-at-point)))))
7406 (when (memq (org-element-type drawer) '(drawer property-drawer))
7407 (let ((post (org-element-property :post-affiliated drawer)))
7408 (save-excursion
7409 (outline-flag-region
7410 (progn (goto-char post) (line-end-position))
7411 (progn (goto-char (org-element-property :end drawer))
7412 (skip-chars-backward " \r\t\n")
7413 (line-end-position))
7414 flag))
7415 ;; When the drawer is hidden away, make sure point lies in
7416 ;; a visible part of the buffer.
7417 (when (and flag (> (line-beginning-position) post))
7418 (goto-char post))))))
7420 (defun org-subtree-end-visible-p ()
7421 "Is the end of the current subtree visible?"
7422 (pos-visible-in-window-p
7423 (save-excursion (org-end-of-subtree t) (point))))
7425 (defun org-first-headline-recenter ()
7426 "Move cursor to the first headline and recenter the headline."
7427 (let ((window (get-buffer-window)))
7428 (when window
7429 (goto-char (point-min))
7430 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7431 (set-window-start window (line-beginning-position))))))
7433 ;;; Saving and restoring visibility
7435 (defun org-outline-overlay-data (&optional use-markers)
7436 "Return a list of the locations of all outline overlays.
7437 These are overlays with the `invisible' property value `outline'.
7438 The return value is a list of cons cells, with start and stop
7439 positions for each overlay.
7440 If USE-MARKERS is set, return the positions as markers."
7441 (let (beg end)
7442 (save-excursion
7443 (save-restriction
7444 (widen)
7445 (delq nil
7446 (mapcar (lambda (o)
7447 (when (eq (overlay-get o 'invisible) 'outline)
7448 (setq beg (overlay-start o)
7449 end (overlay-end o))
7450 (and beg end (> end beg)
7451 (if use-markers
7452 (cons (copy-marker beg)
7453 (copy-marker end t))
7454 (cons beg end)))))
7455 (overlays-in (point-min) (point-max))))))))
7457 (defun org-set-outline-overlay-data (data)
7458 "Create visibility overlays for all positions in DATA.
7459 DATA should have been made by `org-outline-overlay-data'."
7460 (org-with-wide-buffer
7461 (outline-show-all)
7462 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7464 ;;; Folding of blocks
7466 (defvar-local org-hide-block-overlays nil
7467 "Overlays hiding blocks.")
7469 (defun org-block-map (function &optional start end)
7470 "Call FUNCTION at the head of all source blocks in the current buffer.
7471 Optional arguments START and END can be used to limit the range."
7472 (let ((start (or start (point-min)))
7473 (end (or end (point-max))))
7474 (save-excursion
7475 (goto-char start)
7476 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7477 (save-excursion
7478 (save-match-data
7479 (goto-char (match-beginning 0))
7480 (funcall function)))))))
7482 (defun org-hide-block-toggle-all ()
7483 "Toggle the visibility of all blocks in the current buffer."
7484 (org-block-map 'org-hide-block-toggle))
7486 (defun org-hide-block-all ()
7487 "Fold all blocks in the current buffer."
7488 (interactive)
7489 (org-show-block-all)
7490 (org-block-map 'org-hide-block-toggle-maybe))
7492 (defun org-show-block-all ()
7493 "Unfold all blocks in the current buffer."
7494 (interactive)
7495 (mapc #'delete-overlay org-hide-block-overlays)
7496 (setq org-hide-block-overlays nil))
7498 (defun org-hide-block-toggle-maybe ()
7499 "Toggle visibility of block at point.
7500 Unlike to `org-hide-block-toggle', this function does not throw
7501 an error. Return a non-nil value when toggling is successful."
7502 (interactive)
7503 (ignore-errors (org-hide-block-toggle)))
7505 (defun org-hide-block-toggle (&optional force)
7506 "Toggle the visibility of the current block.
7507 When optional argument FORCE is `off', make block visible. If it
7508 is non-nil, hide it unconditionally. Throw an error when not at
7509 a block. Return a non-nil value when toggling is successful."
7510 (interactive)
7511 (let ((element (org-element-at-point)))
7512 (unless (memq (org-element-type element)
7513 '(center-block comment-block dynamic-block example-block
7514 export-block quote-block special-block
7515 src-block verse-block))
7516 (user-error "Not at a block"))
7517 (let* ((start (save-excursion
7518 (goto-char (org-element-property :post-affiliated element))
7519 (line-end-position)))
7520 (end (save-excursion
7521 (goto-char (org-element-property :end element))
7522 (skip-chars-backward " \r\t\n")
7523 (line-end-position)))
7524 (overlays (overlays-at start)))
7525 (cond
7526 ;; Do nothing when not before or at the block opening line or
7527 ;; at the block closing line.
7528 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7529 ((and (not (eq force 'off))
7530 (not (memq t (mapcar
7531 (lambda (o)
7532 (eq (overlay-get o 'invisible) 'org-hide-block))
7533 overlays))))
7534 (let ((ov (make-overlay start end)))
7535 (overlay-put ov 'invisible 'org-hide-block)
7536 ;; Make the block accessible to `isearch'.
7537 (overlay-put
7538 ov 'isearch-open-invisible
7539 (lambda (ov)
7540 (when (memq ov org-hide-block-overlays)
7541 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7542 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7543 (delete-overlay ov))))
7544 (push ov org-hide-block-overlays)
7545 ;; When the block is hidden away, make sure point is left in
7546 ;; a visible part of the buffer.
7547 (when (> (line-beginning-position) start)
7548 (goto-char start)
7549 (beginning-of-line))
7550 ;; Signal successful toggling.
7552 ((or (not force) (eq force 'off))
7553 (dolist (ov overlays t)
7554 (when (memq ov org-hide-block-overlays)
7555 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7556 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7557 (delete-overlay ov))))))))
7559 ;; org-tab-after-check-for-cycling-hook
7560 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7561 ;; Remove overlays when changing major mode
7562 (add-hook 'org-mode-hook
7563 (lambda () (add-hook 'change-major-mode-hook
7564 'org-show-block-all 'append 'local)))
7566 ;;; Org-goto
7568 (defvar org-goto-window-configuration nil)
7569 (defvar org-goto-marker nil)
7570 (defvar org-goto-map)
7571 (defun org-goto-map ()
7572 "Set the keymap `org-goto'."
7573 (setq org-goto-map
7574 (let ((map (make-sparse-keymap)))
7575 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7576 mouse-drag-region universal-argument org-occur)))
7577 (dolist (cmd cmds)
7578 (substitute-key-definition cmd cmd map global-map)))
7579 (suppress-keymap map)
7580 (org-defkey map "\C-m" 'org-goto-ret)
7581 (org-defkey map [(return)] 'org-goto-ret)
7582 (org-defkey map [(left)] 'org-goto-left)
7583 (org-defkey map [(right)] 'org-goto-right)
7584 (org-defkey map [(control ?g)] 'org-goto-quit)
7585 (org-defkey map "\C-i" 'org-cycle)
7586 (org-defkey map [(tab)] 'org-cycle)
7587 (org-defkey map [(down)] 'outline-next-visible-heading)
7588 (org-defkey map [(up)] 'outline-previous-visible-heading)
7589 (if org-goto-auto-isearch
7590 (if (fboundp 'define-key-after)
7591 (define-key-after map [t] 'org-goto-local-auto-isearch)
7592 nil)
7593 (org-defkey map "q" 'org-goto-quit)
7594 (org-defkey map "n" 'outline-next-visible-heading)
7595 (org-defkey map "p" 'outline-previous-visible-heading)
7596 (org-defkey map "f" 'outline-forward-same-level)
7597 (org-defkey map "b" 'outline-backward-same-level)
7598 (org-defkey map "u" 'outline-up-heading))
7599 (org-defkey map "/" 'org-occur)
7600 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7601 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7602 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7603 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7604 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7605 map)))
7607 (defconst org-goto-help
7608 "Browse buffer copy, to find location or copy text.%s
7609 RET=jump to location C-g=quit and return to previous location
7610 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7612 (defvar org-goto-start-pos) ; dynamically scoped parameter
7614 (defun org-goto (&optional alternative-interface)
7615 "Look up a different location in the current file, keeping current visibility.
7617 When you want look-up or go to a different location in a
7618 document, the fastest way is often to fold the entire buffer and
7619 then dive into the tree. This method has the disadvantage, that
7620 the previous location will be folded, which may not be what you
7621 want.
7623 This command works around this by showing a copy of the current
7624 buffer in an indirect buffer, in overview mode. You can dive
7625 into the tree in that copy, use org-occur and incremental search
7626 to find a location. When pressing RET or `Q', the command
7627 returns to the original buffer in which the visibility is still
7628 unchanged. After RET it will also jump to the location selected
7629 in the indirect buffer and expose the headline hierarchy above.
7631 With a prefix argument, use the alternative interface: e.g., if
7632 `org-goto-interface' is `outline' use `outline-path-completion'."
7633 (interactive "P")
7634 (org-goto-map)
7635 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7636 (org-refile-use-outline-path t)
7637 (org-refile-target-verify-function nil)
7638 (interface
7639 (if (not alternative-interface)
7640 org-goto-interface
7641 (if (eq org-goto-interface 'outline)
7642 'outline-path-completion
7643 'outline)))
7644 (org-goto-start-pos (point))
7645 (selected-point
7646 (if (eq interface 'outline)
7647 (car (org-get-location (current-buffer) org-goto-help))
7648 (let ((pa (org-refile-get-location "Goto")))
7649 (org-refile-check-position pa)
7650 (nth 3 pa)))))
7651 (if selected-point
7652 (progn
7653 (org-mark-ring-push org-goto-start-pos)
7654 (goto-char selected-point)
7655 (when (or (outline-invisible-p) (org-invisible-p2))
7656 (org-show-context 'org-goto)))
7657 (message "Quit"))))
7659 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7660 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7661 (defvar org-goto-local-auto-isearch-map) ; defined below
7663 (defun org-get-location (_buf help)
7664 "Let the user select a location in current buffer.
7665 This function uses a recursive edit. It returns the selected position
7666 or nil."
7667 (org-no-popups
7668 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7669 (isearch-hide-immediately nil)
7670 (isearch-search-fun-function
7671 (lambda () 'org-goto-local-search-headings))
7672 (org-goto-selected-point org-goto-exit-command))
7673 (save-excursion
7674 (save-window-excursion
7675 (delete-other-windows)
7676 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7677 (pop-to-buffer-same-window
7678 (condition-case nil
7679 (make-indirect-buffer (current-buffer) "*org-goto*")
7680 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7681 (with-output-to-temp-buffer "*Org Help*"
7682 (princ (format help (if org-goto-auto-isearch
7683 " Just type for auto-isearch."
7684 " n/p/f/b/u to navigate, q to quit."))))
7685 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7686 (setq buffer-read-only nil)
7687 (let ((org-startup-truncated t)
7688 (org-startup-folded nil)
7689 (org-startup-align-all-tables nil))
7690 (org-mode)
7691 (org-overview))
7692 (setq buffer-read-only t)
7693 (if (and (boundp 'org-goto-start-pos)
7694 (integer-or-marker-p org-goto-start-pos))
7695 (progn (goto-char org-goto-start-pos)
7696 (when (outline-invisible-p)
7697 (org-show-set-visibility 'lineage)))
7698 (goto-char (point-min)))
7699 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7700 (message "Select location and press RET")
7701 (use-local-map org-goto-map)
7702 (recursive-edit)))
7703 (kill-buffer "*org-goto*")
7704 (cons org-goto-selected-point org-goto-exit-command))))
7706 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7707 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7708 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7709 (if (fboundp 'isearch-other-control-char)
7710 (progn
7711 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7712 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7713 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7714 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7715 (define-key org-goto-local-auto-isearch-map [return] nil))
7717 (defun org-goto-local-search-headings (string bound noerror)
7718 "Search and make sure that any matches are in headlines."
7719 (catch 'return
7720 (while (if isearch-forward
7721 (search-forward string bound noerror)
7722 (search-backward string bound noerror))
7723 (when (save-match-data
7724 (and (save-excursion
7725 (beginning-of-line)
7726 (looking-at org-complex-heading-regexp))
7727 (or (not (match-beginning 5))
7728 (< (point) (match-beginning 5)))))
7729 (throw 'return (point))))))
7731 (defun org-goto-local-auto-isearch ()
7732 "Start isearch."
7733 (interactive)
7734 (goto-char (point-min))
7735 (let ((keys (this-command-keys)))
7736 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7737 (isearch-mode t)
7738 (isearch-process-search-char (string-to-char keys)))))
7740 (defun org-goto-ret (&optional _arg)
7741 "Finish `org-goto' by going to the new location."
7742 (interactive "P")
7743 (setq org-goto-selected-point (point))
7744 (setq org-goto-exit-command 'return)
7745 (throw 'exit nil))
7747 (defun org-goto-left ()
7748 "Finish `org-goto' by going to the new location."
7749 (interactive)
7750 (if (org-at-heading-p)
7751 (progn
7752 (beginning-of-line 1)
7753 (setq org-goto-selected-point (point)
7754 org-goto-exit-command 'left)
7755 (throw 'exit nil))
7756 (user-error "Not on a heading")))
7758 (defun org-goto-right ()
7759 "Finish `org-goto' by going to the new location."
7760 (interactive)
7761 (if (org-at-heading-p)
7762 (progn
7763 (setq org-goto-selected-point (point)
7764 org-goto-exit-command 'right)
7765 (throw 'exit nil))
7766 (user-error "Not on a heading")))
7768 (defun org-goto-quit ()
7769 "Finish `org-goto' without cursor motion."
7770 (interactive)
7771 (setq org-goto-selected-point nil)
7772 (setq org-goto-exit-command 'quit)
7773 (throw 'exit nil))
7775 ;;; Indirect buffer display of subtrees
7777 (defvar org-indirect-dedicated-frame nil
7778 "This is the frame being used for indirect tree display.")
7779 (defvar org-last-indirect-buffer nil)
7781 (defun org-tree-to-indirect-buffer (&optional arg)
7782 "Create indirect buffer and narrow it to current subtree.
7783 With a numerical prefix ARG, go up to this level and then take that tree.
7784 If ARG is negative, go up that many levels.
7786 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7787 indirect buffer previously made with this command, to avoid proliferation of
7788 indirect buffers. However, when you call the command with a \
7789 \\[universal-argument] prefix, or
7790 when `org-indirect-buffer-display' is `new-frame', the last buffer
7791 is kept so that you can work with several indirect buffers at the same time.
7792 If `org-indirect-buffer-display' is `dedicated-frame', the \
7793 \\[universal-argument] prefix also
7794 requests that a new frame be made for the new buffer, so that the dedicated
7795 frame is not changed."
7796 (interactive "P")
7797 (let ((cbuf (current-buffer))
7798 (cwin (selected-window))
7799 (pos (point))
7800 beg end level heading ibuf)
7801 (save-excursion
7802 (org-back-to-heading t)
7803 (when (numberp arg)
7804 (setq level (org-outline-level))
7805 (when (< arg 0) (setq arg (+ level arg)))
7806 (while (> (setq level (org-outline-level)) arg)
7807 (org-up-heading-safe)))
7808 (setq beg (point)
7809 heading (org-get-heading 'no-tags))
7810 (org-end-of-subtree t t)
7811 (when (org-at-heading-p) (backward-char 1))
7812 (setq end (point)))
7813 (when (and (buffer-live-p org-last-indirect-buffer)
7814 (not (eq org-indirect-buffer-display 'new-frame))
7815 (not arg))
7816 (kill-buffer org-last-indirect-buffer))
7817 (setq ibuf (org-get-indirect-buffer cbuf heading)
7818 org-last-indirect-buffer ibuf)
7819 (cond
7820 ((or (eq org-indirect-buffer-display 'new-frame)
7821 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7822 (select-frame (make-frame))
7823 (delete-other-windows)
7824 (pop-to-buffer-same-window ibuf)
7825 (org-set-frame-title heading))
7826 ((eq org-indirect-buffer-display 'dedicated-frame)
7827 (raise-frame
7828 (select-frame (or (and org-indirect-dedicated-frame
7829 (frame-live-p org-indirect-dedicated-frame)
7830 org-indirect-dedicated-frame)
7831 (setq org-indirect-dedicated-frame (make-frame)))))
7832 (delete-other-windows)
7833 (pop-to-buffer-same-window ibuf)
7834 (org-set-frame-title (concat "Indirect: " heading)))
7835 ((eq org-indirect-buffer-display 'current-window)
7836 (pop-to-buffer-same-window ibuf))
7837 ((eq org-indirect-buffer-display 'other-window)
7838 (pop-to-buffer ibuf))
7839 (t (error "Invalid value")))
7840 (narrow-to-region beg end)
7841 (outline-show-all)
7842 (goto-char pos)
7843 (run-hook-with-args 'org-cycle-hook 'all)
7844 (and (window-live-p cwin) (select-window cwin))))
7846 (defun org-get-indirect-buffer (&optional buffer heading)
7847 (setq buffer (or buffer (current-buffer)))
7848 (let ((n 1) (base (buffer-name buffer)) bname)
7849 (while (buffer-live-p
7850 (get-buffer
7851 (setq bname
7852 (concat base "-"
7853 (if heading (concat heading "-" (number-to-string n))
7854 (number-to-string n))))))
7855 (setq n (1+ n)))
7856 (condition-case nil
7857 (make-indirect-buffer buffer bname 'clone)
7858 (error (make-indirect-buffer buffer bname)))))
7860 (defun org-set-frame-title (title)
7861 "Set the title of the current frame to the string TITLE."
7862 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7864 ;;;; Structure editing
7866 ;;; Inserting headlines
7868 (defun org--line-empty-p (n)
7869 "Is the Nth next line empty?
7871 Counts the current line as N = 1 and the previous line as N = 0;
7872 see `beginning-of-line'."
7873 (save-excursion
7874 (and (not (bobp))
7875 (or (beginning-of-line n) t)
7876 (save-match-data
7877 (looking-at "[ \t]*$")))))
7879 (defun org-previous-line-empty-p ()
7880 "Is the previous line a blank line?
7881 When NEXT is non-nil, check the next line instead."
7882 (org--line-empty-p 0))
7884 (defun org-next-line-empty-p ()
7885 "Is the previous line a blank line?
7886 When NEXT is non-nil, check the next line instead."
7887 (org--line-empty-p 2))
7889 (defun org-insert-heading (&optional arg invisible-ok top)
7890 "Insert a new heading or an item with the same depth at point.
7892 If point is at the beginning of a heading or a list item, insert
7893 a new heading or a new item above the current one. If point is
7894 at the beginning of a normal line, turn the line into a heading.
7896 If point is in the middle of a headline or a list item, split the
7897 headline or the item and create a new headline/item with the text
7898 in the current line after point \(see `org-M-RET-may-split-line'
7899 on how to modify this behavior).
7901 With one universal prefix argument, set the user option
7902 `org-insert-heading-respect-content' to t for the duration of
7903 the command. This modifies the behavior described above in this
7904 ways: on list items and at the beginning of normal lines, force
7905 the insertion of a heading after the current subtree.
7907 With two universal prefix arguments, insert the heading at the
7908 end of the grandparent subtree. For example, if point is within
7909 a 2nd-level heading, then it will insert a 2nd-level heading at
7910 the end of the 1st-level parent heading.
7912 If point is at the beginning of a headline, insert a sibling
7913 before the current headline. If point is not at the beginning,
7914 split the line and create a new headline with the text in the
7915 current line after point \(see `org-M-RET-may-split-line' on how
7916 to modify this behavior).
7918 If point is at the beginning of a normal line, turn this line
7919 into a heading.
7921 When INVISIBLE-OK is set, stop at invisible headlines when going
7922 back. This is important for non-interactive uses of the
7923 command.
7925 When optional argument TOP is non-nil, insert a level 1 heading,
7926 unconditionally."
7927 (interactive "P")
7928 (let ((itemp (and (not top) (org-in-item-p)))
7929 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7930 (respect-content (or org-insert-heading-respect-content
7931 (equal arg '(4))))
7932 (initial-content ""))
7934 (cond
7936 ((or (= (buffer-size) 0)
7937 (and (not (save-excursion
7938 (and (ignore-errors (org-back-to-heading invisible-ok))
7939 (org-at-heading-p))))
7940 (or arg (not itemp))))
7941 ;; At beginning of buffer or so high up that only a heading
7942 ;; makes sense.
7943 (cond ((and (bolp) (not respect-content)) (insert "* "))
7944 ((not respect-content)
7945 (unless may-split (end-of-line))
7946 (insert "\n* "))
7947 ((re-search-forward org-outline-regexp-bol nil t)
7948 (beginning-of-line)
7949 (insert "* \n")
7950 (backward-char))
7951 (t (goto-char (point-max))
7952 (insert "\n* ")))
7953 (run-hooks 'org-insert-heading-hook))
7955 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7958 ;; Maybe move at the end of the subtree
7959 (when (equal arg '(16))
7960 (org-up-heading-safe)
7961 (org-end-of-subtree t))
7962 ;; Insert a heading
7963 (save-restriction
7964 (widen)
7965 (let* ((level nil)
7966 (on-heading (org-at-heading-p))
7967 (empty-line-p (if on-heading
7968 (org-previous-line-empty-p)
7969 ;; We will decide later
7970 nil))
7971 ;; Get a level string to fall back on.
7972 (fix-level
7973 (if (org-before-first-heading-p) "*"
7974 (save-excursion
7975 (org-back-to-heading t)
7976 (when (org-previous-line-empty-p) (setq empty-line-p t))
7977 (looking-at org-outline-regexp)
7978 (make-string (1- (length (match-string 0))) ?*))))
7979 (stars
7980 (save-excursion
7981 (condition-case nil
7982 (if top "* "
7983 (org-back-to-heading invisible-ok)
7984 (when (and (not on-heading)
7985 (featurep 'org-inlinetask)
7986 (integerp org-inlinetask-min-level)
7987 (>= (length (match-string 0))
7988 org-inlinetask-min-level))
7989 ;; Find a heading level before the inline
7990 ;; task.
7991 (while (and (setq level (org-up-heading-safe))
7992 (>= level org-inlinetask-min-level)))
7993 (if (org-at-heading-p)
7994 (org-back-to-heading invisible-ok)
7995 (error "This should not happen")))
7996 (unless (and (save-excursion
7997 (save-match-data
7998 (org-backward-heading-same-level
7999 1 invisible-ok))
8000 (= (point) (match-beginning 0)))
8001 (not (org-next-line-empty-p)))
8002 (setq empty-line-p (or empty-line-p
8003 (org-previous-line-empty-p))))
8004 (match-string 0))
8005 (error (or fix-level "* ")))))
8006 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8007 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8009 ;; If we insert after content, move there and clean up
8010 ;; whitespace.
8011 (when (and respect-content
8012 (not (looking-at-p org-outline-regexp-bol)))
8013 (if (not (org-before-first-heading-p))
8014 (org-end-of-subtree nil t)
8015 (re-search-forward org-outline-regexp-bol)
8016 (beginning-of-line 0))
8017 (skip-chars-backward " \r\t\n")
8018 (and (not (looking-back "^\\*+" (line-beginning-position)))
8019 (looking-at "[ \t]+") (replace-match ""))
8020 (unless (eobp) (forward-char 1))
8021 (when (looking-at "^\\*")
8022 (unless (bobp) (backward-char 1))
8023 (insert "\n")))
8025 ;; If we are splitting, grab the text that should be moved
8026 ;; to the new headline.
8027 (when may-split
8028 (if (org-at-heading-p)
8029 ;; This is a heading: split intelligently (keeping
8030 ;; tags).
8031 (let ((pos (point)))
8032 (beginning-of-line)
8033 (unless (looking-at org-complex-heading-regexp)
8034 (error "This should not happen"))
8035 (when (and (match-beginning 4)
8036 (> pos (match-beginning 4))
8037 (< pos (match-end 4)))
8038 (setq initial-content (buffer-substring pos (match-end 4)))
8039 (goto-char pos)
8040 (delete-region (point) (match-end 4))
8041 (if (looking-at "[ \t]*$")
8042 (replace-match "")
8043 (insert (make-string (length initial-content) ?\s)))
8044 (setq initial-content (org-trim initial-content)))
8045 (goto-char pos))
8046 ;; A normal line.
8047 (setq initial-content
8048 (org-trim
8049 (delete-and-extract-region (point) (line-end-position))))))
8051 ;; If we are at the beginning of the line, insert before it.
8052 ;; Otherwise, after it.
8053 (cond
8054 ((and (bolp) (looking-at "[ \t]*$")))
8055 ((bolp) (save-excursion (insert "\n")))
8056 (t (end-of-line)
8057 (insert "\n")))
8059 ;; Insert the new heading
8060 (insert stars)
8061 (just-one-space)
8062 (insert initial-content)
8063 (unless (and blank (org-previous-line-empty-p))
8064 (org-N-empty-lines-before-current (if blank 1 0)))
8065 ;; Adjust visibility, which may be messed up if we removed
8066 ;; blank lines while previous entry was hidden.
8067 (let ((bol (line-beginning-position)))
8068 (dolist (o (overlays-at (1- bol)))
8069 (when (and (eq (overlay-get o 'invisible) 'outline)
8070 (eq (overlay-end o) bol))
8071 (move-overlay o (overlay-start o) (1- bol)))))
8072 (run-hooks 'org-insert-heading-hook)))))))
8074 (defun org-N-empty-lines-before-current (N)
8075 "Make the number of empty lines before current exactly N.
8076 So this will delete or add empty lines."
8077 (save-excursion
8078 (beginning-of-line)
8079 (let ((p (point)))
8080 (skip-chars-backward " \r\t\n")
8081 (unless (bolp) (forward-line))
8082 (delete-region (point) p))
8083 (when (> N 0) (insert (make-string N ?\n)))))
8085 (defun org-get-heading (&optional no-tags no-todo)
8086 "Return the heading of the current entry, without the stars.
8087 When NO-TAGS is non-nil, don't include tags.
8088 When NO-TODO is non-nil, don't include TODO keywords."
8089 (save-excursion
8090 (org-back-to-heading t)
8091 (let ((case-fold-search nil))
8092 (cond
8093 ((and no-tags no-todo)
8094 (looking-at org-complex-heading-regexp)
8095 (match-string 4))
8096 (no-tags
8097 (looking-at (concat org-outline-regexp
8098 "\\(.*?\\)"
8099 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8100 (match-string 1))
8101 (no-todo
8102 (looking-at org-todo-line-regexp)
8103 (match-string 3))
8104 (t (looking-at org-heading-regexp)
8105 (match-string 2))))))
8107 (defvar orgstruct-mode) ; defined below
8109 (defun org-heading-components ()
8110 "Return the components of the current heading.
8111 This is a list with the following elements:
8112 - the level as an integer
8113 - the reduced level, different if `org-odd-levels-only' is set.
8114 - the TODO keyword, or nil
8115 - the priority character, like ?A, or nil if no priority is given
8116 - the headline text itself, or the tags string if no headline text
8117 - the tags string, or nil."
8118 (save-excursion
8119 (org-back-to-heading t)
8120 (when (let (case-fold-search)
8121 (looking-at
8122 (if orgstruct-mode
8123 org-heading-regexp
8124 org-complex-heading-regexp)))
8125 (if orgstruct-mode
8126 (list (length (match-string 1))
8127 (org-reduced-level (length (match-string 1)))
8130 (match-string 2)
8131 nil)
8132 (list (length (match-string 1))
8133 (org-reduced-level (length (match-string 1)))
8134 (match-string-no-properties 2)
8135 (and (match-end 3) (aref (match-string 3) 2))
8136 (match-string-no-properties 4)
8137 (match-string-no-properties 5))))))
8139 (defun org-get-entry ()
8140 "Get the entry text, after heading, entire subtree."
8141 (save-excursion
8142 (org-back-to-heading t)
8143 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8145 (defun org-edit-headline (&optional heading)
8146 "Edit the current headline.
8147 Set it to HEADING when provided."
8148 (interactive)
8149 (org-with-wide-buffer
8150 (org-back-to-heading t)
8151 (when (looking-at org-complex-heading-regexp)
8152 (let* ((old (match-string-no-properties 4))
8153 (new (save-match-data
8154 (org-trim (or heading (read-string "Edit: " old))))))
8155 (unless (equal old new)
8156 (if old (replace-match new t t nil 4)
8157 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8158 (insert " " new))
8159 (org-set-tags nil t)
8160 (when (looking-at "[ \t]*$") (replace-match "")))))))
8162 (defun org-insert-heading-after-current ()
8163 "Insert a new heading with same level as current, after current subtree."
8164 (interactive)
8165 (org-back-to-heading)
8166 (org-insert-heading)
8167 (org-move-subtree-down)
8168 (end-of-line 1))
8170 (defun org-insert-heading-respect-content (&optional invisible-ok)
8171 "Insert heading with `org-insert-heading-respect-content' set to t."
8172 (interactive)
8173 (org-insert-heading '(4) invisible-ok))
8175 (defun org-insert-todo-heading-respect-content (&optional force-state)
8176 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8177 (interactive)
8178 (org-insert-todo-heading force-state '(4)))
8180 (defun org-insert-todo-heading (arg &optional force-heading)
8181 "Insert a new heading with the same level and TODO state as current heading.
8182 If the heading has no TODO state, or if the state is DONE, use the first
8183 state (TODO by default). Also with one prefix arg, force first state. With
8184 two prefix args, force inserting at the end of the parent subtree."
8185 (interactive "P")
8186 (when (or force-heading (not (org-insert-item 'checkbox)))
8187 (org-insert-heading (or (and (equal arg '(16)) '(16))
8188 force-heading))
8189 (save-excursion
8190 (org-back-to-heading)
8191 (outline-previous-heading)
8192 (looking-at org-todo-line-regexp))
8193 (let*
8194 ((new-mark-x
8195 (if (or (equal arg '(4))
8196 (not (match-beginning 2))
8197 (member (match-string 2) org-done-keywords))
8198 (car org-todo-keywords-1)
8199 (match-string 2)))
8200 (new-mark
8202 (run-hook-with-args-until-success
8203 'org-todo-get-default-hook new-mark-x nil)
8204 new-mark-x)))
8205 (beginning-of-line 1)
8206 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8207 (if org-treat-insert-todo-heading-as-state-change
8208 (org-todo new-mark)
8209 (insert new-mark " "))))
8210 (when org-provide-todo-statistics
8211 (org-update-parent-todo-statistics))))
8213 (defun org-insert-subheading (arg)
8214 "Insert a new subheading and demote it.
8215 Works for outline headings and for plain lists alike."
8216 (interactive "P")
8217 (org-insert-heading arg)
8218 (cond
8219 ((org-at-heading-p) (org-do-demote))
8220 ((org-at-item-p) (org-indent-item))))
8222 (defun org-insert-todo-subheading (arg)
8223 "Insert a new subheading with TODO keyword or checkbox and demote it.
8224 Works for outline headings and for plain lists alike."
8225 (interactive "P")
8226 (org-insert-todo-heading arg)
8227 (cond
8228 ((org-at-heading-p) (org-do-demote))
8229 ((org-at-item-p) (org-indent-item))))
8231 ;;; Promotion and Demotion
8233 (defvar org-after-demote-entry-hook nil
8234 "Hook run after an entry has been demoted.
8235 The cursor will be at the beginning of the entry.
8236 When a subtree is being demoted, the hook will be called for each node.")
8238 (defvar org-after-promote-entry-hook nil
8239 "Hook run after an entry has been promoted.
8240 The cursor will be at the beginning of the entry.
8241 When a subtree is being promoted, the hook will be called for each node.")
8243 (defun org-promote-subtree ()
8244 "Promote the entire subtree.
8245 See also `org-promote'."
8246 (interactive)
8247 (save-excursion
8248 (org-with-limited-levels (org-map-tree 'org-promote)))
8249 (org-fix-position-after-promote))
8251 (defun org-demote-subtree ()
8252 "Demote the entire subtree.
8253 See `org-demote' and `org-promote'."
8254 (interactive)
8255 (save-excursion
8256 (org-with-limited-levels (org-map-tree 'org-demote)))
8257 (org-fix-position-after-promote))
8259 (defun org-do-promote ()
8260 "Promote the current heading higher up the tree.
8261 If the region is active in `transient-mark-mode', promote all
8262 headings in the region."
8263 (interactive)
8264 (save-excursion
8265 (if (org-region-active-p)
8266 (org-map-region 'org-promote (region-beginning) (region-end))
8267 (org-promote)))
8268 (org-fix-position-after-promote))
8270 (defun org-do-demote ()
8271 "Demote the current heading lower down the tree.
8272 If the region is active in `transient-mark-mode', demote all
8273 headings in the region."
8274 (interactive)
8275 (save-excursion
8276 (if (org-region-active-p)
8277 (org-map-region 'org-demote (region-beginning) (region-end))
8278 (org-demote)))
8279 (org-fix-position-after-promote))
8281 (defun org-fix-position-after-promote ()
8282 "Fix cursor position and indentation after demoting/promoting."
8283 (let ((pos (point)))
8284 (when (save-excursion
8285 (beginning-of-line 1)
8286 (looking-at org-todo-line-regexp)
8287 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8288 (cond ((eobp) (insert " "))
8289 ((eolp) (insert " "))
8290 ((equal (char-after) ?\ ) (forward-char 1))))))
8292 (defun org-current-level ()
8293 "Return the level of the current entry, or nil if before the first headline.
8294 The level is the number of stars at the beginning of the
8295 headline. Use `org-reduced-level' to remove the effect of
8296 `org-odd-levels'. Unlike to `org-outline-level', this function
8297 ignores inlinetasks."
8298 (let ((level (org-with-limited-levels (org-outline-level))))
8299 (and (> level 0) level)))
8301 (defun org-get-previous-line-level ()
8302 "Return the outline depth of the last headline before the current line.
8303 Returns 0 for the first headline in the buffer, and nil if before the
8304 first headline."
8305 (and (org-current-level)
8306 (or (and (/= (line-beginning-position) (point-min))
8307 (save-excursion (beginning-of-line 0) (org-current-level)))
8308 0)))
8310 (defun org-reduced-level (l)
8311 "Compute the effective level of a heading.
8312 This takes into account the setting of `org-odd-levels-only'."
8313 (cond
8314 ((zerop l) 0)
8315 (org-odd-levels-only (1+ (floor (/ l 2))))
8316 (t l)))
8318 (defun org-level-increment ()
8319 "Return the number of stars that will be added or removed at a
8320 time to headlines when structure editing, based on the value of
8321 `org-odd-levels-only'."
8322 (if org-odd-levels-only 2 1))
8324 (defun org-get-valid-level (level &optional change)
8325 "Rectify a level change under the influence of `org-odd-levels-only'
8326 LEVEL is a current level, CHANGE is by how much the level should be
8327 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8328 even level numbers will become the next higher odd number."
8329 (if org-odd-levels-only
8330 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8331 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8332 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8333 (max 1 (+ level (or change 0)))))
8335 (defun org-promote ()
8336 "Promote the current heading higher up the tree."
8337 (org-with-wide-buffer
8338 (org-back-to-heading t)
8339 (let* ((after-change-functions (remq 'flyspell-after-change-function
8340 after-change-functions))
8341 (level (save-match-data (funcall outline-level)))
8342 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8343 (diff (abs (- level (length up-head) -1))))
8344 (cond
8345 ((and (= level 1) org-allow-promoting-top-level-subtree)
8346 (replace-match "# " nil t))
8347 ((= level 1)
8348 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8349 (t (replace-match up-head nil t)))
8350 (unless (= level 1)
8351 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8352 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8353 (run-hooks 'org-after-promote-entry-hook))))
8355 (defun org-demote ()
8356 "Demote the current heading lower down the tree."
8357 (org-with-wide-buffer
8358 (org-back-to-heading t)
8359 (let* ((after-change-functions (remq 'flyspell-after-change-function
8360 after-change-functions))
8361 (level (save-match-data (funcall outline-level)))
8362 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8363 (diff (abs (- level (length down-head) -1))))
8364 (replace-match down-head nil t)
8365 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8366 (when org-adapt-indentation (org-fixup-indentation diff))
8367 (run-hooks 'org-after-demote-entry-hook))))
8369 (defun org-cycle-level ()
8370 "Cycle the level of an empty headline through possible states.
8371 This goes first to child, then to parent, level, then up the hierarchy.
8372 After top level, it switches back to sibling level."
8373 (interactive)
8374 (let ((org-adapt-indentation nil))
8375 (when (org-point-at-end-of-empty-headline)
8376 (setq this-command 'org-cycle-level) ; Only needed for caching
8377 (let ((cur-level (org-current-level))
8378 (prev-level (org-get-previous-line-level)))
8379 (cond
8380 ;; If first headline in file, promote to top-level.
8381 ((= prev-level 0)
8382 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8383 do (org-do-promote)))
8384 ;; If same level as prev, demote one.
8385 ((= prev-level cur-level)
8386 (org-do-demote))
8387 ;; If parent is top-level, promote to top level if not already.
8388 ((= prev-level 1)
8389 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8390 do (org-do-promote)))
8391 ;; If top-level, return to prev-level.
8392 ((= cur-level 1)
8393 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8394 do (org-do-demote)))
8395 ;; If less than prev-level, promote one.
8396 ((< cur-level prev-level)
8397 (org-do-promote))
8398 ;; If deeper than prev-level, promote until higher than
8399 ;; prev-level.
8400 ((> cur-level prev-level)
8401 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8402 do (org-do-promote))))
8403 t))))
8405 (defun org-map-tree (fun)
8406 "Call FUN for every heading underneath the current one."
8407 (org-back-to-heading)
8408 (let ((level (funcall outline-level)))
8409 (save-excursion
8410 (funcall fun)
8411 (while (and (progn
8412 (outline-next-heading)
8413 (> (funcall outline-level) level))
8414 (not (eobp)))
8415 (funcall fun)))))
8417 (defun org-map-region (fun beg end)
8418 "Call FUN for every heading between BEG and END."
8419 (let ((org-ignore-region t))
8420 (save-excursion
8421 (setq end (copy-marker end))
8422 (goto-char beg)
8423 (when (and (re-search-forward org-outline-regexp-bol nil t)
8424 (< (point) end))
8425 (funcall fun))
8426 (while (and (progn
8427 (outline-next-heading)
8428 (< (point) end))
8429 (not (eobp)))
8430 (funcall fun)))))
8432 (defun org-fixup-indentation (diff)
8433 "Change the indentation in the current entry by DIFF.
8435 DIFF is an integer. Indentation is done according to the
8436 following rules:
8438 - Planning information and property drawers are always indented
8439 according to the new level of the headline;
8441 - Footnote definitions and their contents are ignored;
8443 - Inlinetasks' boundaries are not shifted;
8445 - Empty lines are ignored;
8447 - Other lines' indentation are shifted by DIFF columns, unless
8448 it would introduce a structural change in the document, in
8449 which case no shifting is done at all.
8451 Assume point is at a heading or an inlinetask beginning."
8452 (org-with-wide-buffer
8453 (narrow-to-region (line-beginning-position)
8454 (save-excursion
8455 (if (org-with-limited-levels (org-at-heading-p))
8456 (org-with-limited-levels (outline-next-heading))
8457 (org-inlinetask-goto-end))
8458 (point)))
8459 (forward-line)
8460 ;; Indent properly planning info and property drawer.
8461 (when (looking-at-p org-planning-line-re)
8462 (org-indent-line)
8463 (forward-line))
8464 (when (looking-at org-property-drawer-re)
8465 (goto-char (match-end 0))
8466 (forward-line)
8467 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8468 (catch 'no-shift
8469 (when (zerop diff) (throw 'no-shift nil))
8470 ;; If DIFF is negative, first check if a shift is possible at all
8471 ;; (e.g., it doesn't break structure). This can only happen if
8472 ;; some contents are not properly indented.
8473 (let ((case-fold-search t))
8474 (when (< diff 0)
8475 (let ((diff (- diff))
8476 (forbidden-re (concat org-outline-regexp
8477 "\\|"
8478 (substring org-footnote-definition-re 1))))
8479 (save-excursion
8480 (while (not (eobp))
8481 (cond
8482 ((looking-at-p "[ \t]*$") (forward-line))
8483 ((and (looking-at-p org-footnote-definition-re)
8484 (let ((e (org-element-at-point)))
8485 (and (eq (org-element-type e) 'footnote-definition)
8486 (goto-char (org-element-property :end e))))))
8487 ((looking-at-p org-outline-regexp) (forward-line))
8488 ;; Give up if shifting would move before column 0 or
8489 ;; if it would introduce a headline or a footnote
8490 ;; definition.
8492 (skip-chars-forward " \t")
8493 (let ((ind (current-column)))
8494 (when (or (< ind diff)
8495 (and (= ind diff) (looking-at-p forbidden-re)))
8496 (throw 'no-shift nil)))
8497 ;; Ignore contents of example blocks and source
8498 ;; blocks if their indentation is meant to be
8499 ;; preserved. Jump to block's closing line.
8500 (beginning-of-line)
8501 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8502 (let ((e (org-element-at-point)))
8503 (and (memq (org-element-type e)
8504 '(example-block src-block))
8505 (or org-src-preserve-indentation
8506 (org-element-property :preserve-indent e))
8507 (goto-char (org-element-property :end e))
8508 (progn (skip-chars-backward " \r\t\n")
8509 (beginning-of-line)
8510 t))))
8511 (forward-line))))))))
8512 ;; Shift lines but footnote definitions, inlinetasks boundaries
8513 ;; by DIFF. Also skip contents of source or example blocks
8514 ;; when indentation is meant to be preserved.
8515 (while (not (eobp))
8516 (cond
8517 ((and (looking-at-p org-footnote-definition-re)
8518 (let ((e (org-element-at-point)))
8519 (and (eq (org-element-type e) 'footnote-definition)
8520 (goto-char (org-element-property :end e))))))
8521 ((looking-at-p org-outline-regexp) (forward-line))
8522 ((looking-at-p "[ \t]*$") (forward-line))
8524 (indent-line-to (+ (org-get-indentation) diff))
8525 (beginning-of-line)
8526 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8527 (let ((e (org-element-at-point)))
8528 (and (memq (org-element-type e)
8529 '(example-block src-block))
8530 (or org-src-preserve-indentation
8531 (org-element-property :preserve-indent e))
8532 (goto-char (org-element-property :end e))
8533 (progn (skip-chars-backward " \r\t\n")
8534 (beginning-of-line)
8535 t))))
8536 (forward-line)))))))))
8538 (defun org-convert-to-odd-levels ()
8539 "Convert an org-mode file with all levels allowed to one with odd levels.
8540 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8541 level 5 etc."
8542 (interactive)
8543 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8544 (let ((outline-level 'org-outline-level)
8545 (org-odd-levels-only nil) n)
8546 (save-excursion
8547 (goto-char (point-min))
8548 (while (re-search-forward "^\\*\\*+ " nil t)
8549 (setq n (- (length (match-string 0)) 2))
8550 (while (>= (setq n (1- n)) 0)
8551 (org-demote))
8552 (end-of-line 1))))))
8554 (defun org-convert-to-oddeven-levels ()
8555 "Convert an org-mode file with only odd levels to one with odd/even levels.
8556 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8557 file contains a section with an even level, conversion would
8558 destroy the structure of the file. An error is signaled in this
8559 case."
8560 (interactive)
8561 (goto-char (point-min))
8562 ;; First check if there are no even levels
8563 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8564 (org-show-set-visibility 'canonical)
8565 (error "Not all levels are odd in this file. Conversion not possible"))
8566 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8567 (let ((outline-regexp org-outline-regexp)
8568 (outline-level 'org-outline-level)
8569 (org-odd-levels-only nil) n)
8570 (save-excursion
8571 (goto-char (point-min))
8572 (while (re-search-forward "^\\*\\*+ " nil t)
8573 (setq n (/ (1- (length (match-string 0))) 2))
8574 (while (>= (setq n (1- n)) 0)
8575 (org-promote))
8576 (end-of-line 1))))))
8578 (defun org-tr-level (n)
8579 "Make N odd if required."
8580 (if org-odd-levels-only (1+ (/ n 2)) n))
8582 ;;; Vertical tree motion, cutting and pasting of subtrees
8584 (defun org-move-subtree-up (&optional arg)
8585 "Move the current subtree up past ARG headlines of the same level."
8586 (interactive "p")
8587 (org-move-subtree-down (- (prefix-numeric-value arg))))
8589 (defun org-move-subtree-down (&optional arg)
8590 "Move the current subtree down past ARG headlines of the same level."
8591 (interactive "p")
8592 (setq arg (prefix-numeric-value arg))
8593 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8594 'org-get-last-sibling))
8595 (ins-point (make-marker))
8596 (cnt (abs arg))
8597 (col (current-column))
8598 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8599 ;; Select the tree
8600 (org-back-to-heading)
8601 (setq beg0 (point))
8602 (save-excursion
8603 (setq ne-beg (org-back-over-empty-lines))
8604 (setq beg (point)))
8605 (save-match-data
8606 (save-excursion (outline-end-of-heading)
8607 (setq folded (outline-invisible-p)))
8608 (progn (org-end-of-subtree nil t)
8609 (unless (eobp) (backward-char))))
8610 (outline-next-heading)
8611 (setq ne-end (org-back-over-empty-lines))
8612 (setq end (point))
8613 (goto-char beg0)
8614 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8615 ;; include less whitespace
8616 (save-excursion
8617 (goto-char beg)
8618 (forward-line (- ne-beg ne-end))
8619 (setq beg (point))))
8620 ;; Find insertion point, with error handling
8621 (while (> cnt 0)
8622 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8623 (progn (goto-char beg0)
8624 (user-error "Cannot move past superior level or buffer limit")))
8625 (setq cnt (1- cnt)))
8626 (when (> arg 0)
8627 ;; Moving forward - still need to move over subtree
8628 (org-end-of-subtree t t)
8629 (save-excursion
8630 (org-back-over-empty-lines)
8631 (or (bolp) (newline))))
8632 (setq ne-ins (org-back-over-empty-lines))
8633 (move-marker ins-point (point))
8634 (setq txt (buffer-substring beg end))
8635 (org-save-markers-in-region beg end)
8636 (delete-region beg end)
8637 (org-remove-empty-overlays-at beg)
8638 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8639 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8640 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8641 (let ((bbb (point)))
8642 (insert-before-markers txt)
8643 (org-reinstall-markers-in-region bbb)
8644 (move-marker ins-point bbb))
8645 (or (bolp) (insert "\n"))
8646 (setq ins-end (point))
8647 (goto-char ins-point)
8648 (org-skip-whitespace)
8649 (when (and (< arg 0)
8650 (org-first-sibling-p)
8651 (> ne-ins ne-beg))
8652 ;; Move whitespace back to beginning
8653 (save-excursion
8654 (goto-char ins-end)
8655 (let ((kill-whole-line t))
8656 (kill-line (- ne-ins ne-beg)) (point)))
8657 (insert (make-string (- ne-ins ne-beg) ?\n)))
8658 (move-marker ins-point nil)
8659 (if folded
8660 (outline-hide-subtree)
8661 (org-show-entry)
8662 (org-show-children)
8663 (org-cycle-hide-drawers 'children))
8664 (org-clean-visibility-after-subtree-move)
8665 ;; move back to the initial column we were at
8666 (move-to-column col)))
8668 (defvar org-subtree-clip ""
8669 "Clipboard for cut and paste of subtrees.
8670 This is actually only a copy of the kill, because we use the normal kill
8671 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8673 (defvar org-subtree-clip-folded nil
8674 "Was the last copied subtree folded?
8675 This is used to fold the tree back after pasting.")
8677 (defun org-cut-subtree (&optional n)
8678 "Cut the current subtree into the clipboard.
8679 With prefix arg N, cut this many sequential subtrees.
8680 This is a short-hand for marking the subtree and then cutting it."
8681 (interactive "p")
8682 (org-copy-subtree n 'cut))
8684 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8685 "Copy the current subtree it in the clipboard.
8686 With prefix arg N, copy this many sequential subtrees.
8687 This is a short-hand for marking the subtree and then copying it.
8688 If CUT is non-nil, actually cut the subtree.
8689 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8690 of some markers in the region, even if CUT is non-nil. This is
8691 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8692 (interactive "p")
8693 (let (beg end folded (beg0 (point)))
8694 (if (called-interactively-p 'any)
8695 (org-back-to-heading nil) ; take what looks like a subtree
8696 (org-back-to-heading t)) ; take what is really there
8697 (setq beg (point))
8698 (skip-chars-forward " \t\r\n")
8699 (save-match-data
8700 (if nosubtrees
8701 (outline-next-heading)
8702 (save-excursion (outline-end-of-heading)
8703 (setq folded (outline-invisible-p)))
8704 (ignore-errors (org-forward-heading-same-level (1- n) t))
8705 (org-end-of-subtree t t)))
8706 ;; Include the end of an inlinetask
8707 (when (and (featurep 'org-inlinetask)
8708 (looking-at-p (concat (org-inlinetask-outline-regexp)
8709 "END[ \t]*$")))
8710 (end-of-line))
8711 (setq end (point))
8712 (goto-char beg0)
8713 (when (> end beg)
8714 (setq org-subtree-clip-folded folded)
8715 (when (or cut force-store-markers)
8716 (org-save-markers-in-region beg end))
8717 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8718 (setq org-subtree-clip (current-kill 0))
8719 (message "%s: Subtree(s) with %d characters"
8720 (if cut "Cut" "Copied")
8721 (length org-subtree-clip)))))
8723 (defun org-paste-subtree (&optional level tree for-yank remove)
8724 "Paste the clipboard as a subtree, with modification of headline level.
8725 The entire subtree is promoted or demoted in order to match a new headline
8726 level.
8728 If the cursor is at the beginning of a headline, the same level as
8729 that headline is used to paste the tree.
8731 If not, the new level is derived from the *visible* headings
8732 before and after the insertion point, and taken to be the inferior headline
8733 level of the two. So if the previous visible heading is level 3 and the
8734 next is level 4 (or vice versa), level 4 will be used for insertion.
8735 This makes sure that the subtree remains an independent subtree and does
8736 not swallow low level entries.
8738 You can also force a different level, either by using a numeric prefix
8739 argument, or by inserting the heading marker by hand. For example, if the
8740 cursor is after \"*****\", then the tree will be shifted to level 5.
8742 If optional TREE is given, use this text instead of the kill ring.
8744 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8745 move back over whitespace before inserting, and move point to the end of
8746 the inserted text when done.
8748 When REMOVE is non-nil, remove the subtree from the clipboard."
8749 (interactive "P")
8750 (setq tree (or tree (and kill-ring (current-kill 0))))
8751 (unless (org-kill-is-subtree-p tree)
8752 (user-error "%s"
8753 (substitute-command-keys
8754 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8755 (org-with-limited-levels
8756 (let* ((visp (not (outline-invisible-p)))
8757 (txt tree)
8758 (^re_ "\\(\\*+\\)[ \t]*")
8759 (old-level (if (string-match org-outline-regexp-bol txt)
8760 (- (match-end 0) (match-beginning 0) 1)
8761 -1))
8762 (force-level (cond (level (prefix-numeric-value level))
8763 ((and (looking-at "[ \t]*$")
8764 (string-match
8765 "^\\*+$" (buffer-substring
8766 (point-at-bol) (point))))
8767 (- (match-end 0) (match-beginning 0)))
8768 ((and (bolp)
8769 (looking-at org-outline-regexp))
8770 (- (match-end 0) (point) 1))))
8771 (previous-level (save-excursion
8772 (condition-case nil
8773 (progn
8774 (outline-previous-visible-heading 1)
8775 (if (looking-at ^re_)
8776 (- (match-end 0) (match-beginning 0) 1)
8778 (error 1))))
8779 (next-level (save-excursion
8780 (condition-case nil
8781 (progn
8782 (or (looking-at org-outline-regexp)
8783 (outline-next-visible-heading 1))
8784 (if (looking-at ^re_)
8785 (- (match-end 0) (match-beginning 0) 1)
8787 (error 1))))
8788 (new-level (or force-level (max previous-level next-level)))
8789 (shift (if (or (= old-level -1)
8790 (= new-level -1)
8791 (= old-level new-level))
8793 (- new-level old-level)))
8794 (delta (if (> shift 0) -1 1))
8795 (func (if (> shift 0) 'org-demote 'org-promote))
8796 (org-odd-levels-only nil)
8797 beg end newend)
8798 ;; Remove the forced level indicator
8799 (when force-level
8800 (delete-region (point-at-bol) (point)))
8801 ;; Paste
8802 (beginning-of-line (if (bolp) 1 2))
8803 (setq beg (point))
8804 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8805 (insert-before-markers txt)
8806 (unless (string-match "\n\\'" txt) (insert "\n"))
8807 (setq newend (point))
8808 (org-reinstall-markers-in-region beg)
8809 (setq end (point))
8810 (goto-char beg)
8811 (skip-chars-forward " \t\n\r")
8812 (setq beg (point))
8813 (when (and (outline-invisible-p) visp)
8814 (save-excursion (outline-show-heading)))
8815 ;; Shift if necessary
8816 (unless (= shift 0)
8817 (save-restriction
8818 (narrow-to-region beg end)
8819 (while (not (= shift 0))
8820 (org-map-region func (point-min) (point-max))
8821 (setq shift (+ delta shift)))
8822 (goto-char (point-min))
8823 (setq newend (point-max))))
8824 (when (or (called-interactively-p 'interactive) for-yank)
8825 (message "Clipboard pasted as level %d subtree" new-level))
8826 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8827 kill-ring
8828 (eq org-subtree-clip (current-kill 0))
8829 org-subtree-clip-folded)
8830 ;; The tree was folded before it was killed/copied
8831 (outline-hide-subtree))
8832 (and for-yank (goto-char newend))
8833 (and remove (setq kill-ring (cdr kill-ring))))))
8835 (defun org-kill-is-subtree-p (&optional txt)
8836 "Check if the current kill is an outline subtree, or a set of trees.
8837 Returns nil if kill does not start with a headline, or if the first
8838 headline level is not the largest headline level in the tree.
8839 So this will actually accept several entries of equal levels as well,
8840 which is OK for `org-paste-subtree'.
8841 If optional TXT is given, check this string instead of the current kill."
8842 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8843 (re (org-get-limited-outline-regexp))
8844 (^re (concat "^" re))
8845 (start-level (and kill
8846 (string-match
8847 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8848 kill)
8849 (- (match-end 2) (match-beginning 2) 1)))
8850 (start (1+ (or (match-beginning 2) -1))))
8851 (if (not start-level)
8852 (progn
8853 nil) ;; does not even start with a heading
8854 (catch 'exit
8855 (while (setq start (string-match ^re kill (1+ start)))
8856 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8857 (throw 'exit nil)))
8858 t))))
8860 (defvar org-markers-to-move nil
8861 "Markers that should be moved with a cut-and-paste operation.
8862 Those markers are stored together with their positions relative to
8863 the start of the region.")
8865 (defun org-save-markers-in-region (beg end)
8866 "Check markers in region.
8867 If these markers are between BEG and END, record their position relative
8868 to BEG, so that after moving the block of text, we can put the markers back
8869 into place.
8870 This function gets called just before an entry or tree gets cut from the
8871 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8872 called immediately, to move the markers with the entries."
8873 (setq org-markers-to-move nil)
8874 (when (featurep 'org-clock)
8875 (org-clock-save-markers-for-cut-and-paste beg end))
8876 (when (featurep 'org-agenda)
8877 (org-agenda-save-markers-for-cut-and-paste beg end)))
8879 (defun org-check-and-save-marker (marker beg end)
8880 "Check if MARKER is between BEG and END.
8881 If yes, remember the marker and the distance to BEG."
8882 (when (and (marker-buffer marker)
8883 (equal (marker-buffer marker) (current-buffer))
8884 (>= marker beg) (< marker end))
8885 (push (cons marker (- marker beg)) org-markers-to-move)))
8887 (defun org-reinstall-markers-in-region (beg)
8888 "Move all remembered markers to their position relative to BEG."
8889 (dolist (x org-markers-to-move)
8890 (move-marker (car x) (+ beg (cdr x))))
8891 (setq org-markers-to-move nil))
8893 (defun org-narrow-to-subtree ()
8894 "Narrow buffer to the current subtree."
8895 (interactive)
8896 (save-excursion
8897 (save-match-data
8898 (org-with-limited-levels
8899 (narrow-to-region
8900 (progn (org-back-to-heading t) (point))
8901 (progn (org-end-of-subtree t t)
8902 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8903 (point)))))))
8905 (defun org-narrow-to-block ()
8906 "Narrow buffer to the current block."
8907 (interactive)
8908 (let* ((case-fold-search t)
8909 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8910 "^[ \t]*#\\+end_.*")))
8911 (if blockp
8912 (narrow-to-region (car blockp) (cdr blockp))
8913 (user-error "Not in a block"))))
8915 (defun org-clone-subtree-with-time-shift (n &optional shift)
8916 "Clone the task (subtree) at point N times.
8917 The clones will be inserted as siblings.
8919 In interactive use, the user will be prompted for the number of
8920 clones to be produced. If the entry has a timestamp, the user
8921 will also be prompted for a time shift, which may be a repeater
8922 as used in time stamps, for example `+3d'. To disable this,
8923 you can call the function with a universal prefix argument.
8925 When a valid repeater is given and the entry contains any time
8926 stamps, the clones will become a sequence in time, with time
8927 stamps in the subtree shifted for each clone produced. If SHIFT
8928 is nil or the empty string, time stamps will be left alone. The
8929 ID property of the original subtree is removed.
8931 If the original subtree did contain time stamps with a repeater,
8932 the following will happen:
8933 - the repeater will be removed in each clone
8934 - an additional clone will be produced, with the current, unshifted
8935 date(s) in the entry.
8936 - the original entry will be placed *after* all the clones, with
8937 repeater intact.
8938 - the start days in the repeater in the original entry will be shifted
8939 to past the last clone.
8940 In this way you can spell out a number of instances of a repeating task,
8941 and still retain the repeater to cover future instances of the task.
8943 As described above, N+1 clones are produced when the original
8944 subtree has a repeater. Setting N to 0, then, can be used to
8945 remove the repeater from a subtree and create a shifted clone
8946 with the original repeater."
8947 (interactive "nNumber of clones to produce: ")
8948 (let ((shift
8949 (or shift
8950 (if (and (not (equal current-prefix-arg '(4)))
8951 (save-excursion
8952 (re-search-forward org-ts-regexp-both
8953 (save-excursion
8954 (org-end-of-subtree t)
8955 (point)) t)))
8956 (read-from-minibuffer
8957 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8958 ""))) ;; No time shift
8959 (n-no-remove -1)
8960 (drawer-re org-drawer-regexp)
8961 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8962 beg end template task idprop
8963 shift-n shift-what doshift nmin nmax)
8964 (unless (wholenump n)
8965 (user-error "Invalid number of replications %s" n))
8966 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8967 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8968 shift)))
8969 (user-error "Invalid shift specification %s" shift))
8970 (when doshift
8971 (setq shift-n (string-to-number (match-string 1 shift))
8972 shift-what (cdr (assoc (match-string 2 shift)
8973 '(("d" . day) ("w" . week)
8974 ("m" . month) ("y" . year))))))
8975 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8976 (setq nmin 1 nmax n)
8977 (org-back-to-heading t)
8978 (setq beg (point))
8979 (setq idprop (org-entry-get nil "ID"))
8980 (org-end-of-subtree t t)
8981 (or (bolp) (insert "\n"))
8982 (setq end (point))
8983 (setq template (buffer-substring beg end))
8984 (when (and doshift
8985 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8986 (delete-region beg end)
8987 (setq end beg)
8988 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8989 (goto-char end)
8990 (cl-loop for n from nmin to nmax do
8991 ;; prepare clone
8992 (with-temp-buffer
8993 (insert template)
8994 (org-mode)
8995 (goto-char (point-min))
8996 (org-show-subtree)
8997 (and idprop (if org-clone-delete-id
8998 (org-entry-delete nil "ID")
8999 (org-id-get-create t)))
9000 (unless (= n 0)
9001 (while (re-search-forward org-clock-re nil t)
9002 (kill-whole-line))
9003 (goto-char (point-min))
9004 (while (re-search-forward drawer-re nil t)
9005 (org-remove-empty-drawer-at (point))))
9006 (goto-char (point-min))
9007 (when doshift
9008 (while (re-search-forward org-ts-regexp-both nil t)
9009 (org-timestamp-change (* n shift-n) shift-what))
9010 (unless (= n n-no-remove)
9011 (goto-char (point-min))
9012 (while (re-search-forward org-ts-regexp nil t)
9013 (save-excursion
9014 (goto-char (match-beginning 0))
9015 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9016 (delete-region (match-beginning 1) (match-end 1)))))))
9017 (setq task (buffer-string)))
9018 (insert task))
9019 (goto-char beg)))
9021 ;;; Outline Sorting
9023 (defun org-sort (with-case)
9024 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9025 Optional argument WITH-CASE means sort case-sensitively."
9026 (interactive "P")
9027 (cond
9028 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9029 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9031 (org-call-with-arg 'org-sort-entries with-case))))
9033 (defun org-sort-remove-invisible (s)
9034 "Remove invisible links from string S."
9035 (remove-text-properties 0 (length s) org-rm-props s)
9036 (while (string-match org-bracket-link-regexp s)
9037 (setq s (replace-match (if (match-end 2)
9038 (match-string 3 s)
9039 (match-string 1 s))
9040 t t s)))
9041 (let ((st (format " %s " s)))
9042 (while (string-match org-emph-re st)
9043 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9044 (setq s (substring st 1 -1)))
9047 (defvar org-priority-regexp) ; defined later in the file
9049 (defvar org-after-sorting-entries-or-items-hook nil
9050 "Hook that is run after a bunch of entries or items have been sorted.
9051 When children are sorted, the cursor is in the parent line when this
9052 hook gets called. When a region or a plain list is sorted, the cursor
9053 will be in the first entry of the sorted region/list.")
9055 (defun org-sort-entries
9056 (&optional with-case sorting-type getkey-func compare-func property)
9057 "Sort entries on a certain level of an outline tree.
9058 If there is an active region, the entries in the region are sorted.
9059 Else, if the cursor is before the first entry, sort the top-level items.
9060 Else, the children of the entry at point are sorted.
9062 Sorting can be alphabetically, numerically, by date/time as given by
9063 a time stamp, by a property, by priority order, or by a custom function.
9065 The command prompts for the sorting type unless it has been given to the
9066 function through the SORTING-TYPE argument, which needs to be a character,
9067 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9068 the precise meaning of each character:
9070 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9071 c By creation time, which is assumed to be the first inactive time stamp
9072 at the beginning of a line.
9073 d By deadline date/time.
9074 k By clocking time.
9075 n Numerically, by converting the beginning of the entry/item to a number.
9076 o By order of TODO keywords.
9077 p By priority according to the cookie.
9078 r By the value of a property.
9079 s By scheduled date/time.
9080 t By date/time, either the first active time stamp in the entry, or, if
9081 none exist, by the first inactive one.
9083 Capital letters will reverse the sort order.
9085 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9086 called with point at the beginning of the record. It must return either
9087 a string or a number that should serve as the sorting key for that record.
9089 Comparing entries ignores case by default. However, with an optional argument
9090 WITH-CASE, the sorting considers case as well.
9092 Sorting is done against the visible part of the headlines, it ignores hidden
9093 links.
9095 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9096 (interactive "P")
9097 (let ((case-func (if with-case 'identity 'downcase))
9098 (cmstr
9099 ;; The clock marker is lost when using `sort-subr', let's
9100 ;; store the clocking string.
9101 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9102 (save-excursion
9103 (goto-char org-clock-marker)
9104 (buffer-substring-no-properties (line-beginning-position)
9105 (point)))))
9106 start beg end stars re re2
9107 txt what tmp)
9108 ;; Find beginning and end of region to sort
9109 (cond
9110 ((org-region-active-p)
9111 ;; we will sort the region
9112 (setq end (region-end)
9113 what "region")
9114 (goto-char (region-beginning))
9115 (unless (org-at-heading-p) (outline-next-heading))
9116 (setq start (point)))
9117 ((or (org-at-heading-p)
9118 (ignore-errors (progn (org-back-to-heading) t)))
9119 ;; we will sort the children of the current headline
9120 (org-back-to-heading)
9121 (setq start (point)
9122 end (progn (org-end-of-subtree t t)
9123 (or (bolp) (insert "\n"))
9124 (when (>= (org-back-over-empty-lines) 1)
9125 (forward-line 1))
9126 (point))
9127 what "children")
9128 (goto-char start)
9129 (outline-show-subtree)
9130 (outline-next-heading))
9132 ;; we will sort the top-level entries in this file
9133 (goto-char (point-min))
9134 (or (org-at-heading-p) (outline-next-heading))
9135 (setq start (point))
9136 (goto-char (point-max))
9137 (beginning-of-line 1)
9138 (when (looking-at ".*?\\S-")
9139 ;; File ends in a non-white line
9140 (end-of-line 1)
9141 (insert "\n"))
9142 (setq end (point-max))
9143 (setq what "top-level")
9144 (goto-char start)
9145 (outline-show-all)))
9147 (setq beg (point))
9148 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9150 (looking-at "\\(\\*+\\)")
9151 (setq stars (match-string 1)
9152 re (concat "^" (regexp-quote stars) " +")
9153 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9154 txt (buffer-substring beg end))
9155 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9156 (when (and (not (equal stars "*")) (string-match re2 txt))
9157 (user-error "Region to sort contains a level above the first entry"))
9159 (unless sorting-type
9160 (message
9161 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9162 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9163 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9164 what)
9165 (setq sorting-type (read-char-exclusive))
9167 (unless getkey-func
9168 (and (= (downcase sorting-type) ?f)
9169 (setq getkey-func
9170 (completing-read "Sort using function: "
9171 obarray 'fboundp t nil nil))
9172 (setq getkey-func (intern getkey-func))))
9174 (and (= (downcase sorting-type) ?r)
9175 (not property)
9176 (setq property
9177 (completing-read "Property: "
9178 (mapcar #'list (org-buffer-property-keys t))
9179 nil t))))
9181 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9182 (message "Sorting entries...")
9184 (save-restriction
9185 (narrow-to-region start end)
9186 (let ((dcst (downcase sorting-type))
9187 (case-fold-search nil)
9188 (now (current-time)))
9189 (sort-subr
9190 (/= dcst sorting-type)
9191 ;; This function moves to the beginning character of the "record" to
9192 ;; be sorted.
9193 (lambda nil
9194 (if (re-search-forward re nil t)
9195 (goto-char (match-beginning 0))
9196 (goto-char (point-max))))
9197 ;; This function moves to the last character of the "record" being
9198 ;; sorted.
9199 (lambda nil
9200 (save-match-data
9201 (condition-case nil
9202 (outline-forward-same-level 1)
9203 (error
9204 (goto-char (point-max))))))
9205 ;; This function returns the value that gets sorted against.
9206 (lambda nil
9207 (cond
9208 ((= dcst ?n)
9209 (if (looking-at org-complex-heading-regexp)
9210 (string-to-number (org-sort-remove-invisible (match-string 4)))
9211 nil))
9212 ((= dcst ?a)
9213 (if (looking-at org-complex-heading-regexp)
9214 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9215 nil))
9216 ((= dcst ?k)
9217 (or (get-text-property (point) :org-clock-minutes) 0))
9218 ((= dcst ?t)
9219 (let ((end (save-excursion (outline-next-heading) (point))))
9220 (if (or (re-search-forward org-ts-regexp end t)
9221 (re-search-forward org-ts-regexp-both end t))
9222 (org-time-string-to-seconds (match-string 0))
9223 (float-time now))))
9224 ((= dcst ?c)
9225 (let ((end (save-excursion (outline-next-heading) (point))))
9226 (if (re-search-forward
9227 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9228 end t)
9229 (org-time-string-to-seconds (match-string 0))
9230 (float-time now))))
9231 ((= dcst ?s)
9232 (let ((end (save-excursion (outline-next-heading) (point))))
9233 (if (re-search-forward org-scheduled-time-regexp end t)
9234 (org-time-string-to-seconds (match-string 1))
9235 (float-time now))))
9236 ((= dcst ?d)
9237 (let ((end (save-excursion (outline-next-heading) (point))))
9238 (if (re-search-forward org-deadline-time-regexp end t)
9239 (org-time-string-to-seconds (match-string 1))
9240 (float-time now))))
9241 ((= dcst ?p)
9242 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9243 (string-to-char (match-string 2))
9244 org-default-priority))
9245 ((= dcst ?r)
9246 (or (org-entry-get nil property) ""))
9247 ((= dcst ?o)
9248 (when (looking-at org-complex-heading-regexp)
9249 (let* ((m (match-string 2))
9250 (s (if (member m org-done-keywords) '- '+)))
9251 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9252 ((= dcst ?f)
9253 (if getkey-func
9254 (progn
9255 (setq tmp (funcall getkey-func))
9256 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9257 tmp)
9258 (error "Invalid key function `%s'" getkey-func)))
9259 (t (error "Invalid sorting type `%c'" sorting-type))))
9261 (cond
9262 ((= dcst ?a) 'string<)
9263 ((= dcst ?f) compare-func)
9264 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9265 (run-hooks 'org-after-sorting-entries-or-items-hook)
9266 ;; Reset the clock marker if needed
9267 (when cmstr
9268 (save-excursion
9269 (goto-char start)
9270 (search-forward cmstr nil t)
9271 (move-marker org-clock-marker (point))))
9272 (message "Sorting entries...done")))
9274 ;;; The orgstruct minor mode
9276 ;; Define a minor mode which can be used in other modes in order to
9277 ;; integrate the org-mode structure editing commands.
9279 ;; This is really a hack, because the org-mode structure commands use
9280 ;; keys which normally belong to the major mode. Here is how it
9281 ;; works: The minor mode defines all the keys necessary to operate the
9282 ;; structure commands, but wraps the commands into a function which
9283 ;; tests if the cursor is currently at a headline or a plain list
9284 ;; item. If that is the case, the structure command is used,
9285 ;; temporarily setting many Org-mode variables like regular
9286 ;; expressions for filling etc. However, when any of those keys is
9287 ;; used at a different location, function uses `key-binding' to look
9288 ;; up if the key has an associated command in another currently active
9289 ;; keymap (minor modes, major mode, global), and executes that
9290 ;; command. There might be problems if any of the keys is otherwise
9291 ;; used as a prefix key.
9293 (defcustom orgstruct-heading-prefix-regexp ""
9294 "Regexp that matches the custom prefix of Org headlines in
9295 orgstruct(++)-mode."
9296 :group 'org
9297 :version "24.4"
9298 :package-version '(Org . "8.3")
9299 :type 'regexp)
9300 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9302 (defcustom orgstruct-setup-hook nil
9303 "Hook run after orgstruct-mode-map is filled."
9304 :group 'org
9305 :version "24.4"
9306 :package-version '(Org . "8.0")
9307 :type 'hook)
9309 (defvar orgstruct-initialized nil)
9311 (defvar org-local-vars nil
9312 "List of local variables, for use by `orgstruct-mode'.")
9314 ;;;###autoload
9315 (define-minor-mode orgstruct-mode
9316 "Toggle the minor mode `orgstruct-mode'.
9317 This mode is for using Org-mode structure commands in other
9318 modes. The following keys behave as if Org-mode were active, if
9319 the cursor is on a headline, or on a plain list item (both as
9320 defined by Org-mode)."
9321 nil " OrgStruct" (make-sparse-keymap)
9322 (funcall (if orgstruct-mode
9323 'add-to-invisibility-spec
9324 'remove-from-invisibility-spec)
9325 '(outline . t))
9326 (when orgstruct-mode
9327 (org-load-modules-maybe)
9328 (unless orgstruct-initialized
9329 (orgstruct-setup)
9330 (setq orgstruct-initialized t))))
9332 ;;;###autoload
9333 (defun turn-on-orgstruct ()
9334 "Unconditionally turn on `orgstruct-mode'."
9335 (orgstruct-mode 1))
9337 (defvar-local orgstruct-is-++ nil
9338 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9339 (defvar-local org-fb-vars nil)
9340 (defun orgstruct++-mode (&optional arg)
9341 "Toggle `orgstruct-mode', the enhanced version of it.
9342 In addition to setting orgstruct-mode, this also exports all
9343 indentation and autofilling variables from org-mode into the
9344 buffer. It will also recognize item context in multiline items."
9345 (interactive "P")
9346 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9347 (if (< arg 1)
9348 (progn (orgstruct-mode -1)
9349 (dolist (v org-fb-vars)
9350 (set (make-local-variable (car v))
9351 (if (eq (car-safe (cadr v)) 'quote)
9352 (cl-cadadr v)
9353 (nth 1 v)))))
9354 (orgstruct-mode 1)
9355 (setq org-fb-vars nil)
9356 (unless org-local-vars
9357 (setq org-local-vars (org-get-local-variables)))
9358 (let (var val)
9359 (dolist (x org-local-vars)
9360 (when (string-match
9361 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9362 \\|fill-prefix\\|indent-\\)"
9363 (symbol-name (car x)))
9364 (setq var (car x) val (nth 1 x))
9365 (push (list var `(quote ,(eval var))) org-fb-vars)
9366 (set (make-local-variable var)
9367 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9368 (setq-local orgstruct-is-++ t))))
9370 ;;;###autoload
9371 (defun turn-on-orgstruct++ ()
9372 "Unconditionally turn on `orgstruct++-mode'."
9373 (orgstruct++-mode 1))
9375 (defun orgstruct-error ()
9376 "Error when there is no default binding for a structure key."
9377 (interactive)
9378 (funcall (if (fboundp 'user-error)
9379 'user-error
9380 'error)
9381 "This key has no function outside structure elements"))
9383 (defun orgstruct-setup ()
9384 "Setup orgstruct keymap."
9385 (dolist (cell '((org-demote . t)
9386 (org-metaleft . t)
9387 (org-metaright . t)
9388 (org-promote . t)
9389 (org-shiftmetaleft . t)
9390 (org-shiftmetaright . t)
9391 org-backward-element
9392 org-backward-heading-same-level
9393 org-ctrl-c-ret
9394 org-ctrl-c-minus
9395 org-ctrl-c-star
9396 org-cycle
9397 org-force-cycle-archived
9398 org-forward-heading-same-level
9399 org-insert-heading
9400 org-insert-heading-respect-content
9401 org-kill-note-or-show-branches
9402 org-mark-subtree
9403 org-meta-return
9404 org-metadown
9405 org-metaup
9406 org-narrow-to-subtree
9407 org-promote-subtree
9408 org-reveal
9409 org-shiftdown
9410 org-shiftleft
9411 org-shiftmetadown
9412 org-shiftmetaup
9413 org-shiftright
9414 org-shifttab
9415 org-shifttab
9416 org-shiftup
9417 org-show-children
9418 org-show-subtree
9419 org-sort
9420 org-up-element
9421 outline-demote
9422 outline-next-visible-heading
9423 outline-previous-visible-heading
9424 outline-promote
9425 outline-up-heading))
9426 (let ((f (or (car-safe cell) cell))
9427 (disable-when-heading-prefix (cdr-safe cell)))
9428 (when (fboundp f)
9429 (let ((new-bindings))
9430 (dolist (binding (nconc (where-is-internal f org-mode-map)
9431 (where-is-internal f outline-mode-map)))
9432 (push binding new-bindings)
9433 ;; TODO use local-function-key-map
9434 (dolist (rep '(("<tab>" . "TAB")
9435 ("<return>" . "RET")
9436 ("<escape>" . "ESC")
9437 ("<delete>" . "DEL")))
9438 (setq binding (read-kbd-macro
9439 (let ((case-fold-search))
9440 (replace-regexp-in-string
9441 (regexp-quote (cdr rep))
9442 (car rep)
9443 (key-description binding)))))
9444 (cl-pushnew binding new-bindings :test 'equal)))
9445 (dolist (binding new-bindings)
9446 (let ((key (lookup-key orgstruct-mode-map binding)))
9447 (when (or (not key) (numberp key))
9448 (ignore-errors
9449 (org-defkey orgstruct-mode-map
9450 binding
9451 (orgstruct-make-binding
9452 f binding disable-when-heading-prefix))))))))))
9453 (run-hooks 'orgstruct-setup-hook))
9455 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9456 "Create a function for binding in the structure minor mode.
9457 FUN is the command to call inside a table. KEY is the key that
9458 should be checked in for a command to execute outside of tables.
9459 Non-nil `disable-when-heading-prefix' means to disable the command
9460 if `orgstruct-heading-prefix-regexp' is not empty."
9461 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9462 (let ((nname name)
9463 (i 0))
9464 (while (fboundp (intern nname))
9465 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9466 (setq name (intern nname)))
9467 (eval
9468 (let ((bindings '((org-heading-regexp
9469 (concat "^"
9470 orgstruct-heading-prefix-regexp
9471 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9472 (org-outline-regexp
9473 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9474 (org-outline-regexp-bol
9475 (concat "^" org-outline-regexp))
9476 (outline-regexp org-outline-regexp)
9477 (outline-heading-end-regexp "\n")
9478 (outline-level 'org-outline-level)
9479 (outline-heading-alist))))
9480 `(defun ,name (arg)
9481 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9482 "Outside of structure, run the binding of `"
9483 (key-description key) "'."
9484 (when disable-when-heading-prefix
9485 (concat
9486 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9487 "back to the default binding due to limitations of Org's implementation of\n"
9488 "`" (symbol-name fun) "'.")))
9489 (interactive "p")
9490 (let* ((disable
9491 ,(and disable-when-heading-prefix
9492 '(not (string= orgstruct-heading-prefix-regexp ""))))
9493 (fallback
9494 (or disable
9495 (not
9496 (let* ,bindings
9497 (org-context-p 'headline 'item
9498 ,(when (memq fun
9499 '(org-insert-heading
9500 org-insert-heading-respect-content
9501 org-meta-return))
9502 '(when orgstruct-is-++
9503 'item-body))))))))
9504 (if fallback
9505 (let* ((orgstruct-mode)
9506 (binding
9507 (let ((key ,key))
9508 (catch 'exit
9509 (dolist
9510 (rep
9511 '(nil
9512 ("<\\([^>]*\\)tab>" . "\\1TAB")
9513 ("<\\([^>]*\\)return>" . "\\1RET")
9514 ("<\\([^>]*\\)escape>" . "\\1ESC")
9515 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9516 nil)
9517 (when rep
9518 (setq key (read-kbd-macro
9519 (let ((case-fold-search))
9520 (replace-regexp-in-string
9521 (car rep)
9522 (cdr rep)
9523 (key-description key))))))
9524 (when (key-binding key)
9525 (throw 'exit (key-binding key))))))))
9526 (if (keymapp binding)
9527 (org-set-transient-map binding)
9528 (let ((func (or binding
9529 (unless disable
9530 'orgstruct-error))))
9531 (when func
9532 (call-interactively func)))))
9533 (org-run-like-in-org-mode
9534 (lambda ()
9535 (interactive)
9536 (let* ,bindings
9537 (call-interactively ',fun)))))))))
9538 name))
9540 (defun org-contextualize-keys (alist contexts)
9541 "Return valid elements in ALIST depending on CONTEXTS.
9543 `org-agenda-custom-commands' or `org-capture-templates' are the
9544 values used for ALIST, and `org-agenda-custom-commands-contexts'
9545 or `org-capture-templates-contexts' are the associated contexts
9546 definitions."
9547 (let ((contexts
9548 ;; normalize contexts
9549 (mapcar
9550 (lambda(c) (cond ((listp (cadr c))
9551 (list (car c) (car c) (nth 1 c)))
9552 ((string= "" (cadr c))
9553 (list (car c) (car c) (nth 2 c)))
9554 (t c)))
9555 contexts))
9556 (a alist) r s)
9557 ;; loop over all commands or templates
9558 (dolist (c a)
9559 (let (vrules repl)
9560 (cond
9561 ((not (assoc (car c) contexts))
9562 (push c r))
9563 ((and (assoc (car c) contexts)
9564 (setq vrules (org-contextualize-validate-key
9565 (car c) contexts)))
9566 (mapc (lambda (vr)
9567 (unless (equal (car vr) (cadr vr))
9568 (setq repl vr)))
9569 vrules)
9570 (if (not repl) (push c r)
9571 (push (cadr repl) s)
9572 (push
9573 (cons (car c)
9574 (cdr (or (assoc (cadr repl) alist)
9575 (error "Undefined key `%s' as contextual replacement for `%s'"
9576 (cadr repl) (car c)))))
9577 r))))))
9578 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9579 (delq
9581 (delete-dups
9582 (mapcar (lambda (x)
9583 (let ((tpl (car x)))
9584 (unless (delq
9586 (mapcar (lambda (y)
9587 (equal y tpl))
9589 x)))
9590 (reverse r))))))
9592 (defun org-contextualize-validate-key (key contexts)
9593 "Check CONTEXTS for agenda or capture KEY."
9594 (let (res)
9595 (dolist (r contexts)
9596 (dolist (rr (car (last r)))
9597 (when
9598 (and (equal key (car r))
9599 (if (functionp rr) (funcall rr)
9600 (or (and (eq (car rr) 'in-file)
9601 (buffer-file-name)
9602 (string-match (cdr rr) (buffer-file-name)))
9603 (and (eq (car rr) 'in-mode)
9604 (string-match (cdr rr) (symbol-name major-mode)))
9605 (and (eq (car rr) 'in-buffer)
9606 (string-match (cdr rr) (buffer-name)))
9607 (when (and (eq (car rr) 'not-in-file)
9608 (buffer-file-name))
9609 (not (string-match (cdr rr) (buffer-file-name))))
9610 (when (eq (car rr) 'not-in-mode)
9611 (not (string-match (cdr rr) (symbol-name major-mode))))
9612 (when (eq (car rr) 'not-in-buffer)
9613 (not (string-match (cdr rr) (buffer-name)))))))
9614 (push r res))))
9615 (delete-dups (delq nil res))))
9617 (defun org-context-p (&rest contexts)
9618 "Check if local context is any of CONTEXTS.
9619 Possible values in the list of contexts are `table', `headline', and `item'."
9620 (let ((pos (point)))
9621 (goto-char (point-at-bol))
9622 (prog1 (or (and (memq 'table contexts)
9623 (looking-at "[ \t]*|"))
9624 (and (memq 'headline contexts)
9625 (looking-at org-outline-regexp))
9626 (and (memq 'item contexts)
9627 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9628 (and (memq 'item-body contexts)
9629 (org-in-item-p)))
9630 (goto-char pos))))
9632 (defconst org-unique-local-variables
9633 '(org-element--cache
9634 org-element--cache-objects
9635 org-element--cache-sync-keys
9636 org-element--cache-sync-requests
9637 org-element--cache-sync-timer)
9638 "List of local variables that cannot be transferred to another buffer.")
9640 (defun org-get-local-variables ()
9641 "Return a list of all local variables in an Org mode buffer."
9642 (delq nil
9643 (mapcar
9644 (lambda (x)
9645 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9646 (name (car binding)))
9647 (and (not (get name 'org-state))
9648 (not (memq name org-unique-local-variables))
9649 (string-match-p
9650 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9651 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9652 (symbol-name name))
9653 binding)))
9654 (with-temp-buffer
9655 (org-mode)
9656 (buffer-local-variables)))))
9658 (defun org-clone-local-variables (from-buffer &optional regexp)
9659 "Clone local variables from FROM-BUFFER.
9660 Optional argument REGEXP selects variables to clone."
9661 (dolist (pair (buffer-local-variables from-buffer))
9662 (let ((name (car pair)))
9663 (when (and (symbolp name)
9664 (not (memq name org-unique-local-variables))
9665 (or (null regexp) (string-match regexp (symbol-name name))))
9666 (set (make-local-variable name) (cdr pair))))))
9668 ;;;###autoload
9669 (defun org-run-like-in-org-mode (cmd)
9670 "Run a command, pretending that the current buffer is in Org-mode.
9671 This will temporarily bind local variables that are typically bound in
9672 Org-mode to the values they have in Org-mode, and then interactively
9673 call CMD."
9674 (org-load-modules-maybe)
9675 (unless org-local-vars
9676 (setq org-local-vars (org-get-local-variables)))
9677 (let (binds)
9678 (dolist (var org-local-vars)
9679 (when (or (not (boundp (car var)))
9680 (eq (symbol-value (car var))
9681 (default-value (car var))))
9682 (push (list (car var) `(quote ,(cadr var))) binds)))
9683 (eval `(let ,binds
9684 (call-interactively (quote ,cmd))))))
9686 (defun org-get-category (&optional pos force-refresh)
9687 "Get the category applying to position POS."
9688 (save-match-data
9689 (when force-refresh (org-refresh-category-properties))
9690 (let ((pos (or pos (point))))
9691 (or (get-text-property pos 'org-category)
9692 (progn (org-refresh-category-properties)
9693 (get-text-property pos 'org-category))))))
9695 ;;; Refresh properties
9697 (defun org-refresh-properties (dprop tprop)
9698 "Refresh buffer text properties.
9699 DPROP is the drawer property and TPROP is either the
9700 corresponding text property to set, or an alist with each element
9701 being a text property (as a symbol) and a function to apply to
9702 the value of the drawer property."
9703 (let ((case-fold-search t)
9704 (inhibit-read-only t))
9705 (org-with-silent-modifications
9706 (save-excursion
9707 (save-restriction
9708 (widen)
9709 (goto-char (point-min))
9710 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9711 (org-refresh-property tprop (match-string-no-properties 1))))))))
9713 (defun org-refresh-property (tprop p)
9714 "Refresh the buffer text property TPROP from the drawer property P.
9715 The refresh happens only for the current tree (not subtree)."
9716 (unless (org-before-first-heading-p)
9717 (save-excursion
9718 (org-back-to-heading t)
9719 (if (symbolp tprop)
9720 ;; TPROP is a text property symbol
9721 (put-text-property
9722 (point) (or (outline-next-heading) (point-max)) tprop p)
9723 ;; TPROP is an alist with (properties . function) elements
9724 (dolist (al tprop)
9725 (save-excursion
9726 (put-text-property
9727 (line-beginning-position) (or (outline-next-heading) (point-max))
9728 (car al)
9729 (funcall (cdr al) p))))))))
9731 (defun org-refresh-category-properties ()
9732 "Refresh category text properties in the buffer."
9733 (let ((case-fold-search t)
9734 (inhibit-read-only t)
9735 (default-category
9736 (cond ((null org-category)
9737 (if buffer-file-name
9738 (file-name-sans-extension
9739 (file-name-nondirectory buffer-file-name))
9740 "???"))
9741 ((symbolp org-category) (symbol-name org-category))
9742 (t org-category))))
9743 (org-with-silent-modifications
9744 (org-with-wide-buffer
9745 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9746 ;; This is the default category for the buffer. If none is
9747 ;; found, fall-back to `org-category' or buffer file name.
9748 (put-text-property
9749 (point-min) (point-max)
9750 'org-category
9751 (catch 'buffer-category
9752 (goto-char (point-max))
9753 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9754 (let ((element (org-element-at-point)))
9755 (when (eq (org-element-type element) 'keyword)
9756 (throw 'buffer-category
9757 (org-element-property :value element)))))
9758 default-category))
9759 ;; Set sub-tree specific categories.
9760 (goto-char (point-min))
9761 (let ((regexp (org-re-property "CATEGORY")))
9762 (while (re-search-forward regexp nil t)
9763 (let ((value (match-string-no-properties 3)))
9764 (when (org-at-property-p)
9765 (put-text-property
9766 (save-excursion (org-back-to-heading t) (point))
9767 (save-excursion (org-end-of-subtree t t) (point))
9768 'org-category
9769 value)))))))))
9771 (defun org-refresh-stats-properties ()
9772 "Refresh stats text properties in the buffer."
9773 (let (stats)
9774 (org-with-silent-modifications
9775 (save-excursion
9776 (save-restriction
9777 (widen)
9778 (goto-char (point-min))
9779 (while (re-search-forward
9780 (concat org-outline-regexp-bol ".*"
9781 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9782 nil t)
9783 (setq stats (cond ((equal (match-string 3) "0") 0)
9784 ((match-string 2)
9785 (/ (* (string-to-number (match-string 2)) 100)
9786 (string-to-number (match-string 3))))
9787 (t (string-to-number (match-string 1)))))
9788 (org-back-to-heading t)
9789 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9790 'org-stats stats)))))))
9792 (defun org-refresh-effort-properties ()
9793 "Refresh effort properties"
9794 (org-refresh-properties
9795 org-effort-property
9796 '((effort . identity)
9797 (effort-minutes . org-duration-string-to-minutes))))
9799 ;;;; Link Stuff
9801 ;;; Link abbreviations
9803 (defun org-link-expand-abbrev (link)
9804 "Apply replacements as defined in `org-link-abbrev-alist'."
9805 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9806 (let* ((key (match-string 1 link))
9807 (as (or (assoc key org-link-abbrev-alist-local)
9808 (assoc key org-link-abbrev-alist)))
9809 (tag (and (match-end 2) (match-string 3 link)))
9810 rpl)
9811 (if (not as)
9812 link
9813 (setq rpl (cdr as))
9814 (cond
9815 ((symbolp rpl) (funcall rpl tag))
9816 ((string-match "%(\\([^)]+\\))" rpl)
9817 (replace-match
9818 (save-match-data
9819 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9820 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9821 ((string-match "%h" rpl)
9822 (replace-match (url-hexify-string (or tag "")) t t rpl))
9823 (t (concat rpl tag)))))
9824 link))
9826 ;;; Storing and inserting links
9828 (defvar org-insert-link-history nil
9829 "Minibuffer history for links inserted with `org-insert-link'.")
9831 (defvar org-stored-links nil
9832 "Contains the links stored with `org-store-link'.")
9834 (defvar org-store-link-plist nil
9835 "Plist with info about the most recently link created with `org-store-link'.")
9837 (defun org-store-link-functions ()
9838 "Return a list of functions that are called to create and store a link.
9839 The functions defined in the :store property of
9840 `org-link-parameters'.
9842 Each function will be called in turn until one returns a non-nil
9843 value. Each function should check if it is responsible for
9844 creating this link (for example by looking at the major mode).
9845 If not, it must exit and return nil. If yes, it should return
9846 a non-nil value after calling `org-store-link-props' with a list
9847 of properties and values. Special properties are:
9849 :type The link prefix, like \"http\". This must be given.
9850 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9851 This is obligatory as well.
9852 :description Optional default description for the second pair
9853 of brackets in an Org mode link. The user can still change
9854 this when inserting this link into an Org mode buffer.
9856 In addition to these, any additional properties can be specified
9857 and then used in capture templates."
9858 (cl-loop for link in org-link-parameters
9859 with store-func
9860 do (setq store-func (org-link-get-parameter (car link) :store))
9861 if store-func
9862 collect store-func))
9864 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9865 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9867 ;;;###autoload
9868 (defun org-store-link (arg)
9869 "\\<org-mode-map>Store an org-link to the current location.
9870 This link is added to `org-stored-links' and can later be inserted
9871 into an Org buffer with \\[org-insert-link].
9873 For some link types, a prefix ARG is interpreted.
9874 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9875 For file links, ARG negates `org-context-in-file-links'.
9877 A double prefix ARG force skipping storing functions that are not
9878 part of Org's core.
9880 A triple prefix ARG force storing a link for each line in the
9881 active region."
9882 (interactive "P")
9883 (org-load-modules-maybe)
9884 (if (and (equal arg '(64)) (org-region-active-p))
9885 (save-excursion
9886 (let ((end (region-end)))
9887 (goto-char (region-beginning))
9888 (set-mark (point))
9889 (while (< (point-at-eol) end)
9890 (move-end-of-line 1) (activate-mark)
9891 (let (current-prefix-arg)
9892 (call-interactively 'org-store-link))
9893 (move-beginning-of-line 2)
9894 (set-mark (point)))))
9895 (org-with-limited-levels
9896 (setq org-store-link-plist nil)
9897 (let (link cpltxt desc description search
9898 txt custom-id agenda-link sfuns sfunsn)
9899 (cond
9901 ;; Store a link using an external link type
9902 ((and (not (equal arg '(16)))
9903 (setq sfuns
9904 (delq
9905 nil (mapcar (lambda (f)
9906 (let (fs) (if (funcall f) (push f fs))))
9907 (org-store-link-functions)))
9908 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9909 (or (and (cdr sfuns)
9910 (funcall (intern
9911 (completing-read
9912 "Which function for creating the link? "
9913 sfunsn nil t (car sfunsn)))))
9914 (funcall (caar sfuns)))
9915 (setq link (plist-get org-store-link-plist :link)
9916 desc (or (plist-get org-store-link-plist
9917 :description)
9918 link))))
9920 ;; Store a link from a source code buffer.
9921 ((org-src-edit-buffer-p)
9922 (cond
9923 ((save-excursion
9924 (beginning-of-line)
9925 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9926 "[ \t]*$")))
9927 (setq link (format "(%s)" (match-string-no-properties 1))))
9928 ((called-interactively-p 'any)
9929 (let (label)
9930 (while (or (not label)
9931 (org-with-wide-buffer
9932 (goto-char (point-min))
9933 (re-search-forward
9934 (regexp-quote (format org-coderef-label-format label))
9935 nil t)))
9936 (when label (message "Label exists already") (sit-for 2))
9937 (setq label (read-string "Code line label: " label)))
9938 (end-of-line)
9939 (setq link (format org-coderef-label-format label))
9940 (let ((gc (- 79 (length link))))
9941 (if (< (current-column) gc) (org-move-to-column gc t)
9942 (insert " ")))
9943 (insert link)
9944 (setq link (concat "(" label ")") desc nil)))
9945 (t (setq link nil))))
9947 ;; We are in the agenda, link to referenced location
9948 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9949 (let ((m (or (get-text-property (point) 'org-hd-marker)
9950 (get-text-property (point) 'org-marker))))
9951 (when m
9952 (org-with-point-at m
9953 (setq agenda-link
9954 (if (called-interactively-p 'any)
9955 (call-interactively 'org-store-link)
9956 (org-store-link nil)))))))
9958 ((eq major-mode 'calendar-mode)
9959 (let ((cd (calendar-cursor-to-date)))
9960 (setq link
9961 (format-time-string
9962 (car org-time-stamp-formats)
9963 (apply 'encode-time
9964 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9965 nil nil nil))))
9966 (org-store-link-props :type "calendar" :date cd)))
9968 ((eq major-mode 'help-mode)
9969 (setq link (concat "help:" (save-excursion
9970 (goto-char (point-min))
9971 (looking-at "^[^ ]+")
9972 (match-string 0))))
9973 (org-store-link-props :type "help"))
9975 ((eq major-mode 'w3-mode)
9976 (setq cpltxt (if (and (buffer-name)
9977 (not (string-match "Untitled" (buffer-name))))
9978 (buffer-name)
9979 (url-view-url t))
9980 link (url-view-url t))
9981 (org-store-link-props :type "w3" :url (url-view-url t)))
9983 ((eq major-mode 'image-mode)
9984 (setq cpltxt (concat "file:"
9985 (abbreviate-file-name buffer-file-name))
9986 link cpltxt)
9987 (org-store-link-props :type "image" :file buffer-file-name))
9989 ;; In dired, store a link to the file of the current line
9990 ((derived-mode-p 'dired-mode)
9991 (let ((file (dired-get-filename nil t)))
9992 (setq file (if file
9993 (abbreviate-file-name
9994 (expand-file-name (dired-get-filename nil t)))
9995 ;; otherwise, no file so use current directory.
9996 default-directory))
9997 (setq cpltxt (concat "file:" file)
9998 link cpltxt)))
10000 ((setq search (run-hook-with-args-until-success
10001 'org-create-file-search-functions))
10002 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10003 "::" search))
10004 (setq cpltxt (or description link)))
10006 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10007 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10008 (cond
10009 ;; Store a link using the target at point
10010 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10011 (setq cpltxt
10012 (concat "file:"
10013 (abbreviate-file-name
10014 (buffer-file-name (buffer-base-buffer)))
10015 "::" (match-string 1))
10016 link cpltxt))
10017 ((and (featurep 'org-id)
10018 (or (eq org-id-link-to-org-use-id t)
10019 (and (called-interactively-p 'any)
10020 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10021 (and (eq org-id-link-to-org-use-id
10022 'create-if-interactive-and-no-custom-id)
10023 (not custom-id))))
10024 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10025 ;; Store a link using the ID at point
10026 (setq link (condition-case nil
10027 (prog1 (org-id-store-link)
10028 (setq desc (or (plist-get org-store-link-plist
10029 :description)
10030 "")))
10031 (error
10032 ;; Probably before first headline, link only to file
10033 (concat "file:"
10034 (abbreviate-file-name
10035 (buffer-file-name (buffer-base-buffer))))))))
10037 ;; Just link to current headline
10038 (setq cpltxt (concat "file:"
10039 (abbreviate-file-name
10040 (buffer-file-name (buffer-base-buffer)))))
10041 ;; Add a context search string
10042 (when (org-xor org-context-in-file-links arg)
10043 (let* ((element (org-element-at-point))
10044 (name (org-element-property :name element)))
10045 (setq txt (cond
10046 ((org-at-heading-p) nil)
10047 (name)
10048 ((org-region-active-p)
10049 (buffer-substring (region-beginning) (region-end)))))
10050 (when (or (null txt) (string-match "\\S-" txt))
10051 (setq cpltxt
10052 (concat cpltxt "::"
10053 (condition-case nil
10054 (org-make-org-heading-search-string txt)
10055 (error "")))
10056 desc (or name
10057 (nth 4 (ignore-errors (org-heading-components)))
10058 "NONE")))))
10059 (when (string-match "::\\'" cpltxt)
10060 (setq cpltxt (substring cpltxt 0 -2)))
10061 (setq link cpltxt))))
10063 ((buffer-file-name (buffer-base-buffer))
10064 ;; Just link to this file here.
10065 (setq cpltxt (concat "file:"
10066 (abbreviate-file-name
10067 (buffer-file-name (buffer-base-buffer)))))
10068 ;; Add a context string.
10069 (when (org-xor org-context-in-file-links arg)
10070 (setq txt (if (org-region-active-p)
10071 (buffer-substring (region-beginning) (region-end))
10072 (buffer-substring (point-at-bol) (point-at-eol))))
10073 ;; Only use search option if there is some text.
10074 (when (string-match "\\S-" txt)
10075 (setq cpltxt
10076 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10077 desc "NONE")))
10078 (setq link cpltxt))
10080 ((called-interactively-p 'interactive)
10081 (user-error "No method for storing a link from this buffer"))
10083 (t (setq link nil)))
10085 ;; We're done setting link and desc, clean up
10086 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10087 (setq link (or link cpltxt)
10088 desc (or desc cpltxt))
10089 (cond ((not desc))
10090 ((equal desc "NONE") (setq desc nil))
10091 (t (setq desc
10092 (replace-regexp-in-string
10093 org-bracket-link-analytic-regexp
10094 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10095 desc))))
10096 ;; Return the link
10097 (if (not (and (or (called-interactively-p 'any)
10098 executing-kbd-macro)
10099 link))
10100 (or agenda-link (and link (org-make-link-string link desc)))
10101 (push (list link desc) org-stored-links)
10102 (message "Stored: %s" (or desc link))
10103 (when custom-id
10104 (setq link (concat "file:" (abbreviate-file-name
10105 (buffer-file-name)) "::#" custom-id))
10106 (push (list link desc) org-stored-links))
10107 (car org-stored-links))))))
10109 (defun org-store-link-props (&rest plist)
10110 "Store link properties, extract names, addresses and dates."
10111 (let ((x (plist-get plist :from)))
10112 (when x
10113 (let ((adr (mail-extract-address-components x)))
10114 (setq plist (plist-put plist :fromname (car adr)))
10115 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10116 (let ((x (plist-get plist :to)))
10117 (when x
10118 (let ((adr (mail-extract-address-components x)))
10119 (setq plist (plist-put plist :toname (car adr)))
10120 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10121 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10122 (when x
10123 (setq plist (plist-put plist :date-timestamp
10124 (format-time-string
10125 (org-time-stamp-format t) x)))
10126 (setq plist (plist-put plist :date-timestamp-inactive
10127 (format-time-string
10128 (org-time-stamp-format t t) x)))))
10129 (let ((from (plist-get plist :from))
10130 (to (plist-get plist :to)))
10131 (when (and from to org-from-is-user-regexp)
10132 (setq plist
10133 (plist-put plist :fromto
10134 (if (string-match org-from-is-user-regexp from)
10135 (concat "to %t")
10136 (concat "from %f"))))))
10137 (setq org-store-link-plist plist))
10139 (defun org-add-link-props (&rest plist)
10140 "Add these properties to the link property list."
10141 (let (key value)
10142 (while plist
10143 (setq key (pop plist) value (pop plist))
10144 (setq org-store-link-plist
10145 (plist-put org-store-link-plist key value)))))
10147 (defun org-email-link-description (&optional fmt)
10148 "Return the description part of an email link.
10149 This takes information from `org-store-link-plist' and formats it
10150 according to FMT (default from `org-email-link-description-format')."
10151 (setq fmt (or fmt org-email-link-description-format))
10152 (let* ((p org-store-link-plist)
10153 (to (plist-get p :toaddress))
10154 (from (plist-get p :fromaddress))
10155 (table
10156 (list
10157 (cons "%c" (plist-get p :fromto))
10158 (cons "%F" (plist-get p :from))
10159 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10160 (cons "%T" (plist-get p :to))
10161 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10162 (cons "%s" (plist-get p :subject))
10163 (cons "%d" (plist-get p :date))
10164 (cons "%m" (plist-get p :message-id)))))
10165 (when (string-match "%c" fmt)
10166 ;; Check if the user wrote this message
10167 (if (and org-from-is-user-regexp from to
10168 (save-match-data (string-match org-from-is-user-regexp from)))
10169 (setq fmt (replace-match "to %t" t t fmt))
10170 (setq fmt (replace-match "from %f" t t fmt))))
10171 (org-replace-escapes fmt table)))
10173 (defun org-make-org-heading-search-string (&optional string)
10174 "Make search string for the current headline or STRING."
10175 (let ((s (or string
10176 (and (derived-mode-p 'org-mode)
10177 (save-excursion
10178 (org-back-to-heading t)
10179 (org-element-property :raw-value (org-element-at-point))))))
10180 (lines org-context-in-file-links))
10181 (or string (setq s (concat "*" s))) ; Add * for headlines
10182 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10183 (when (and string (integerp lines) (> lines 0))
10184 (let ((slines (org-split-string s "\n")))
10185 (when (< lines (length slines))
10186 (setq s (mapconcat
10187 'identity
10188 (reverse (nthcdr (- (length slines) lines)
10189 (reverse slines))) "\n")))))
10190 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10192 (defun org-make-link-string (link &optional description)
10193 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10194 (unless (org-string-nw-p link) (error "Empty link"))
10195 (let ((uri (cond ((string-match org-link-types-re link)
10196 (concat (match-string 1 link)
10197 (org-link-escape (substring link (match-end 1)))))
10198 ;; For readability, url-encode internal links only
10199 ;; when absolutely needed (i.e, when they contain
10200 ;; square brackets). File links however, are
10201 ;; encoded since, e.g., spaces are significant.
10202 ((or (file-name-absolute-p link)
10203 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10204 (org-link-escape link))
10205 (t link)))
10206 (description
10207 (and (org-string-nw-p description)
10208 ;; Remove brackets from description, as they are fatal.
10209 (replace-regexp-in-string
10210 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10211 (org-trim description)))))
10212 (format "[[%s]%s]"
10214 (if description (format "[%s]" description) ""))))
10216 (defconst org-link-escape-chars
10217 ;;%20 %5B %5D %25
10218 '(?\s ?\[ ?\] ?%)
10219 "List of characters that should be escaped in a link when stored to Org.
10220 This is the list that is used for internal purposes.")
10222 (defun org-link-escape (text &optional table merge)
10223 "Return percent escaped representation of TEXT.
10224 TEXT is a string with the text to escape.
10225 Optional argument TABLE is a list with characters that should be
10226 escaped. When nil, `org-link-escape-chars' is used.
10227 If optional argument MERGE is set, merge TABLE into
10228 `org-link-escape-chars'."
10229 (let ((characters-to-encode
10230 (cond ((null table) org-link-escape-chars)
10231 (merge (append org-link-escape-chars table))
10232 (t table))))
10233 (mapconcat
10234 (lambda (c)
10235 (if (or (memq c characters-to-encode)
10236 (and org-url-hexify-p (or (< c 32) (> c 126))))
10237 (mapconcat (lambda (e) (format "%%%.2X" e))
10238 (or (encode-coding-char c 'utf-8)
10239 (error "Unable to percent escape character: %c" c))
10241 (char-to-string c)))
10242 text "")))
10244 (defun org-link-unescape (str)
10245 "Unhex hexified Unicode parts in string STR.
10246 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10247 reciprocal of `org-link-escape', which see."
10248 (if (org-string-nw-p str)
10249 (replace-regexp-in-string
10250 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10251 str))
10253 (defun org-link-unescape-compound (hex)
10254 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10255 Note: this function also decodes single byte encodings like
10256 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10257 (save-match-data
10258 (let* ((bytes (cdr (split-string hex "%")))
10259 (ret "")
10260 (eat 0)
10261 (sum 0))
10262 (while bytes
10263 (let* ((val (string-to-number (pop bytes) 16))
10264 (shift-xor
10265 (if (= 0 eat)
10266 (cond
10267 ((>= val 252) (cons 6 252))
10268 ((>= val 248) (cons 5 248))
10269 ((>= val 240) (cons 4 240))
10270 ((>= val 224) (cons 3 224))
10271 ((>= val 192) (cons 2 192))
10272 (t (cons 0 0)))
10273 (cons 6 128))))
10274 (when (>= val 192) (setq eat (car shift-xor)))
10275 (setq val (logxor val (cdr shift-xor)))
10276 (setq sum (+ (lsh sum (car shift-xor)) val))
10277 (when (> eat 0) (setq eat (- eat 1)))
10278 (cond
10279 ((= 0 eat) ;multi byte
10280 (setq ret (concat ret (char-to-string sum)))
10281 (setq sum 0))
10282 ((not bytes) ; single byte(s)
10283 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10284 ret)))
10286 (defun org-link-unescape-single-byte-sequence (hex)
10287 "Unhexify hex-encoded single byte character sequences."
10288 (mapconcat (lambda (byte)
10289 (char-to-string (string-to-number byte 16)))
10290 (cdr (split-string hex "%")) ""))
10292 (defun org-xor (a b)
10293 "Exclusive or."
10294 (if a (not b) b))
10296 (defun org-fixup-message-id-for-http (s)
10297 "Replace special characters in a message id, so it can be used in an http query."
10298 (when (string-match "%" s)
10299 (setq s (mapconcat (lambda (c)
10300 (if (eq c ?%)
10301 "%25"
10302 (char-to-string c)))
10303 s "")))
10304 (while (string-match "<" s)
10305 (setq s (replace-match "%3C" t t s)))
10306 (while (string-match ">" s)
10307 (setq s (replace-match "%3E" t t s)))
10308 (while (string-match "@" s)
10309 (setq s (replace-match "%40" t t s)))
10312 (defun org-link-prettify (link)
10313 "Return a human-readable representation of LINK.
10314 The car of LINK must be a raw link.
10315 The cdr of LINK must be either a link description or nil."
10316 (let ((desc (or (cadr link) "<no description>")))
10317 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10318 "<" (car link) ">")))
10320 ;;;###autoload
10321 (defun org-insert-link-global ()
10322 "Insert a link like Org-mode does.
10323 This command can be called in any mode to insert a link in Org-mode syntax."
10324 (interactive)
10325 (org-load-modules-maybe)
10326 (org-run-like-in-org-mode 'org-insert-link))
10328 (defun org-insert-all-links (arg &optional pre post)
10329 "Insert all links in `org-stored-links'.
10330 When a universal prefix, do not delete the links from `org-stored-links'.
10331 When `ARG' is a number, insert the last N link(s).
10332 `PRE' and `POST' are optional arguments to define a string to
10333 prepend or to append."
10334 (interactive "P")
10335 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10336 (links (copy-sequence org-stored-links))
10337 (pr (or pre "- "))
10338 (po (or post "\n"))
10339 (cnt 1) l)
10340 (if (null org-stored-links)
10341 (message "No link to insert")
10342 (while (and (or (listp arg) (>= arg cnt))
10343 (setq l (if (listp arg)
10344 (pop links)
10345 (pop org-stored-links))))
10346 (setq cnt (1+ cnt))
10347 (insert pr)
10348 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10349 (insert po)))))
10351 (defun org-insert-last-stored-link (arg)
10352 "Insert the last link stored in `org-stored-links'."
10353 (interactive "p")
10354 (org-insert-all-links arg "" "\n"))
10356 (defun org-link-fontify-links-to-this-file ()
10357 "Fontify links to the current file in `org-stored-links'."
10358 (let ((f (buffer-file-name)) a b)
10359 (setq a (mapcar (lambda(l)
10360 (let ((ll (car l)))
10361 (when (and (string-match "^file:\\(.+\\)::" ll)
10362 (equal f (expand-file-name (match-string 1 ll))))
10363 ll)))
10364 org-stored-links))
10365 (when (featurep 'org-id)
10366 (setq b (mapcar (lambda(l)
10367 (let ((ll (car l)))
10368 (when (and (string-match "^id:\\(.+\\)$" ll)
10369 (equal f (expand-file-name
10370 (or (org-id-find-id-file
10371 (match-string 1 ll)) ""))))
10372 ll)))
10373 org-stored-links)))
10374 (mapcar (lambda(l)
10375 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10376 (delq nil (append a b)))))
10378 (defvar org--links-history nil)
10379 (defun org-insert-link (&optional complete-file link-location default-description)
10380 "Insert a link. At the prompt, enter the link.
10382 Completion can be used to insert any of the link protocol prefixes like
10383 http or ftp in use.
10385 The history can be used to select a link previously stored with
10386 `org-store-link'. When the empty string is entered (i.e. if you just
10387 press RET at the prompt), the link defaults to the most recently
10388 stored link. As SPC triggers completion in the minibuffer, you need to
10389 use M-SPC or C-q SPC to force the insertion of a space character.
10391 You will also be prompted for a description, and if one is given, it will
10392 be displayed in the buffer instead of the link.
10394 If there is already a link at point, this command will allow you to edit link
10395 and description parts.
10397 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10398 be selected using completion. The path to the file will be relative to the
10399 current directory if the file is in the current directory or a subdirectory.
10400 Otherwise, the link will be the absolute path as completed in the minibuffer
10401 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10402 option `org-link-file-path-type'.
10404 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10405 the current directory or below.
10407 With three \\[universal-argument] prefixes, negate the meaning of
10408 `org-keep-stored-link-after-insertion'.
10410 If `org-make-link-description-function' is non-nil, this function will be
10411 called with the link target, and the result will be the default
10412 link description.
10414 If the LINK-LOCATION parameter is non-nil, this value will be
10415 used as the link location instead of reading one interactively.
10417 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10418 be used as the default description."
10419 (interactive "P")
10420 (let* ((wcf (current-window-configuration))
10421 (origbuf (current-buffer))
10422 (region (when (org-region-active-p)
10423 (buffer-substring (region-beginning) (region-end))))
10424 (remove (and region (list (region-beginning) (region-end))))
10425 (desc region)
10426 (link link-location)
10427 (abbrevs org-link-abbrev-alist-local)
10428 entry all-prefixes auto-desc)
10429 (cond
10430 (link-location) ; specified by arg, just use it.
10431 ((org-in-regexp org-bracket-link-regexp 1)
10432 ;; We do have a link at point, and we are going to edit it.
10433 (setq remove (list (match-beginning 0) (match-end 0)))
10434 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10435 (setq link (read-string "Link: "
10436 (org-link-unescape
10437 (match-string-no-properties 1)))))
10438 ((or (org-in-regexp org-angle-link-re)
10439 (org-in-regexp org-plain-link-re))
10440 ;; Convert to bracket link
10441 (setq remove (list (match-beginning 0) (match-end 0))
10442 link (read-string "Link: "
10443 (org-remove-angle-brackets (match-string 0)))))
10444 ((member complete-file '((4) (16)))
10445 ;; Completing read for file names.
10446 (setq link (org-file-complete-link complete-file)))
10448 ;; Read link, with completion for stored links.
10449 (org-link-fontify-links-to-this-file)
10450 (org-switch-to-buffer-other-window "*Org Links*")
10451 (with-current-buffer "*Org Links*"
10452 (erase-buffer)
10453 (insert "Insert a link.
10454 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10455 (when org-stored-links
10456 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10457 (insert (mapconcat 'org-link-prettify
10458 (reverse org-stored-links) "\n")))
10459 (goto-char (point-min)))
10460 (let ((cw (selected-window)))
10461 (select-window (get-buffer-window "*Org Links*" 'visible))
10462 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10463 (unless (pos-visible-in-window-p (point-max))
10464 (org-fit-window-to-buffer))
10465 (and (window-live-p cw) (select-window cw)))
10466 (setq all-prefixes (append (mapcar 'car abbrevs)
10467 (mapcar 'car org-link-abbrev-alist)
10468 (org-link-types)))
10469 (unwind-protect
10470 ;; Fake a link history, containing the stored links.
10471 (let ((org--links-history
10472 (append (mapcar #'car org-stored-links)
10473 org-insert-link-history)))
10474 (setq link
10475 (org-completing-read
10476 "Link: "
10477 (append
10478 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10479 (mapcar #'car org-stored-links))
10480 nil nil nil
10481 'org--links-history
10482 (caar org-stored-links)))
10483 (unless (org-string-nw-p link) (user-error "No link selected"))
10484 (dolist (l org-stored-links)
10485 (when (equal link (cadr l))
10486 (setq link (car l))
10487 (setq auto-desc t)))
10488 (when (or (member link all-prefixes)
10489 (and (equal ":" (substring link -1))
10490 (member (substring link 0 -1) all-prefixes)
10491 (setq link (substring link 0 -1))))
10492 (setq link (with-current-buffer origbuf
10493 (org-link-try-special-completion link)))))
10494 (set-window-configuration wcf)
10495 (kill-buffer "*Org Links*"))
10496 (setq entry (assoc link org-stored-links))
10497 (or entry (push link org-insert-link-history))
10498 (setq desc (or desc (nth 1 entry)))))
10500 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10501 (not org-keep-stored-link-after-insertion))
10502 (setq org-stored-links (delq (assoc link org-stored-links)
10503 org-stored-links)))
10505 (when (and (string-match org-plain-link-re link)
10506 (not (string-match org-ts-regexp link)))
10507 ;; URL-like link, normalize the use of angular brackets.
10508 (setq link (org-remove-angle-brackets link)))
10510 ;; Check if we are linking to the current file with a search
10511 ;; option If yes, simplify the link by using only the search
10512 ;; option.
10513 (when (and buffer-file-name
10514 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10515 (let* ((path (match-string 1 link))
10516 (case-fold-search nil)
10517 (search (match-string 2 link)))
10518 (save-match-data
10519 (when (equal (file-truename buffer-file-name) (file-truename path))
10520 ;; We are linking to this same file, with a search option
10521 (setq link search)))))
10523 ;; Check if we can/should use a relative path. If yes, simplify the link
10524 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10525 (let* ((type (match-string 1 link))
10526 (path (match-string 2 link))
10527 (origpath path)
10528 (case-fold-search nil))
10529 (cond
10530 ((or (eq org-link-file-path-type 'absolute)
10531 (equal complete-file '(16)))
10532 (setq path (abbreviate-file-name (expand-file-name path))))
10533 ((eq org-link-file-path-type 'noabbrev)
10534 (setq path (expand-file-name path)))
10535 ((eq org-link-file-path-type 'relative)
10536 (setq path (file-relative-name path)))
10538 (save-match-data
10539 (if (string-match (concat "^" (regexp-quote
10540 (expand-file-name
10541 (file-name-as-directory
10542 default-directory))))
10543 (expand-file-name path))
10544 ;; We are linking a file with relative path name.
10545 (setq path (substring (expand-file-name path)
10546 (match-end 0)))
10547 (setq path (abbreviate-file-name (expand-file-name path)))))))
10548 (setq link (concat type path))
10549 (when (equal desc origpath)
10550 (setq desc path))))
10552 (if org-make-link-description-function
10553 (setq desc
10554 (or (condition-case nil
10555 (funcall org-make-link-description-function link desc)
10556 (error (progn (message "Can't get link description from `%s'"
10557 (symbol-name org-make-link-description-function))
10558 (sit-for 2) nil)))
10559 (read-string "Description: " default-description)))
10560 (if default-description (setq desc default-description)
10561 (setq desc (or (and auto-desc desc)
10562 (read-string "Description: " desc)))))
10564 (unless (string-match "\\S-" desc) (setq desc nil))
10565 (when remove (apply 'delete-region remove))
10566 (insert (org-make-link-string link desc))
10567 ;; Redisplay so as the new link has proper invisible characters.
10568 (sit-for 0)))
10570 (defun org-link-try-special-completion (type)
10571 "If there is completion support for link type TYPE, offer it."
10572 (let ((fun (org-link-get-parameter type :complete)))
10573 (if (functionp fun)
10574 (funcall fun)
10575 (read-string "Link (no completion support): " (concat type ":")))))
10577 (defun org-file-complete-link (&optional arg)
10578 "Create a file link using completion."
10579 (let ((file (read-file-name "File: "))
10580 (pwd (file-name-as-directory (expand-file-name ".")))
10581 (pwd1 (file-name-as-directory (abbreviate-file-name
10582 (expand-file-name ".")))))
10583 (cond ((equal arg '(16))
10584 (concat "file:"
10585 (abbreviate-file-name (expand-file-name file))))
10586 ((string-match
10587 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10588 (concat "file:" (match-string 1 file)))
10589 ((string-match
10590 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10591 (expand-file-name file))
10592 (concat "file:"
10593 (match-string 1 (expand-file-name file))))
10594 (t (concat "file:" file)))))
10596 (defun org-completing-read (&rest args)
10597 "Completing-read with SPACE being a normal character."
10598 (let ((enable-recursive-minibuffers t)
10599 (minibuffer-local-completion-map
10600 (copy-keymap minibuffer-local-completion-map)))
10601 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10602 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10603 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10604 'org-time-stamp-inactive)
10605 (apply #'completing-read args)))
10607 ;;; Opening/following a link
10609 (defvar org-link-search-failed nil)
10611 (defvar org-open-link-functions nil
10612 "Hook for functions finding a plain text link.
10613 These functions must take a single argument, the link content.
10614 They will be called for links that look like [[link text][description]]
10615 when LINK TEXT does not have a protocol like \"http:\" and does not look
10616 like a filename (e.g. \"./blue.png\").
10618 These functions will be called *before* Org attempts to resolve the
10619 link by doing text searches in the current buffer - so if you want a
10620 link \"[[target]]\" to still find \"<<target>>\", your function should
10621 handle this as a special case.
10623 When the function does handle the link, it must return a non-nil value.
10624 If it decides that it is not responsible for this link, it must return
10625 nil to indicate that that Org-mode can continue with other options
10626 like exact and fuzzy text search.")
10628 (defun org-next-link (&optional search-backward)
10629 "Move forward to the next link.
10630 If the link is in hidden text, expose it."
10631 (interactive "P")
10632 (when (and org-link-search-failed (eq this-command last-command))
10633 (goto-char (point-min))
10634 (message "Link search wrapped back to beginning of buffer"))
10635 (setq org-link-search-failed nil)
10636 (let* ((pos (point))
10637 (ct (org-context))
10638 (a (assoc :link ct))
10639 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10640 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10641 ((looking-at org-any-link-re)
10642 ;; Don't stay stuck at link without an org-link face
10643 (forward-char (if search-backward -1 1))))
10644 (if (funcall srch-fun org-any-link-re nil t)
10645 (progn
10646 (goto-char (match-beginning 0))
10647 (when (outline-invisible-p) (org-show-context)))
10648 (goto-char pos)
10649 (setq org-link-search-failed t)
10650 (message "No further link found"))))
10652 (defun org-previous-link ()
10653 "Move backward to the previous link.
10654 If the link is in hidden text, expose it."
10655 (interactive)
10656 (funcall 'org-next-link t))
10658 (defun org-translate-link (s)
10659 "Translate a link string if a translation function has been defined."
10660 (with-temp-buffer
10661 (insert (org-trim s))
10662 (org-trim (org-element-interpret-data (org-element-context)))))
10664 (defun org-translate-link-from-planner (type path)
10665 "Translate a link from Emacs Planner syntax so that Org can follow it.
10666 This is still an experimental function, your mileage may vary."
10667 (cond
10668 ((member type '("http" "https" "news" "ftp"))
10669 ;; standard Internet links are the same.
10670 nil)
10671 ((and (equal type "irc") (string-match "^//" path))
10672 ;; Planner has two / at the beginning of an irc link, we have 1.
10673 ;; We should have zero, actually....
10674 (setq path (substring path 1)))
10675 ((and (equal type "lisp") (string-match "^/" path))
10676 ;; Planner has a slash, we do not.
10677 (setq type "elisp" path (substring path 1)))
10678 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10679 ;; A typical message link. Planner has the id after the final slash,
10680 ;; we separate it with a hash mark
10681 (setq path (concat (match-string 1 path) "#"
10682 (org-remove-angle-brackets (match-string 2 path))))))
10683 (cons type path))
10685 (defun org-find-file-at-mouse (ev)
10686 "Open file link or URL at mouse."
10687 (interactive "e")
10688 (mouse-set-point ev)
10689 (org-open-at-point 'in-emacs))
10691 (defun org-open-at-mouse (ev)
10692 "Open file link or URL at mouse.
10693 See the docstring of `org-open-file' for details."
10694 (interactive "e")
10695 (mouse-set-point ev)
10696 (when (eq major-mode 'org-agenda-mode)
10697 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10698 (org-open-at-point))
10700 (defvar org-window-config-before-follow-link nil
10701 "The window configuration before following a link.
10702 This is saved in case the need arises to restore it.")
10704 ;;;###autoload
10705 (defun org-open-at-point-global ()
10706 "Follow a link or time-stamp like Org mode does.
10707 This command can be called in any mode to follow an external link
10708 or a time-stamp that has Org mode syntax. Its behavior is
10709 undefined when called on internal links (e.g., fuzzy links).
10710 Raise an error when there is nothing to follow. "
10711 (interactive)
10712 (cond ((org-in-regexp org-any-link-re)
10713 (org-open-link-from-string (match-string-no-properties 0)))
10714 ((or (org-in-regexp org-ts-regexp-both nil t)
10715 (org-in-regexp org-tsr-regexp-both nil t))
10716 (org-follow-timestamp-link))
10717 (t (user-error "No link found"))))
10719 ;;;###autoload
10720 (defun org-open-link-from-string (s &optional arg reference-buffer)
10721 "Open a link in the string S, as if it was in Org-mode."
10722 (interactive "sLink: \nP")
10723 (let ((reference-buffer (or reference-buffer (current-buffer))))
10724 (with-temp-buffer
10725 (let ((org-inhibit-startup (not reference-buffer)))
10726 (org-mode)
10727 (insert s)
10728 (goto-char (point-min))
10729 (when reference-buffer
10730 (setq org-link-abbrev-alist-local
10731 (with-current-buffer reference-buffer
10732 org-link-abbrev-alist-local)))
10733 (org-open-at-point arg reference-buffer)))))
10735 (defvar org-open-at-point-functions nil
10736 "Hook that is run when following a link at point.
10738 Functions in this hook must return t if they identify and follow
10739 a link at point. If they don't find anything interesting at point,
10740 they must return nil.")
10742 (defvar org-link-search-inhibit-query nil)
10743 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10744 (defun org--open-doi-link (path)
10745 "Open a \"doi\" type link.
10746 PATH is a the path to search for, as a string."
10747 (browse-url (url-encode-url (concat org-doi-server-url path))))
10749 (defun org--open-elisp-link (path)
10750 "Open a \"elisp\" type link.
10751 PATH is the sexp to evaluate, as a string."
10752 (let ((cmd path))
10753 (if (or (and (org-string-nw-p
10754 org-confirm-elisp-link-not-regexp)
10755 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10756 (not org-confirm-elisp-link-function)
10757 (funcall org-confirm-elisp-link-function
10758 (format "Execute \"%s\" as elisp? "
10759 (org-add-props cmd nil 'face 'org-warning))))
10760 (message "%s => %s" cmd
10761 (if (eq (string-to-char cmd) ?\()
10762 (eval (read cmd))
10763 (call-interactively (read cmd))))
10764 (user-error "Abort"))))
10766 (defun org--open-help-link (path)
10767 "Open a \"help\" type link.
10768 PATH is a symbol name, as a string."
10769 (pcase (intern path)
10770 ((and (pred fboundp) variable) (describe-function variable))
10771 ((and (pred boundp) function) (describe-variable function))
10772 (name (user-error "Unknown function or variable: %s" name))))
10774 (defun org--open-shell-link (path)
10775 "Open a \"shell\" type link.
10776 PATH is the command to execute, as a string."
10777 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10778 (cmd path))
10779 (if (or (and (org-string-nw-p
10780 org-confirm-shell-link-not-regexp)
10781 (string-match
10782 org-confirm-shell-link-not-regexp cmd))
10783 (not org-confirm-shell-link-function)
10784 (funcall org-confirm-shell-link-function
10785 (format "Execute \"%s\" in shell? "
10786 (org-add-props cmd nil
10787 'face 'org-warning))))
10788 (progn
10789 (message "Executing %s" cmd)
10790 (shell-command cmd buf)
10791 (when (featurep 'midnight)
10792 (setq clean-buffer-list-kill-buffer-names
10793 (cons (buffer-name buf)
10794 clean-buffer-list-kill-buffer-names))))
10795 (user-error "Abort"))))
10797 (defun org-open-at-point (&optional arg reference-buffer)
10798 "Open link, timestamp, footnote or tags at point.
10800 When point is on a link, follow it. Normally, files will be
10801 opened by an appropriate application. If the optional prefix
10802 argument ARG is non-nil, Emacs will visit the file. With
10803 a double prefix argument, try to open outside of Emacs, in the
10804 application the system uses for this file type.
10806 When point is on a timestamp, open the agenda at the day
10807 specified.
10809 When point is a footnote definition, move to the first reference
10810 found. If it is on a reference, move to the associated
10811 definition.
10813 When point is on a headline, display a list of every link in the
10814 entry, so it is possible to pick one, or all, of them. If point
10815 is on a tag, call `org-tags-view' instead.
10817 When optional argument REFERENCE-BUFFER is non-nil, it should
10818 specify a buffer from where the link search should happen. This
10819 is used internally by `org-open-link-from-string'.
10821 On top of syntactically correct links, this function will open
10822 the link at point in comments or comment blocks and the first
10823 link in a property drawer line."
10824 (interactive "P")
10825 ;; On a code block, open block's results.
10826 (unless (call-interactively 'org-babel-open-src-block-result)
10827 (org-load-modules-maybe)
10828 (setq org-window-config-before-follow-link (current-window-configuration))
10829 (org-remove-occur-highlights nil nil t)
10830 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10831 (let* ((context
10832 ;; Only consider supported types, even if they are not
10833 ;; the closest one.
10834 (org-element-lineage
10835 (org-element-context)
10836 '(clock comment comment-block footnote-definition
10837 footnote-reference headline inlinetask keyword link
10838 node-property timestamp)
10840 (type (org-element-type context))
10841 (value (org-element-property :value context)))
10842 (cond
10843 ((not context) (user-error "No link found"))
10844 ;; Exception: open timestamps and links in properties
10845 ;; drawers, keywords and comments.
10846 ((memq type '(comment comment-block keyword node-property))
10847 (call-interactively #'org-open-at-point-global))
10848 ;; On a headline or an inlinetask, but not on a timestamp,
10849 ;; a link, a footnote reference or on tags.
10850 ((and (memq type '(headline inlinetask))
10851 ;; Not on tags.
10852 (progn (save-excursion (beginning-of-line)
10853 (looking-at org-complex-heading-regexp))
10854 (or (not (match-beginning 5))
10855 (< (point) (match-beginning 5)))))
10856 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10857 (links (car data))
10858 (links-end (cdr data)))
10859 (if links
10860 (dolist (link (if (stringp links) (list links) links))
10861 (search-forward link nil links-end)
10862 (goto-char (match-beginning 0))
10863 (org-open-at-point))
10864 (require 'org-attach)
10865 (org-attach-reveal 'if-exists))))
10866 ;; On a clock line, make sure point is on the timestamp
10867 ;; before opening it.
10868 ((and (eq type 'clock)
10869 value
10870 (>= (point) (org-element-property :begin value))
10871 (<= (point) (org-element-property :end value)))
10872 (org-follow-timestamp-link))
10873 ;; Do nothing on white spaces after an object.
10874 ((>= (point)
10875 (save-excursion
10876 (goto-char (org-element-property :end context))
10877 (skip-chars-backward " \t")
10878 (point)))
10879 (user-error "No link found"))
10880 ((eq type 'timestamp) (org-follow-timestamp-link))
10881 ;; On tags within a headline or an inlinetask.
10882 ((and (memq type '(headline inlinetask))
10883 (progn (save-excursion (beginning-of-line)
10884 (looking-at org-complex-heading-regexp))
10885 (and (match-beginning 5)
10886 (>= (point) (match-beginning 5)))))
10887 (org-tags-view arg (substring (match-string 5) 0 -1)))
10888 ((eq type 'link)
10889 ;; When link is located within the description of another
10890 ;; link (e.g., an inline image), always open the parent
10891 ;; link.
10892 (let* ((link (let ((up (org-element-property :parent context)))
10893 (if (eq (org-element-type up) 'link) up context)))
10894 (type (org-element-property :type link))
10895 (path (org-link-unescape (org-element-property :path link))))
10896 ;; Switch back to REFERENCE-BUFFER needed when called in
10897 ;; a temporary buffer through `org-open-link-from-string'.
10898 (with-current-buffer (or reference-buffer (current-buffer))
10899 (cond
10900 ((equal type "file")
10901 (if (string-match "[*?{]" (file-name-nondirectory path))
10902 (dired path)
10903 ;; Look into `org-link-parameters' in order to find
10904 ;; a DEDICATED-FUNCTION to open file. The function
10905 ;; will be applied on raw link instead of parsed
10906 ;; link due to the limitation in `org-add-link-type'
10907 ;; ("open" function called with a single argument).
10908 ;; If no such function is found, fallback to
10909 ;; `org-open-file'.
10910 (let* ((option (org-element-property :search-option link))
10911 (app (org-element-property :application link))
10912 (dedicated-function
10913 (org-link-get-parameter
10914 (if app (concat type "+" app) type)
10915 :follow)))
10916 (if dedicated-function
10917 (funcall dedicated-function
10918 (concat path
10919 (and option (concat "::" option))))
10920 (apply #'org-open-file
10921 path
10922 (cond (arg)
10923 ((equal app "emacs") 'emacs)
10924 ((equal app "sys") 'system))
10925 (cond ((not option) nil)
10926 ((string-match-p "\\`[0-9]+\\'" option)
10927 (list (string-to-number option)))
10928 (t (list nil
10929 (org-link-unescape option)))))))))
10930 ((functionp (org-link-get-parameter type :follow))
10931 (funcall (org-link-get-parameter type :follow) path))
10932 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10933 (unless (run-hook-with-args-until-success
10934 'org-open-link-functions path)
10935 (if (not arg) (org-mark-ring-push)
10936 (switch-to-buffer-other-window
10937 (org-get-buffer-for-internal-link (current-buffer))))
10938 (let ((destination
10939 (org-with-wide-buffer
10940 (if (equal type "radio")
10941 (org-search-radio-target
10942 (org-element-property :path link))
10943 (org-link-search
10944 (if (member type '("custom-id" "coderef"))
10945 (org-element-property :raw-link link)
10946 path)
10947 ;; Prevent fuzzy links from matching
10948 ;; themselves.
10949 (and (equal type "fuzzy")
10950 (+ 2 (org-element-property :begin link)))))
10951 (point))))
10952 (unless (and (<= (point-min) destination)
10953 (>= (point-max) destination))
10954 (widen))
10955 (goto-char destination))))
10956 (t (browse-url-at-point))))))
10957 ;; On a footnote reference or at a footnote definition's label.
10958 ((or (eq type 'footnote-reference)
10959 (and (eq type 'footnote-definition)
10960 (save-excursion
10961 ;; Do not validate action when point is on the
10962 ;; spaces right after the footnote label, in
10963 ;; order to be on par with behaviour on links.
10964 (skip-chars-forward " \t")
10965 (let ((begin
10966 (org-element-property :contents-begin context)))
10967 (if begin (< (point) begin)
10968 (= (org-element-property :post-affiliated context)
10969 (line-beginning-position)))))))
10970 (org-footnote-action))
10971 (t (user-error "No link found")))))
10972 (run-hook-with-args 'org-follow-link-hook)))
10974 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10975 "Offer links in the current entry and return the selected link.
10976 If there is only one link, return it.
10977 If NTH is an integer, return the NTH link found.
10978 If ZERO is a string, check also this string for a link, and if
10979 there is one, return it."
10980 (with-current-buffer buffer
10981 (save-excursion
10982 (save-restriction
10983 (widen)
10984 (goto-char marker)
10985 (let ((cnt ?0)
10986 have-zero end links link c)
10987 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10988 (push (match-string 0 zero) links)
10989 (setq cnt (1- cnt) have-zero t))
10990 (save-excursion
10991 (org-back-to-heading t)
10992 (setq end (save-excursion (outline-next-heading) (point)))
10993 (while (re-search-forward org-any-link-re end t)
10994 (push (match-string 0) links))
10995 (setq links (org-uniquify (reverse links))))
10996 (cond
10997 ((null links)
10998 (message "No links"))
10999 ((equal (length links) 1)
11000 (setq link (car links)))
11001 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11002 (setq link (nth (if have-zero nth (1- nth)) links)))
11003 (t ; we have to select a link
11004 (save-excursion
11005 (save-window-excursion
11006 (delete-other-windows)
11007 (with-output-to-temp-buffer "*Select Link*"
11008 (dolist (l links)
11009 (cond
11010 ((not (string-match org-bracket-link-regexp l))
11011 (princ (format "[%c] %s\n" (cl-incf cnt)
11012 (org-remove-angle-brackets l))))
11013 ((match-end 3)
11014 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11015 (match-string 3 l) (match-string 1 l))))
11016 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11017 (match-string 1 l)))))))
11018 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11019 (message "Select link to open, RET to open all:")
11020 (setq c (read-char-exclusive))
11021 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11022 (when (equal c ?q) (user-error "Abort"))
11023 (if (equal c ?\C-m)
11024 (setq link links)
11025 (setq nth (- c ?0))
11026 (when have-zero (setq nth (1+ nth)))
11027 (unless (and (integerp nth) (>= (length links) nth))
11028 (user-error "Invalid link selection"))
11029 (setq link (nth (1- nth) links)))))
11030 (cons link end))))))
11032 ;; TODO: These functions are deprecated since `org-open-at-point'
11033 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11034 (defun org-open-file-with-system (path)
11035 "Open file at PATH using the system way of opening it."
11036 (org-open-file path 'system))
11037 (defun org-open-file-with-emacs (path)
11038 "Open file at PATH in Emacs."
11039 (org-open-file path 'emacs))
11042 ;;; File search
11044 (defvar org-create-file-search-functions nil
11045 "List of functions to construct the right search string for a file link.
11046 These functions are called in turn with point at the location to
11047 which the link should point.
11049 A function in the hook should first test if it would like to
11050 handle this file type, for example by checking the `major-mode'
11051 or the file extension. If it decides not to handle this file, it
11052 should just return nil to give other functions a chance. If it
11053 does handle the file, it must return the search string to be used
11054 when following the link. The search string will be part of the
11055 file link, given after a double colon, and `org-open-at-point'
11056 will automatically search for it. If special measures must be
11057 taken to make the search successful, another function should be
11058 added to the companion hook `org-execute-file-search-functions',
11059 which see.
11061 A function in this hook may also use `setq' to set the variable
11062 `description' to provide a suggestion for the descriptive text to
11063 be used for this link when it gets inserted into an Org-mode
11064 buffer with \\[org-insert-link].")
11066 (defvar org-execute-file-search-functions nil
11067 "List of functions to execute a file search triggered by a link.
11069 Functions added to this hook must accept a single argument, the
11070 search string that was part of the file link, the part after the
11071 double colon. The function must first check if it would like to
11072 handle this search, for example by checking the `major-mode' or
11073 the file extension. If it decides not to handle this search, it
11074 should just return nil to give other functions a chance. If it
11075 does handle the search, it must return a non-nil value to keep
11076 other functions from trying.
11078 Each function can access the current prefix argument through the
11079 variable `current-prefix-arg'. Note that a single prefix is used
11080 to force opening a link in Emacs, so it may be good to only use a
11081 numeric or double prefix to guide the search function.
11083 In case this is needed, a function in this hook can also restore
11084 the window configuration before `org-open-at-point' was called using:
11086 \(set-window-configuration org-window-config-before-follow-link)")
11088 (defun org-search-radio-target (target)
11089 "Search a radio target matching TARGET in current buffer.
11090 White spaces are not significant."
11091 (let ((re (format "<<<%s>>>"
11092 (mapconcat #'regexp-quote
11093 (org-split-string target "[ \t\n]+")
11094 "[ \t]+\\(?:\n[ \t]*\\)?")))
11095 (origin (point)))
11096 (goto-char (point-min))
11097 (catch :radio-match
11098 (while (re-search-forward re nil t)
11099 (backward-char)
11100 (let ((object (org-element-context)))
11101 (when (eq (org-element-type object) 'radio-target)
11102 (goto-char (org-element-property :begin object))
11103 (org-show-context 'link-search)
11104 (throw :radio-match nil))))
11105 (goto-char origin)
11106 (user-error "No match for radio target: %s" target))))
11108 (defun org-link-search (s &optional avoid-pos stealth)
11109 "Search for a search string S.
11111 If S starts with \"#\", it triggers a custom ID search.
11113 If S is enclosed within parenthesis, it initiates a coderef
11114 search.
11116 If S is surrounded by forward slashes, it is interpreted as
11117 a regular expression. In Org mode files, this will create an
11118 `org-occur' sparse tree. In ordinary files, `occur' will be used
11119 to list matches. If the current buffer is in `dired-mode', grep
11120 will be used to search in all files.
11122 When AVOID-POS is given, ignore matches near that position.
11124 When optional argument STEALTH is non-nil, do not modify
11125 visibility around point, thus ignoring `org-show-context-detail'
11126 variable.
11128 Search is case-insensitive and ignores white spaces. Return type
11129 of matched result, with is either `dedicated' or `fuzzy'."
11130 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11131 (let* ((case-fold-search t)
11132 (origin (point))
11133 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11134 (words (org-split-string s "[ \t\n]+"))
11135 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11136 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11137 type)
11138 (cond
11139 ;; Check if there are any special search functions.
11140 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11141 ((eq (string-to-char s) ?#)
11142 ;; Look for a custom ID S if S starts with "#".
11143 (let* ((id (substring normalized 1))
11144 (match (org-find-property "CUSTOM_ID" id)))
11145 (if match (progn (goto-char match) (setf type 'dedicated))
11146 (error "No match for custom ID: %s" id))))
11147 ((string-match "\\`(\\(.*\\))\\'" normalized)
11148 ;; Look for coderef targets if S is enclosed within parenthesis.
11149 (let ((coderef (match-string-no-properties 1 normalized))
11150 (re (substring s-single-re 1 -1)))
11151 (goto-char (point-min))
11152 (catch :coderef-match
11153 (while (re-search-forward re nil t)
11154 (let ((element (org-element-at-point)))
11155 (when (and (memq (org-element-type element)
11156 '(example-block src-block))
11157 ;; Build proper regexp according to current
11158 ;; block's label format.
11159 (let ((label-fmt
11160 (regexp-quote
11161 (or (org-element-property :label-fmt element)
11162 org-coderef-label-format))))
11163 (save-excursion
11164 (beginning-of-line)
11165 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11166 (format label-fmt coderef))))))
11167 (setq type 'dedicated)
11168 (goto-char (match-beginning 1))
11169 (throw :coderef-match nil))))
11170 (goto-char origin)
11171 (error "No match for coderef: %s" coderef))))
11172 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11173 ;; Look for a regular expression.
11174 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11175 (match-string 1 s)))
11176 ;; Fuzzy links.
11178 (let ((starred (eq (string-to-char normalized) ?*)))
11179 (cond
11180 ;; Look for targets, only if not in a headline search.
11181 ((and (not starred)
11182 (let ((target (format "<<%s>>" s-multi-re)))
11183 (catch :target-match
11184 (goto-char (point-min))
11185 (while (re-search-forward target nil t)
11186 (backward-char)
11187 (let ((context (org-element-context)))
11188 (when (eq (org-element-type context) 'target)
11189 (setq type 'dedicated)
11190 (goto-char (org-element-property :begin context))
11191 (throw :target-match t))))
11192 nil))))
11193 ;; Look for elements named after S, only if not in a headline
11194 ;; search.
11195 ((and (not starred)
11196 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11197 (catch :name-match
11198 (goto-char (point-min))
11199 (while (re-search-forward name nil t)
11200 (let ((element (org-element-at-point)))
11201 (when (equal (org-split-string
11202 (org-element-property :name element)
11203 "[ \t]+")
11204 words)
11205 (setq type 'dedicated)
11206 (beginning-of-line)
11207 (throw :name-match t))))
11208 nil))))
11209 ;; Regular text search. Prefer headlines in Org mode
11210 ;; buffers.
11211 ((and (derived-mode-p 'org-mode)
11212 (let* ((wspace "[ \t]")
11213 (wspaceopt (concat wspace "*"))
11214 (cookie (concat "\\(?:"
11215 wspaceopt
11216 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11217 wspaceopt
11218 "\\)"))
11219 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11220 (re (concat
11221 org-outline-regexp-bol
11222 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11223 "\\(?:\\[#.\\][ \t]+\\)?"
11224 "\\(?:" org-comment-string "[ \t]+\\)?"
11225 sep "?"
11226 (let ((title (mapconcat #'regexp-quote
11227 words
11228 sep)))
11229 (if starred (substring title 1) title))
11230 sep "?"
11231 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11232 "[ \t]*$")))
11233 (goto-char (point-min))
11234 (re-search-forward re nil t)))
11235 (goto-char (match-beginning 0))
11236 (setq type 'dedicated))
11237 ;; Offer to create non-existent headline depending on
11238 ;; `org-link-search-must-match-exact-headline'.
11239 ((and (derived-mode-p 'org-mode)
11240 (not org-link-search-inhibit-query)
11241 (eq org-link-search-must-match-exact-headline 'query-to-create)
11242 (yes-or-no-p "No match - create this as a new heading? "))
11243 (goto-char (point-max))
11244 (unless (bolp) (newline))
11245 (org-insert-heading nil t t)
11246 (insert s "\n")
11247 (beginning-of-line 0))
11248 ;; Only headlines are looked after. No need to process
11249 ;; further: throw an error.
11250 ((and (derived-mode-p 'org-mode)
11251 (or starred org-link-search-must-match-exact-headline))
11252 (goto-char origin)
11253 (error "No match for fuzzy expression: %s" normalized))
11254 ;; Regular text search.
11255 ((catch :fuzzy-match
11256 (goto-char (point-min))
11257 (while (re-search-forward s-multi-re nil t)
11258 ;; Skip match if it contains AVOID-POS or it is included
11259 ;; in a link with a description but outside the
11260 ;; description.
11261 (unless (or (and avoid-pos
11262 (<= (match-beginning 0) avoid-pos)
11263 (> (match-end 0) avoid-pos))
11264 (and (save-match-data
11265 (org-in-regexp org-bracket-link-regexp))
11266 (match-beginning 3)
11267 (or (> (match-beginning 3) (point))
11268 (<= (match-end 3) (point)))
11269 (org-element-lineage
11270 (save-match-data (org-element-context))
11271 '(link) t)))
11272 (goto-char (match-beginning 0))
11273 (setq type 'fuzzy)
11274 (throw :fuzzy-match t)))
11275 nil))
11276 ;; All failed. Throw an error.
11277 (t (goto-char origin)
11278 (error "No match for fuzzy expression: %s" normalized))))))
11279 ;; Disclose surroundings of match, if appropriate.
11280 (when (and (derived-mode-p 'org-mode) (not stealth))
11281 (org-show-context 'link-search))
11282 type))
11284 (defun org-get-buffer-for-internal-link (buffer)
11285 "Return a buffer to be used for displaying the link target of internal links."
11286 (cond
11287 ((not org-display-internal-link-with-indirect-buffer)
11288 buffer)
11289 ((string-match "(Clone)$" (buffer-name buffer))
11290 (message "Buffer is already a clone, not making another one")
11291 ;; we also do not modify visibility in this case
11292 buffer)
11293 (t ; make a new indirect buffer for displaying the link
11294 (let* ((bn (buffer-name buffer))
11295 (ibn (concat bn "(Clone)"))
11296 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11297 (with-current-buffer ib (org-overview))
11298 ib))))
11300 (defun org-do-occur (regexp &optional cleanup)
11301 "Call the Emacs command `occur'.
11302 If CLEANUP is non-nil, remove the printout of the regular expression
11303 in the *Occur* buffer. This is useful if the regex is long and not useful
11304 to read."
11305 (occur regexp)
11306 (when cleanup
11307 (let ((cwin (selected-window)) win beg end)
11308 (when (setq win (get-buffer-window "*Occur*"))
11309 (select-window win))
11310 (goto-char (point-min))
11311 (when (re-search-forward "match[a-z]+" nil t)
11312 (setq beg (match-end 0))
11313 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11314 (setq end (1- (match-beginning 0)))))
11315 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11316 (goto-char (point-min))
11317 (select-window cwin))))
11319 ;;; The mark ring for links jumps
11321 (defvar org-mark-ring nil
11322 "Mark ring for positions before jumps in Org-mode.")
11323 (defvar org-mark-ring-last-goto nil
11324 "Last position in the mark ring used to go back.")
11325 ;; Fill and close the ring
11326 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11327 (dotimes (_ org-mark-ring-length)
11328 (push (make-marker) org-mark-ring))
11329 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11330 org-mark-ring)
11332 (defun org-mark-ring-push (&optional pos buffer)
11333 "Put the current position or POS into the mark ring and rotate it."
11334 (interactive)
11335 (setq pos (or pos (point)))
11336 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11337 (move-marker (car org-mark-ring)
11338 (or pos (point))
11339 (or buffer (current-buffer)))
11340 (message "%s"
11341 (substitute-command-keys
11342 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11344 (defun org-mark-ring-goto (&optional n)
11345 "Jump to the previous position in the mark ring.
11346 With prefix arg N, jump back that many stored positions. When
11347 called several times in succession, walk through the entire ring.
11348 Org-mode commands jumping to a different position in the current file,
11349 or to another Org-mode file, automatically push the old position
11350 onto the ring."
11351 (interactive "p")
11352 (let (p m)
11353 (if (eq last-command this-command)
11354 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11355 (setq p org-mark-ring))
11356 (setq org-mark-ring-last-goto p)
11357 (setq m (car p))
11358 (pop-to-buffer-same-window (marker-buffer m))
11359 (goto-char m)
11360 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11362 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11363 ;;; Emacs 24.4+
11364 (defun org-remove-angle-brackets (s)
11365 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11366 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11368 (defun org-add-angle-brackets (s)
11369 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11370 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11372 (defun org-remove-double-quotes (s)
11373 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11374 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11377 ;;; Following specific links
11379 (defvar org-agenda-buffer-tmp-name)
11380 (defvar org-agenda-start-on-weekday)
11381 (defun org-follow-timestamp-link ()
11382 "Open an agenda view for the time-stamp date/range at point."
11383 (cond
11384 ((org-at-date-range-p t)
11385 (let ((org-agenda-start-on-weekday)
11386 (t1 (match-string 1))
11387 (t2 (match-string 2)) tt1 tt2)
11388 (setq tt1 (time-to-days (org-time-string-to-time t1))
11389 tt2 (time-to-days (org-time-string-to-time t2)))
11390 (let ((org-agenda-buffer-tmp-name
11391 (format "*Org Agenda(a:%s)"
11392 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11393 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11394 ((org-at-timestamp-p t)
11395 (let ((org-agenda-buffer-tmp-name
11396 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11397 (org-agenda-list nil (time-to-days (org-time-string-to-time
11398 (substring (match-string 1) 0 10)))
11399 1)))
11400 (t (error "This should not happen"))))
11403 ;;; Following file links
11404 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11405 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11406 (declare-function mailcap-mime-info
11407 "mailcap" (string &optional request no-decode))
11408 (defvar org-wait nil)
11409 (defun org-open-file (path &optional in-emacs line search)
11410 "Open the file at PATH.
11411 First, this expands any special file name abbreviations. Then the
11412 configuration variable `org-file-apps' is checked if it contains an
11413 entry for this file type, and if yes, the corresponding command is launched.
11415 If no application is found, Emacs simply visits the file.
11417 With optional prefix argument IN-EMACS, Emacs will visit the file.
11418 With a double \\[universal-argument] \\[universal-argument] \
11419 prefix arg, Org tries to avoid opening in Emacs
11420 and to use an external application to visit the file.
11422 Optional LINE specifies a line to go to, optional SEARCH a string
11423 to search for. If LINE or SEARCH is given, the file will be
11424 opened in Emacs, unless an entry from org-file-apps that makes
11425 use of groups in a regexp matches.
11427 If you want to change the way frames are used when following a
11428 link, please customize `org-link-frame-setup'.
11430 If the file does not exist, an error is thrown."
11431 (let* ((file (if (equal path "")
11432 buffer-file-name
11433 (substitute-in-file-name (expand-file-name path))))
11434 (file-apps (append org-file-apps (org-default-apps)))
11435 (apps (cl-remove-if
11436 'org-file-apps-entry-match-against-dlink-p file-apps))
11437 (apps-dlink (cl-remove-if-not
11438 'org-file-apps-entry-match-against-dlink-p file-apps))
11439 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11440 (dirp (unless remp (file-directory-p file)))
11441 (file (if (and dirp org-open-directory-means-index-dot-org)
11442 (concat (file-name-as-directory file) "index.org")
11443 file))
11444 (a-m-a-p (assq 'auto-mode apps))
11445 (dfile (downcase file))
11446 ;; Reconstruct the original link from the PATH, LINE and
11447 ;; SEARCH args.
11448 (link (cond (line (concat file "::" (number-to-string line)))
11449 (search (concat file "::" search))
11450 (t file)))
11451 (dlink (downcase link))
11452 (old-buffer (current-buffer))
11453 (old-pos (point))
11454 (old-mode major-mode)
11455 (ext
11456 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11457 (match-string 1 dfile)))
11458 cmd link-match-data)
11459 (cond
11460 ((member in-emacs '((16) system))
11461 (setq cmd (cdr (assq 'system apps))))
11462 (in-emacs (setq cmd 'emacs))
11464 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11465 (and dirp (cdr (assq 'directory apps)))
11466 ;; First, try matching against apps-dlink if we
11467 ;; get a match here, store the match data for
11468 ;; later.
11469 (let ((match (assoc-default dlink apps-dlink
11470 'string-match)))
11471 (if match
11472 (progn (setq link-match-data (match-data))
11473 match)
11474 (progn (setq in-emacs (or in-emacs line search))
11475 nil))) ; if we have no match in apps-dlink,
11476 ; always open the file in emacs if line or search
11477 ; is given (for backwards compatibility)
11478 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11479 'string-match)
11480 (cdr (assoc ext apps))
11481 (cdr (assq t apps))))))
11482 (when (eq cmd 'system)
11483 (setq cmd (cdr (assoc 'system apps))))
11484 (when (eq cmd 'default)
11485 (setq cmd (cdr (assoc t apps))))
11486 (when (eq cmd 'mailcap)
11487 (require 'mailcap)
11488 (mailcap-parse-mailcaps)
11489 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11490 (command (mailcap-mime-info mime-type)))
11491 (if (stringp command)
11492 (setq cmd command)
11493 (setq cmd 'emacs))))
11494 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11495 (not (file-exists-p file))
11496 (not org-open-non-existing-files))
11497 (user-error "No such file: %s" file))
11498 (cond
11499 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11500 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11501 (while (string-match "['\"]%s['\"]" cmd)
11502 (setq cmd (replace-match "%s" t t cmd)))
11503 (while (string-match "%s" cmd)
11504 (setq cmd (replace-match
11505 (save-match-data
11506 (shell-quote-argument
11507 (convert-standard-filename file)))
11508 t t cmd)))
11510 ;; Replace "%1", "%2" etc. in command with group matches from regex
11511 (save-match-data
11512 (let ((match-index 1)
11513 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11514 (set-match-data link-match-data)
11515 (while (<= match-index number-of-groups)
11516 (let ((regex (concat "%" (number-to-string match-index)))
11517 (replace-with (match-string match-index dlink)))
11518 (while (string-match regex cmd)
11519 (setq cmd (replace-match replace-with t t cmd))))
11520 (setq match-index (+ match-index 1)))))
11522 (save-window-excursion
11523 (message "Running %s...done" cmd)
11524 (start-process-shell-command cmd nil cmd)
11525 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11526 ((or (stringp cmd)
11527 (eq cmd 'emacs))
11528 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11529 (widen)
11530 (cond (line (org-goto-line line)
11531 (when (derived-mode-p 'org-mode) (org-reveal)))
11532 (search (org-link-search search))))
11533 ((functionp cmd)
11534 (save-match-data
11535 (set-match-data link-match-data)
11536 (condition-case nil
11537 (funcall cmd file link)
11538 ;; FIXME: Remove this check when most default installations
11539 ;; of Emacs have at least Org 9.0.
11540 ((debug wrong-number-of-arguments wrong-type-argument
11541 invalid-function)
11542 (user-error "Please see Org News for version 9.0 about \
11543 `org-file-apps'--Lisp error: %S" cmd)))))
11544 ((consp cmd)
11545 ;; FIXME: Remove this check when most default installations of
11546 ;; Emacs have at least Org 9.0.
11547 ;; Heads-up instead of silently fall back to
11548 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11549 ;; with sexp instead of a function for `cmd'.
11550 (user-error "Please see Org News for version 9.0 about \
11551 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11552 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11553 (and (derived-mode-p 'org-mode)
11554 (eq old-mode 'org-mode)
11555 (or (not (eq old-buffer (current-buffer)))
11556 (not (eq old-pos (point))))
11557 (org-mark-ring-push old-pos old-buffer))))
11559 (defun org-file-apps-entry-match-against-dlink-p (entry)
11560 "This function returns non-nil if `entry' uses a regular
11561 expression which should be matched against the whole link by
11562 org-open-file.
11564 It assumes that is the case when the entry uses a regular
11565 expression which has at least one grouping construct and the
11566 action is either a lisp form or a command string containing
11567 `%1', i.e. using at least one subexpression match as a
11568 parameter."
11569 (let ((selector (car entry))
11570 (action (cdr entry)))
11571 (if (stringp selector)
11572 (and (> (regexp-opt-depth selector) 0)
11573 (or (and (stringp action)
11574 (string-match "%[0-9]" action))
11575 (consp action)))
11576 nil)))
11578 (defun org-default-apps ()
11579 "Return the default applications for this operating system."
11580 (cond
11581 ((eq system-type 'darwin)
11582 org-file-apps-defaults-macosx)
11583 ((eq system-type 'windows-nt)
11584 org-file-apps-defaults-windowsnt)
11585 (t org-file-apps-defaults-gnu)))
11587 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11588 "Convert extensions to regular expressions in the cars of LIST.
11589 Also, weed out any non-string entries, because the return value is used
11590 only for regexp matching.
11591 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11592 point to the symbol `emacs', indicating that the file should
11593 be opened in Emacs."
11594 (append
11595 (delq nil
11596 (mapcar (lambda (x)
11597 (unless (not (stringp (car x)))
11598 (if (string-match "\\W" (car x))
11600 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11601 list))
11602 (when add-auto-mode
11603 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11605 (defvar ange-ftp-name-format)
11606 (defun org-file-remote-p (file)
11607 "Test whether FILE specifies a location on a remote system.
11608 Return non-nil if the location is indeed remote.
11610 For example, the filename \"/user@host:/foo\" specifies a location
11611 on the system \"/user@host:\"."
11612 (cond ((fboundp 'file-remote-p)
11613 (file-remote-p file))
11614 ((fboundp 'tramp-handle-file-remote-p)
11615 (tramp-handle-file-remote-p file))
11616 ((and (boundp 'ange-ftp-name-format)
11617 (string-match (car ange-ftp-name-format) file))
11618 t)))
11621 ;;;; Refiling
11623 (defun org-get-org-file ()
11624 "Read a filename, with default directory `org-directory'."
11625 (let ((default (or org-default-notes-file remember-data-file)))
11626 (read-file-name (format "File name [%s]: " default)
11627 (file-name-as-directory org-directory)
11628 default)))
11630 (defun org-notes-order-reversed-p ()
11631 "Check if the current file should receive notes in reversed order."
11632 (cond
11633 ((not org-reverse-note-order) nil)
11634 ((eq t org-reverse-note-order) t)
11635 ((not (listp org-reverse-note-order)) nil)
11636 (t (catch 'exit
11637 (dolist (entry org-reverse-note-order)
11638 (when (string-match (car entry) buffer-file-name)
11639 (throw 'exit (cdr entry))))))))
11641 (defvar org-refile-target-table nil
11642 "The list of refile targets, created by `org-refile'.")
11644 (defvar org-agenda-new-buffers nil
11645 "Buffers created to visit agenda files.")
11647 (defvar org-refile-cache nil
11648 "Cache for refile targets.")
11650 (defvar org-refile-markers nil
11651 "All the markers used for caching refile locations.")
11653 (defun org-refile-marker (pos)
11654 "Get a new refile marker, but only if caching is in use."
11655 (if (not org-refile-use-cache)
11657 (let ((m (make-marker)))
11658 (move-marker m pos)
11659 (push m org-refile-markers)
11660 m)))
11662 (defun org-refile-cache-clear ()
11663 "Clear the refile cache and disable all the markers."
11664 (dolist (m org-refile-markers) (move-marker m nil))
11665 (setq org-refile-markers nil)
11666 (setq org-refile-cache nil)
11667 (message "Refile cache has been cleared"))
11669 (defun org-refile-cache-check-set (set)
11670 "Check if all the markers in the cache still have live buffers."
11671 (let (marker)
11672 (catch 'exit
11673 (while (and set (setq marker (nth 3 (pop set))))
11674 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11675 (when (and marker (null (marker-buffer marker)))
11676 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11677 (sit-for 3)
11678 (throw 'exit nil)))
11679 t)))
11681 (defun org-refile-cache-put (set &rest identifiers)
11682 "Push the refile targets SET into the cache, under IDENTIFIERS."
11683 (let* ((key (sha1 (prin1-to-string identifiers)))
11684 (entry (assoc key org-refile-cache)))
11685 (if entry
11686 (setcdr entry set)
11687 (push (cons key set) org-refile-cache))))
11689 (defun org-refile-cache-get (&rest identifiers)
11690 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11691 (cond
11692 ((not org-refile-cache) nil)
11693 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11695 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11696 org-refile-cache))))
11697 (and set (org-refile-cache-check-set set) set)))))
11699 (defvar org-outline-path-cache nil
11700 "Alist between buffer positions and outline paths.
11701 It value is an alist (POSITION . PATH) where POSITION is the
11702 buffer position at the beginning of an entry and PATH is a list
11703 of strings describing the outline path for that entry, in reverse
11704 order.")
11706 (defun org-refile-get-targets (&optional default-buffer)
11707 "Produce a table with refile targets."
11708 (let ((case-fold-search nil)
11709 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11710 (entries (or org-refile-targets '((nil . (:level . 1)))))
11711 targets tgs files desc descre)
11712 (message "Getting targets...")
11713 (with-current-buffer (or default-buffer (current-buffer))
11714 (dolist (entry entries)
11715 (setq files (car entry) desc (cdr entry))
11716 (cond
11717 ((null files) (setq files (list (current-buffer))))
11718 ((eq files 'org-agenda-files)
11719 (setq files (org-agenda-files 'unrestricted)))
11720 ((and (symbolp files) (fboundp files))
11721 (setq files (funcall files)))
11722 ((and (symbolp files) (boundp files))
11723 (setq files (symbol-value files))))
11724 (when (stringp files) (setq files (list files)))
11725 (cond
11726 ((eq (car desc) :tag)
11727 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11728 ((eq (car desc) :todo)
11729 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11730 ((eq (car desc) :regexp)
11731 (setq descre (cdr desc)))
11732 ((eq (car desc) :level)
11733 (setq descre (concat "^\\*\\{" (number-to-string
11734 (if org-odd-levels-only
11735 (1- (* 2 (cdr desc)))
11736 (cdr desc)))
11737 "\\}[ \t]")))
11738 ((eq (car desc) :maxlevel)
11739 (setq descre (concat "^\\*\\{1," (number-to-string
11740 (if org-odd-levels-only
11741 (1- (* 2 (cdr desc)))
11742 (cdr desc)))
11743 "\\}[ \t]")))
11744 (t (error "Bad refiling target description %s" desc)))
11745 (dolist (f files)
11746 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11748 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11749 (progn
11750 (when (bufferp f)
11751 (setq f (buffer-file-name (buffer-base-buffer f))))
11752 (setq f (and f (expand-file-name f)))
11753 (when (eq org-refile-use-outline-path 'file)
11754 (push (list (file-name-nondirectory f) f nil nil) tgs))
11755 (org-with-wide-buffer
11756 (goto-char (point-min))
11757 (setq org-outline-path-cache nil)
11758 (while (re-search-forward descre nil t)
11759 (beginning-of-line)
11760 (looking-at org-complex-heading-regexp)
11761 (let ((begin (point))
11762 (heading (match-string-no-properties 4)))
11763 (unless (or (and
11764 org-refile-target-verify-function
11765 (not
11766 (funcall org-refile-target-verify-function)))
11767 (not heading))
11768 (let ((re (format org-complex-heading-regexp-format
11769 (regexp-quote heading)))
11770 (target
11771 (if (not org-refile-use-outline-path) heading
11772 (mapconcat
11773 #'org-protect-slash
11774 (append
11775 (pcase org-refile-use-outline-path
11776 (`file (list (file-name-nondirectory
11777 (buffer-file-name
11778 (buffer-base-buffer)))))
11779 (`full-file-path
11780 (list (buffer-file-name
11781 (buffer-base-buffer))))
11782 (_ nil))
11783 (org-get-outline-path t t))
11784 "/"))))
11785 (push (list target f re (org-refile-marker (point)))
11786 tgs)))
11787 (when (= (point) begin)
11788 ;; Verification function has not moved point.
11789 (end-of-line)))))))
11790 (when org-refile-use-cache
11791 (org-refile-cache-put tgs (buffer-file-name) descre))
11792 (setq targets (append tgs targets))))))
11793 (message "Getting targets...done")
11794 (nreverse targets)))
11796 (defun org-protect-slash (s)
11797 (while (string-match "/" s)
11798 (setq s (replace-match "\\" t t s)))
11801 (defun org--get-outline-path-1 (&optional use-cache)
11802 "Return outline path to current headline.
11804 Outline path is a list of strings, in reverse order. When
11805 optional argument USE-CACHE is non-nil, make use of a cache. See
11806 `org-get-outline-path' for details.
11808 Assume buffer is widened and point is on a headline."
11809 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11810 (let ((p (point))
11811 (heading (progn
11812 (looking-at org-complex-heading-regexp)
11813 (if (not (match-end 4)) ""
11814 ;; Remove statistics cookies.
11815 (org-trim
11816 (org-link-display-format
11817 (replace-regexp-in-string
11818 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11819 (match-string-no-properties 4))))))))
11820 (if (org-up-heading-safe)
11821 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11822 (when use-cache
11823 (push (cons p path) org-outline-path-cache))
11824 path)
11825 ;; This is a new root node. Since we assume we are moving
11826 ;; forward, we can drop previous cache so as to limit number
11827 ;; of associations there.
11828 (let ((path (list heading)))
11829 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11830 path)))))
11832 (defun org-get-outline-path (&optional with-self use-cache)
11833 "Return the outline path to the current entry.
11835 An outline path is a list of ancestors for current headline, as
11836 a list of strings. Statistics cookies are removed and links are
11837 replaced with their description, if any, or their path otherwise.
11839 When optional argument WITH-SELF is non-nil, the path also
11840 includes the current headline.
11842 When optional argument USE-CACHE is non-nil, cache outline paths
11843 between calls to this function so as to avoid backtracking. This
11844 argument is useful when planning to find more than one outline
11845 path in the same document. In that case, there are two
11846 conditions to satisfy:
11847 - `org-outline-path-cache' is set to nil before starting the
11848 process;
11849 - outline paths are computed by increasing buffer positions."
11850 (org-with-wide-buffer
11851 (and (or (and with-self (org-back-to-heading t))
11852 (org-up-heading-safe))
11853 (reverse (org--get-outline-path-1 use-cache)))))
11855 (defun org-format-outline-path (path &optional width prefix separator)
11856 "Format the outline path PATH for display.
11857 WIDTH is the maximum number of characters that is available.
11858 PREFIX is a prefix to be included in the returned string,
11859 such as the file name.
11860 SEPARATOR is inserted between the different parts of the path,
11861 the default is \"/\"."
11862 (setq width (or width 79))
11863 (setq path (delq nil path))
11864 (unless (> width 0)
11865 (user-error "Argument `width' must be positive"))
11866 (setq separator (or separator "/"))
11867 (let* ((org-odd-levels-only nil)
11868 (fpath (concat
11869 prefix (and prefix path separator)
11870 (mapconcat
11871 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11872 (cl-loop for head in path
11873 for n from 0
11874 collect (org-add-props
11875 head nil 'face
11876 (nth (% n org-n-level-faces) org-level-faces)))
11877 separator))))
11878 (when (> (length fpath) width)
11879 (if (< width 7)
11880 ;; It's unlikely that `width' will be this small, but don't
11881 ;; waste characters by adding ".." if it is.
11882 (setq fpath (substring fpath 0 width))
11883 (setf (substring fpath (- width 2)) "..")))
11884 fpath))
11886 (defun org-display-outline-path (&optional file current separator just-return-string)
11887 "Display the current outline path in the echo area.
11889 If FILE is non-nil, prepend the output with the file name.
11890 If CURRENT is non-nil, append the current heading to the output.
11891 SEPARATOR is passed through to `org-format-outline-path'. It separates
11892 the different parts of the path and defaults to \"/\".
11893 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11894 (interactive "P")
11895 (let* (case-fold-search
11896 (bfn (buffer-file-name (buffer-base-buffer)))
11897 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11898 res)
11899 (when current (setq path (append path
11900 (save-excursion
11901 (org-back-to-heading t)
11902 (when (looking-at org-complex-heading-regexp)
11903 (list (match-string 4)))))))
11904 (setq res
11905 (org-format-outline-path
11906 path
11907 (1- (frame-width))
11908 (and file bfn (concat (file-name-nondirectory bfn) separator))
11909 separator))
11910 (if just-return-string
11911 (org-no-properties res)
11912 (org-unlogged-message "%s" res))))
11914 (defvar org-refile-history nil
11915 "History for refiling operations.")
11917 (defvar org-after-refile-insert-hook nil
11918 "Hook run after `org-refile' has inserted its stuff at the new location.
11919 Note that this is still *before* the stuff will be removed from
11920 the *old* location.")
11922 (defvar org-capture-last-stored-marker)
11923 (defvar org-refile-keep nil
11924 "Non-nil means `org-refile' will copy instead of refile.")
11926 (defun org-copy ()
11927 "Like `org-refile', but copy."
11928 (interactive)
11929 (let ((org-refile-keep t))
11930 (funcall 'org-refile nil nil nil "Copy")))
11932 (defun org-refile (&optional arg default-buffer rfloc msg)
11933 "Move the entry or entries at point to another heading.
11934 The list of target headings is compiled using the information in
11935 `org-refile-targets', which see.
11937 At the target location, the entry is filed as a subitem of the
11938 target heading. Depending on `org-reverse-note-order', the new
11939 subitem will either be the first or the last subitem.
11941 If there is an active region, all entries in that region will be
11942 refiled. However, the region must fulfill the requirement that
11943 the first heading sets the top-level of the moved text.
11945 With prefix arg ARG, the command will only visit the target
11946 location and not actually move anything.
11948 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11949 refiling operation has put the subtree.
11951 With a numeric prefix argument of `2', refile to the running clock.
11953 With a numeric prefix argument of `3', emulate `org-refile-keep'
11954 being set to t and copy to the target location, don't move it.
11955 Beware that keeping refiled entries may result in duplicated ID
11956 properties.
11958 RFLOC can be a refile location obtained in a different way.
11960 MSG is a string to replace \"Refile\" in the default prompt with
11961 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11963 See also `org-refile-use-outline-path'.
11965 If you are using target caching (see `org-refile-use-cache'), you
11966 have to clear the target cache in order to find new targets.
11967 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11968 prefix argument (`C-u C-u C-u C-c C-w')."
11969 (interactive "P")
11970 (if (member arg '(0 (64)))
11971 (org-refile-cache-clear)
11972 (let* ((actionmsg (cond (msg msg)
11973 ((equal arg 3) "Refile (and keep)")
11974 (t "Refile")))
11975 (regionp (org-region-active-p))
11976 (region-start (and regionp (region-beginning)))
11977 (region-end (and regionp (region-end)))
11978 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11979 pos it nbuf file level reversed)
11980 (setq last-command nil)
11981 (when regionp
11982 (goto-char region-start)
11983 (or (bolp) (goto-char (point-at-bol)))
11984 (setq region-start (point))
11985 (unless (or (org-kill-is-subtree-p
11986 (buffer-substring region-start region-end))
11987 (prog1 org-refile-active-region-within-subtree
11988 (let ((s (point-at-eol)))
11989 (org-toggle-heading)
11990 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11991 (user-error "The region is not a (sequence of) subtree(s)")))
11992 (if (equal arg '(16))
11993 (org-refile-goto-last-stored)
11994 (when (or
11995 (and (equal arg 2)
11996 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11997 (prog1
11998 (setq it (list (or org-clock-heading "running clock")
11999 (buffer-file-name
12000 (marker-buffer org-clock-hd-marker))
12002 (marker-position org-clock-hd-marker)))
12003 (setq arg nil)))
12004 (setq it
12005 (or rfloc
12006 (let (heading-text)
12007 (save-excursion
12008 (unless (and arg (listp arg))
12009 (org-back-to-heading t)
12010 (setq heading-text
12011 (replace-regexp-in-string
12012 org-bracket-link-regexp
12013 "\\3"
12014 (or (nth 4 (org-heading-components))
12015 ""))))
12016 (org-refile-get-location
12017 (cond ((and arg (listp arg)) "Goto")
12018 (regionp (concat actionmsg " region to"))
12019 (t (concat actionmsg " subtree \""
12020 heading-text "\" to")))
12021 default-buffer
12022 (and (not (equal '(4) arg))
12023 org-refile-allow-creating-parent-nodes)))))))
12024 (setq file (nth 1 it)
12025 pos (nth 3 it))
12026 (when (and (not arg)
12028 (equal (buffer-file-name) file)
12029 (if regionp
12030 (and (>= pos region-start)
12031 (<= pos region-end))
12032 (and (>= pos (point))
12033 (< pos (save-excursion
12034 (org-end-of-subtree t t))))))
12035 (error "Cannot refile to position inside the tree or region"))
12036 (setq nbuf (or (find-buffer-visiting file)
12037 (find-file-noselect file)))
12038 (if (and arg (not (equal arg 3)))
12039 (progn
12040 (pop-to-buffer-same-window nbuf)
12041 (goto-char pos)
12042 (org-show-context 'org-goto))
12043 (if regionp
12044 (progn
12045 (org-kill-new (buffer-substring region-start region-end))
12046 (org-save-markers-in-region region-start region-end))
12047 (org-copy-subtree 1 nil t))
12048 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12049 (find-file-noselect file)))
12050 (setq reversed (org-notes-order-reversed-p))
12051 (save-excursion
12052 (save-restriction
12053 (widen)
12054 (if pos
12055 (progn
12056 (goto-char pos)
12057 (looking-at org-outline-regexp)
12058 (setq level (org-get-valid-level (funcall outline-level) 1))
12059 (goto-char
12060 (if reversed
12061 (or (outline-next-heading) (point-max))
12062 (or (save-excursion (org-get-next-sibling))
12063 (org-end-of-subtree t t)
12064 (point-max)))))
12065 (setq level 1)
12066 (if (not reversed)
12067 (goto-char (point-max))
12068 (goto-char (point-min))
12069 (or (outline-next-heading) (goto-char (point-max)))))
12070 (unless (bolp) (newline))
12071 (org-paste-subtree level nil nil t)
12072 (when org-log-refile
12073 (org-add-log-setup 'refile nil nil org-log-refile)
12074 (unless (eq org-log-refile 'note)
12075 (save-excursion (org-add-log-note))))
12076 (and org-auto-align-tags
12077 (let ((org-loop-over-headlines-in-active-region nil))
12078 (org-set-tags nil t)))
12079 (let ((bookmark-name (plist-get org-bookmark-names-plist
12080 :last-refile)))
12081 (when bookmark-name
12082 (with-demoted-errors
12083 (bookmark-set bookmark-name))))
12084 ;; If we are refiling for capture, make sure that the
12085 ;; last-capture pointers point here
12086 (when (bound-and-true-p org-capture-is-refiling)
12087 (let ((bookmark-name (plist-get org-bookmark-names-plist
12088 :last-capture-marker)))
12089 (when bookmark-name
12090 (with-demoted-errors
12091 (bookmark-set bookmark-name))))
12092 (move-marker org-capture-last-stored-marker (point)))
12093 (when (fboundp 'deactivate-mark) (deactivate-mark))
12094 (run-hooks 'org-after-refile-insert-hook))))
12095 (unless org-refile-keep
12096 (if regionp
12097 (delete-region (point) (+ (point) (- region-end region-start)))
12098 (delete-region
12099 (and (org-back-to-heading t) (point))
12100 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12101 (when (featurep 'org-inlinetask)
12102 (org-inlinetask-remove-END-maybe))
12103 (setq org-markers-to-move nil)
12104 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12106 (defun org-refile-goto-last-stored ()
12107 "Go to the location where the last refile was stored."
12108 (interactive)
12109 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12110 (message "This is the location of the last refile"))
12112 (defun org-refile--get-location (refloc tbl)
12113 "When user refile to REFLOC, find the associated target in TBL.
12114 Also check `org-refile-target-table'."
12115 (car (delq
12117 (mapcar
12118 (lambda (r) (or (assoc r tbl)
12119 (assoc r org-refile-target-table)))
12120 (list (replace-regexp-in-string "/$" "" refloc)
12121 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12123 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12124 "Prompt the user for a refile location, using PROMPT.
12125 PROMPT should not be suffixed with a colon and a space, because
12126 this function appends the default value from
12127 `org-refile-history' automatically, if that is not empty."
12128 (let ((org-refile-targets org-refile-targets)
12129 (org-refile-use-outline-path org-refile-use-outline-path))
12130 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12131 (unless org-refile-target-table
12132 (user-error "No refile targets"))
12133 (let* ((cbuf (current-buffer))
12134 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12135 (cfunc (if (and org-refile-use-outline-path
12136 org-outline-path-complete-in-steps)
12137 #'org-olpath-completing-read
12138 #'completing-read))
12139 (extra (if org-refile-use-outline-path "/" ""))
12140 (cbnex (concat (buffer-name) extra))
12141 (filename (and cfn (expand-file-name cfn)))
12142 (tbl (mapcar
12143 (lambda (x)
12144 (if (and (not (member org-refile-use-outline-path
12145 '(file full-file-path)))
12146 (not (equal filename (nth 1 x))))
12147 (cons (concat (car x) extra " ("
12148 (file-name-nondirectory (nth 1 x)) ")")
12149 (cdr x))
12150 (cons (concat (car x) extra) (cdr x))))
12151 org-refile-target-table))
12152 (completion-ignore-case t)
12153 cdef
12154 (prompt (concat prompt
12155 (or (and (car org-refile-history)
12156 (concat " (default " (car org-refile-history) ")"))
12157 (and (assoc cbnex tbl) (setq cdef cbnex)
12158 (concat " (default " cbnex ")"))) ": "))
12159 pa answ parent-target child parent old-hist)
12160 (setq old-hist org-refile-history)
12161 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12162 nil 'org-refile-history (or cdef (car org-refile-history))))
12163 (if (setq pa (org-refile--get-location answ tbl))
12164 (progn
12165 (org-refile-check-position pa)
12166 (when (or (not org-refile-history)
12167 (not (eq old-hist org-refile-history))
12168 (not (equal (car pa) (car org-refile-history))))
12169 (setq org-refile-history
12170 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12171 org-refile-history
12172 (cdr org-refile-history))))
12173 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12174 (pop org-refile-history)))
12176 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12177 (progn
12178 (setq parent (match-string 1 answ)
12179 child (match-string 2 answ))
12180 (setq parent-target (org-refile--get-location parent tbl))
12181 (when (and parent-target
12182 (or (eq new-nodes t)
12183 (and (eq new-nodes 'confirm)
12184 (y-or-n-p (format "Create new node \"%s\"? "
12185 child)))))
12186 (org-refile-new-child parent-target child)))
12187 (user-error "Invalid target location")))))
12189 (declare-function org-string-nw-p "org-macs" (s))
12190 (defun org-refile-check-position (refile-pointer)
12191 "Check if the refile pointer matches the headline to which it points."
12192 (let* ((file (nth 1 refile-pointer))
12193 (re (nth 2 refile-pointer))
12194 (pos (nth 3 refile-pointer))
12195 buffer)
12196 (if (and (not (markerp pos)) (not file))
12197 (user-error "Please indicate a target file in the refile path")
12198 (when (org-string-nw-p re)
12199 (setq buffer (if (markerp pos)
12200 (marker-buffer pos)
12201 (or (find-buffer-visiting file)
12202 (find-file-noselect file))))
12203 (with-current-buffer buffer
12204 (save-excursion
12205 (save-restriction
12206 (widen)
12207 (goto-char pos)
12208 (beginning-of-line 1)
12209 (unless (looking-at-p re)
12210 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12212 (defun org-refile-new-child (parent-target child)
12213 "Use refile target PARENT-TARGET to add new CHILD below it."
12214 (unless parent-target
12215 (error "Cannot find parent for new node"))
12216 (let ((file (nth 1 parent-target))
12217 (pos (nth 3 parent-target))
12218 level)
12219 (with-current-buffer (or (find-buffer-visiting file)
12220 (find-file-noselect file))
12221 (save-excursion
12222 (save-restriction
12223 (widen)
12224 (if pos
12225 (goto-char pos)
12226 (goto-char (point-max))
12227 (unless (bolp) (newline)))
12228 (when (looking-at org-outline-regexp)
12229 (setq level (funcall outline-level))
12230 (org-end-of-subtree t t))
12231 (org-back-over-empty-lines)
12232 (insert "\n" (make-string
12233 (if pos (org-get-valid-level level 1) 1) ?*)
12234 " " child "\n")
12235 (beginning-of-line 0)
12236 (list (concat (car parent-target) "/" child) file "" (point)))))))
12238 (defun org-olpath-completing-read (prompt collection &rest args)
12239 "Read an outline path like a file name."
12240 (let ((thetable collection))
12241 (apply #'completing-read
12242 prompt
12243 (lambda (string predicate &optional flag)
12244 (cond
12245 ((eq flag nil) (try-completion string thetable))
12246 ((eq flag t)
12247 (let ((l (length string)))
12248 (mapcar (lambda (x)
12249 (let ((r (substring x l))
12250 (f (if (string-match " ([^)]*)$" x)
12251 (match-string 0 x)
12252 "")))
12253 (if (string-match "/" r)
12254 (concat string (substring r 0 (match-end 0)) f)
12255 x)))
12256 (all-completions string thetable predicate))))
12257 ;; Exact match?
12258 ((eq flag 'lambda) (assoc string thetable))))
12259 args)))
12261 ;;;; Dynamic blocks
12263 (defun org-find-dblock (name)
12264 "Find the first dynamic block with name NAME in the buffer.
12265 If not found, stay at current position and return nil."
12266 (let ((case-fold-search t) pos)
12267 (save-excursion
12268 (goto-char (point-min))
12269 (setq pos (and (re-search-forward
12270 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12271 (match-beginning 0))))
12272 (when pos (goto-char pos))
12273 pos))
12275 (defun org-create-dblock (plist)
12276 "Create a dynamic block section, with parameters taken from PLIST.
12277 PLIST must contain a :name entry which is used as the name of the block."
12278 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12279 (end-of-line 1)
12280 (newline))
12281 (let ((col (current-column))
12282 (name (plist-get plist :name)))
12283 (insert "#+BEGIN: " name)
12284 (while plist
12285 (if (eq (car plist) :name)
12286 (setq plist (cddr plist))
12287 (insert " " (prin1-to-string (pop plist)))))
12288 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12289 (beginning-of-line -2)))
12291 (defun org-prepare-dblock ()
12292 "Prepare dynamic block for refresh.
12293 This empties the block, puts the cursor at the insert position and returns
12294 the property list including an extra property :name with the block name."
12295 (unless (looking-at org-dblock-start-re)
12296 (user-error "Not at a dynamic block"))
12297 (let* ((begdel (1+ (match-end 0)))
12298 (name (org-no-properties (match-string 1)))
12299 (params (append (list :name name)
12300 (read (concat "(" (match-string 3) ")")))))
12301 (save-excursion
12302 (beginning-of-line 1)
12303 (skip-chars-forward " \t")
12304 (setq params (plist-put params :indentation-column (current-column))))
12305 (unless (re-search-forward org-dblock-end-re nil t)
12306 (error "Dynamic block not terminated"))
12307 (setq params
12308 (append params
12309 (list :content (buffer-substring
12310 begdel (match-beginning 0)))))
12311 (delete-region begdel (match-beginning 0))
12312 (goto-char begdel)
12313 (open-line 1)
12314 params))
12316 (defun org-map-dblocks (&optional command)
12317 "Apply COMMAND to all dynamic blocks in the current buffer.
12318 If COMMAND is not given, use `org-update-dblock'."
12319 (let ((cmd (or command 'org-update-dblock)))
12320 (save-excursion
12321 (goto-char (point-min))
12322 (while (re-search-forward org-dblock-start-re nil t)
12323 (goto-char (match-beginning 0))
12324 (save-excursion
12325 (condition-case nil
12326 (funcall cmd)
12327 (error (message "Error during update of dynamic block"))))
12328 (unless (re-search-forward org-dblock-end-re nil t)
12329 (error "Dynamic block not terminated"))))))
12331 (defun org-dblock-update (&optional arg)
12332 "User command for updating dynamic blocks.
12333 Update the dynamic block at point. With prefix ARG, update all dynamic
12334 blocks in the buffer."
12335 (interactive "P")
12336 (if arg
12337 (org-update-all-dblocks)
12338 (or (looking-at org-dblock-start-re)
12339 (org-beginning-of-dblock))
12340 (org-update-dblock)))
12342 (defun org-update-dblock ()
12343 "Update the dynamic block at point.
12344 This means to empty the block, parse for parameters and then call
12345 the correct writing function."
12346 (interactive)
12347 (save-excursion
12348 (let* ((win (selected-window))
12349 (pos (point))
12350 (line (org-current-line))
12351 (params (org-prepare-dblock))
12352 (name (plist-get params :name))
12353 (indent (plist-get params :indentation-column))
12354 (cmd (intern (concat "org-dblock-write:" name))))
12355 (message "Updating dynamic block `%s' at line %d..." name line)
12356 (funcall cmd params)
12357 (message "Updating dynamic block `%s' at line %d...done" name line)
12358 (goto-char pos)
12359 (when (and indent (> indent 0))
12360 (setq indent (make-string indent ?\ ))
12361 (save-excursion
12362 (select-window win)
12363 (org-beginning-of-dblock)
12364 (forward-line 1)
12365 (while (not (looking-at org-dblock-end-re))
12366 (insert indent)
12367 (beginning-of-line 2))
12368 (when (looking-at org-dblock-end-re)
12369 (and (looking-at "[ \t]+")
12370 (replace-match ""))
12371 (insert indent)))))))
12373 (defun org-beginning-of-dblock ()
12374 "Find the beginning of the dynamic block at point.
12375 Error if there is no such block at point."
12376 (let ((pos (point))
12377 beg)
12378 (end-of-line 1)
12379 (if (and (re-search-backward org-dblock-start-re nil t)
12380 (setq beg (match-beginning 0))
12381 (re-search-forward org-dblock-end-re nil t)
12382 (> (match-end 0) pos))
12383 (goto-char beg)
12384 (goto-char pos)
12385 (error "Not in a dynamic block"))))
12387 (defun org-update-all-dblocks ()
12388 "Update all dynamic blocks in the buffer.
12389 This function can be used in a hook."
12390 (interactive)
12391 (when (derived-mode-p 'org-mode)
12392 (org-map-dblocks 'org-update-dblock)))
12395 ;;;; Completion
12397 (declare-function org-export-backend-options "ox" (cl-x) t)
12398 (defun org-get-export-keywords ()
12399 "Return a list of all currently understood export keywords.
12400 Export keywords include options, block names, attributes and
12401 keywords relative to each registered export back-end."
12402 (let (keywords)
12403 (dolist (backend
12404 (bound-and-true-p org-export-registered-backends)
12405 (delq nil keywords))
12406 ;; Back-end name (for keywords, like #+LATEX:)
12407 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12408 (dolist (option-entry (org-export-backend-options backend))
12409 ;; Back-end options.
12410 (push (nth 1 option-entry) keywords)))))
12412 (defconst org-options-keywords
12413 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12414 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12415 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12416 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12417 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12419 (defcustom org-structure-template-alist
12420 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12421 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12422 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12423 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12424 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12425 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12426 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12427 ("L" "#+LaTeX: ")
12428 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12429 ("H" "#+HTML: ")
12430 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12431 ("A" "#+ASCII: ")
12432 ("i" "#+INDEX: ?")
12433 ("I" "#+INCLUDE: %file ?"))
12434 "Structure completion elements.
12435 This is a list of abbreviation keys and values. The value gets inserted
12436 if you type `<' followed by the key and then press the completion key,
12437 usually `TAB'. %file will be replaced by a file name after prompting
12438 for the file using completion. The cursor will be placed at the position
12439 of the `?' in the template.
12440 There are two templates for each key, the first uses the original Org syntax,
12441 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12442 the default when the /org-mtags.el/ module has been loaded. See also the
12443 variable `org-mtags-prefer-muse-templates'."
12444 :group 'org-completion
12445 :type '(repeat
12446 (list
12447 (string :tag "Key")
12448 (string :tag "Template")))
12449 :version "25.1"
12450 :package-version '(Org . "8.3"))
12452 (defun org-try-structure-completion ()
12453 "Try to complete a structure template before point.
12454 This looks for strings like \"<e\" on an otherwise empty line and
12455 expands them."
12456 (let ((l (buffer-substring (point-at-bol) (point)))
12458 (when (and (looking-at "[ \t]*$")
12459 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12460 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12461 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12462 (match-beginning 1)) a)
12463 t)))
12465 (defun org-complete-expand-structure-template (start cell)
12466 "Expand a structure template."
12467 (let ((rpl (nth 1 cell))
12468 (ind ""))
12469 (delete-region start (point))
12470 (when (string-match "\\`[ \t]*#\\+" rpl)
12471 (cond
12472 ((bolp))
12473 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12474 (setq ind (buffer-substring (point-at-bol) (point))))
12475 (t (newline))))
12476 (setq start (point))
12477 (when (string-match "%file" rpl)
12478 (setq rpl (replace-match
12479 (concat
12480 "\""
12481 (save-match-data
12482 (abbreviate-file-name (read-file-name "Include file: ")))
12483 "\"")
12484 t t rpl)))
12485 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12486 (concat "\n" ind)))
12487 (insert rpl)
12488 (when (re-search-backward "\\?" start t) (delete-char 1))))
12490 ;;;; TODO, DEADLINE, Comments
12492 (defun org-toggle-comment ()
12493 "Change the COMMENT state of an entry."
12494 (interactive)
12495 (save-excursion
12496 (org-back-to-heading)
12497 (looking-at org-complex-heading-regexp)
12498 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12499 (skip-chars-forward " \t")
12500 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12501 (if (org-in-commented-heading-p t)
12502 (delete-region (point)
12503 (progn (search-forward " " (line-end-position) 'move)
12504 (skip-chars-forward " \t")
12505 (point)))
12506 (insert org-comment-string)
12507 (unless (eolp) (insert " ")))))
12509 (defvar org-last-todo-state-is-todo nil
12510 "This is non-nil when the last TODO state change led to a TODO state.
12511 If the last change removed the TODO tag or switched to DONE, then
12512 this is nil.")
12514 (defvar org-setting-tags nil) ; dynamically skipped
12516 (defvar org-todo-setup-filter-hook nil
12517 "Hook for functions that pre-filter todo specs.
12518 Each function takes a todo spec and returns either nil or the spec
12519 transformed into canonical form." )
12521 (defvar org-todo-get-default-hook nil
12522 "Hook for functions that get a default item for todo.
12523 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12524 nil or a string to be used for the todo mark." )
12526 (defvar org-agenda-headline-snapshot-before-repeat)
12528 (defun org-current-effective-time ()
12529 "Return current time adjusted for `org-extend-today-until' variable."
12530 (let* ((ct (org-current-time))
12531 (dct (decode-time ct))
12532 (ct1
12533 (cond
12534 (org-use-last-clock-out-time-as-effective-time
12535 (or (org-clock-get-last-clock-out-time) ct))
12536 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12537 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12538 (t ct))))
12539 ct1))
12541 (defun org-todo-yesterday (&optional arg)
12542 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12543 (interactive "P")
12544 (if (eq major-mode 'org-agenda-mode)
12545 (apply 'org-agenda-todo-yesterday arg)
12546 (let* ((org-use-effective-time t)
12547 (hour (nth 2 (decode-time (org-current-time))))
12548 (org-extend-today-until (1+ hour)))
12549 (org-todo arg))))
12551 (defvar org-block-entry-blocking ""
12552 "First entry preventing the TODO state change.")
12554 (defun org-cancel-repeater ()
12555 "Cancel a repeater by setting its numeric value to zero."
12556 (interactive)
12557 (save-excursion
12558 (org-back-to-heading t)
12559 (let ((bound1 (point))
12560 (bound0 (save-excursion (outline-next-heading) (point))))
12561 (when (and (re-search-forward
12562 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12563 org-deadline-time-regexp "\\)\\|\\("
12564 org-ts-regexp "\\)")
12565 bound0 t)
12566 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12567 bound1 t))
12568 (replace-match "0" t nil nil 1)))))
12570 (defvar org-state) ;; dynamically scoped into this function
12571 (defun org-todo (&optional arg)
12572 "Change the TODO state of an item.
12573 The state of an item is given by a keyword at the start of the heading,
12574 like
12575 *** TODO Write paper
12576 *** DONE Call mom
12578 The different keywords are specified in the variable `org-todo-keywords'.
12579 By default the available states are \"TODO\" and \"DONE\".
12580 So for this example: when the item starts with TODO, it is changed to DONE.
12581 When it starts with DONE, the DONE is removed. And when neither TODO nor
12582 DONE are present, add TODO at the beginning of the heading.
12584 With \\[universal-argument] prefix arg, use completion to determine the new \
12585 state.
12586 With numeric prefix arg, switch to that state.
12587 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12588 keywords (nextset).
12589 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12590 With a numeric prefix arg of 0, inhibit note taking for the change.
12591 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12593 When called through ELisp, arg is also interpreted in the following way:
12594 `none' -> empty state
12595 \"\"(empty string) -> switch to empty state
12596 `done' -> switch to DONE
12597 `nextset' -> switch to the next set of keywords
12598 `previousset' -> switch to the previous set of keywords
12599 \"WAITING\" -> switch to the specified keyword, but only if it
12600 really is a member of `org-todo-keywords'."
12601 (interactive "P")
12602 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12603 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12604 'region-start-level 'region))
12605 org-loop-over-headlines-in-active-region)
12606 (org-map-entries
12607 `(org-todo ,arg)
12608 org-loop-over-headlines-in-active-region
12609 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12610 (when (equal arg '(16)) (setq arg 'nextset))
12611 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12612 (let ((org-blocker-hook org-blocker-hook)
12613 commentp
12614 case-fold-search)
12615 (when (equal arg '(64))
12616 (setq arg nil org-blocker-hook nil))
12617 (when (and org-blocker-hook
12618 (or org-inhibit-blocking
12619 (org-entry-get nil "NOBLOCKING")))
12620 (setq org-blocker-hook nil))
12621 (save-excursion
12622 (catch 'exit
12623 (org-back-to-heading t)
12624 (when (org-in-commented-heading-p t)
12625 (org-toggle-comment)
12626 (setq commentp t))
12627 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12628 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12629 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12630 (let* ((match-data (match-data))
12631 (startpos (point-at-bol))
12632 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12633 (org-log-done org-log-done)
12634 (org-log-repeat org-log-repeat)
12635 (org-todo-log-states org-todo-log-states)
12636 (org-inhibit-logging
12637 (if (equal arg 0)
12638 (progn (setq arg nil) 'note) org-inhibit-logging))
12639 (this (match-string 1))
12640 (hl-pos (match-beginning 0))
12641 (head (org-get-todo-sequence-head this))
12642 (ass (assoc head org-todo-kwd-alist))
12643 (interpret (nth 1 ass))
12644 (done-word (nth 3 ass))
12645 (final-done-word (nth 4 ass))
12646 (org-last-state (or this ""))
12647 (completion-ignore-case t)
12648 (member (member this org-todo-keywords-1))
12649 (tail (cdr member))
12650 (org-state (cond
12651 ((and org-todo-key-trigger
12652 (or (and (equal arg '(4))
12653 (eq org-use-fast-todo-selection 'prefix))
12654 (and (not arg) org-use-fast-todo-selection
12655 (not (eq org-use-fast-todo-selection
12656 'prefix)))))
12657 ;; Use fast selection
12658 (org-fast-todo-selection))
12659 ((and (equal arg '(4))
12660 (or (not org-use-fast-todo-selection)
12661 (not org-todo-key-trigger)))
12662 ;; Read a state with completion
12663 (completing-read
12664 "State: " (mapcar #'list org-todo-keywords-1)
12665 nil t))
12666 ((eq arg 'right)
12667 (if this
12668 (if tail (car tail) nil)
12669 (car org-todo-keywords-1)))
12670 ((eq arg 'left)
12671 (unless (equal member org-todo-keywords-1)
12672 (if this
12673 (nth (- (length org-todo-keywords-1)
12674 (length tail) 2)
12675 org-todo-keywords-1)
12676 (org-last org-todo-keywords-1))))
12677 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12678 (setq arg nil))) ; hack to fall back to cycling
12679 (arg
12680 ;; user or caller requests a specific state
12681 (cond
12682 ((equal arg "") nil)
12683 ((eq arg 'none) nil)
12684 ((eq arg 'done) (or done-word (car org-done-keywords)))
12685 ((eq arg 'nextset)
12686 (or (car (cdr (member head org-todo-heads)))
12687 (car org-todo-heads)))
12688 ((eq arg 'previousset)
12689 (let ((org-todo-heads (reverse org-todo-heads)))
12690 (or (car (cdr (member head org-todo-heads)))
12691 (car org-todo-heads))))
12692 ((car (member arg org-todo-keywords-1)))
12693 ((stringp arg)
12694 (user-error "State `%s' not valid in this file" arg))
12695 ((nth (1- (prefix-numeric-value arg))
12696 org-todo-keywords-1))))
12697 ((null member) (or head (car org-todo-keywords-1)))
12698 ((equal this final-done-word) nil) ;; -> make empty
12699 ((null tail) nil) ;; -> first entry
12700 ((memq interpret '(type priority))
12701 (if (eq this-command last-command)
12702 (car tail)
12703 (if (> (length tail) 0)
12704 (or done-word (car org-done-keywords))
12705 nil)))
12707 (car tail))))
12708 (org-state (or
12709 (run-hook-with-args-until-success
12710 'org-todo-get-default-hook org-state org-last-state)
12711 org-state))
12712 (next (if org-state (concat " " org-state " ") " "))
12713 (change-plist (list :type 'todo-state-change :from this :to org-state
12714 :position startpos))
12715 dolog now-done-p)
12716 (when org-blocker-hook
12717 (setq org-last-todo-state-is-todo
12718 (not (member this org-done-keywords)))
12719 (unless (save-excursion
12720 (save-match-data
12721 (org-with-wide-buffer
12722 (run-hook-with-args-until-failure
12723 'org-blocker-hook change-plist))))
12724 (if (called-interactively-p 'interactive)
12725 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12726 this org-state org-block-entry-blocking)
12727 ;; fail silently
12728 (message "TODO state change from %s to %s blocked (by \"%s\")"
12729 this org-state org-block-entry-blocking)
12730 (throw 'exit nil))))
12731 (store-match-data match-data)
12732 (replace-match next t t)
12733 (cond ((equal this org-state)
12734 (message "TODO state was already %s" (org-trim next)))
12735 ((pos-visible-in-window-p hl-pos)
12736 (message "TODO state changed to %s" (org-trim next))))
12737 (unless head
12738 (setq head (org-get-todo-sequence-head org-state)
12739 ass (assoc head org-todo-kwd-alist)
12740 interpret (nth 1 ass)
12741 done-word (nth 3 ass)
12742 final-done-word (nth 4 ass)))
12743 (when (memq arg '(nextset previousset))
12744 (message "Keyword-Set %d/%d: %s"
12745 (- (length org-todo-sets) -1
12746 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12747 (length org-todo-sets)
12748 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12749 (setq org-last-todo-state-is-todo
12750 (not (member org-state org-done-keywords)))
12751 (setq now-done-p (and (member org-state org-done-keywords)
12752 (not (member this org-done-keywords))))
12753 (and logging (org-local-logging logging))
12754 (when (and (or org-todo-log-states org-log-done)
12755 (not (eq org-inhibit-logging t))
12756 (not (memq arg '(nextset previousset))))
12757 ;; we need to look at recording a time and note
12758 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12759 (nth 2 (assoc this org-todo-log-states))))
12760 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12761 (setq dolog 'time))
12762 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12763 (and org-state
12764 (member org-state org-not-done-keywords)
12765 (not (member this org-not-done-keywords))))
12766 ;; This is now a todo state and was not one before
12767 ;; If there was a CLOSED time stamp, get rid of it.
12768 (org-add-planning-info nil nil 'closed))
12769 (when (and now-done-p org-log-done)
12770 ;; It is now done, and it was not done before
12771 (org-add-planning-info 'closed (org-current-effective-time))
12772 (when (and (not dolog) (eq 'note org-log-done))
12773 (org-add-log-setup 'done org-state this 'note)))
12774 (when (and org-state dolog)
12775 ;; This is a non-nil state, and we need to log it
12776 (org-add-log-setup 'state org-state this dolog)))
12777 ;; Fixup tag positioning
12778 (org-todo-trigger-tag-changes org-state)
12779 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12780 (when org-provide-todo-statistics
12781 (org-update-parent-todo-statistics))
12782 (run-hooks 'org-after-todo-state-change-hook)
12783 (when (and arg (not (member org-state org-done-keywords)))
12784 (setq head (org-get-todo-sequence-head org-state)))
12785 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12786 ;; Do we need to trigger a repeat?
12787 (when now-done-p
12788 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12789 ;; This is for the agenda, take a snapshot of the headline.
12790 (save-match-data
12791 (setq org-agenda-headline-snapshot-before-repeat
12792 (org-get-heading))))
12793 (org-auto-repeat-maybe org-state))
12794 ;; Fixup cursor location if close to the keyword
12795 (when (and (outline-on-heading-p)
12796 (not (bolp))
12797 (save-excursion (beginning-of-line 1)
12798 (looking-at org-todo-line-regexp))
12799 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12800 (goto-char (or (match-end 2) (match-end 1)))
12801 (and (looking-at " ") (just-one-space)))
12802 (when org-trigger-hook
12803 (save-excursion
12804 (run-hook-with-args 'org-trigger-hook change-plist)))
12805 (when commentp (org-toggle-comment))))))))
12807 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12808 "Block turning an entry into a TODO, using the hierarchy.
12809 This checks whether the current task should be blocked from state
12810 changes. Such blocking occurs when:
12812 1. The task has children which are not all in a completed state.
12814 2. A task has a parent with the property :ORDERED:, and there
12815 are siblings prior to the current task with incomplete
12816 status.
12818 3. The parent of the task is blocked because it has siblings that should
12819 be done first, or is child of a block grandparent TODO entry."
12821 (if (not org-enforce-todo-dependencies)
12822 t ; if locally turned off don't block
12823 (catch 'dont-block
12824 ;; If this is not a todo state change, or if this entry is already DONE,
12825 ;; do not block
12826 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12827 (member (plist-get change-plist :from)
12828 (cons 'done org-done-keywords))
12829 (member (plist-get change-plist :to)
12830 (cons 'todo org-not-done-keywords))
12831 (not (plist-get change-plist :to)))
12832 (throw 'dont-block t))
12833 ;; If this task has children, and any are undone, it's blocked
12834 (save-excursion
12835 (org-back-to-heading t)
12836 (let ((this-level (funcall outline-level)))
12837 (outline-next-heading)
12838 (let ((child-level (funcall outline-level)))
12839 (while (and (not (eobp))
12840 (> child-level this-level))
12841 ;; this todo has children, check whether they are all
12842 ;; completed
12843 (when (and (not (org-entry-is-done-p))
12844 (org-entry-is-todo-p))
12845 (setq org-block-entry-blocking (org-get-heading))
12846 (throw 'dont-block nil))
12847 (outline-next-heading)
12848 (setq child-level (funcall outline-level))))))
12849 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12850 ;; any previous siblings are undone, it's blocked
12851 (save-excursion
12852 (org-back-to-heading t)
12853 (let* ((pos (point))
12854 (parent-pos (and (org-up-heading-safe) (point))))
12855 (unless parent-pos (throw 'dont-block t)) ; no parent
12856 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12857 (forward-line 1)
12858 (re-search-forward org-not-done-heading-regexp pos t))
12859 (setq org-block-entry-blocking (match-string 0))
12860 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12861 ;; Search further up the hierarchy, to see if an ancestor is blocked
12862 (while t
12863 (goto-char parent-pos)
12864 (unless (looking-at org-not-done-heading-regexp)
12865 (throw 'dont-block t)) ; do not block, parent is not a TODO
12866 (setq pos (point))
12867 (setq parent-pos (and (org-up-heading-safe) (point)))
12868 (unless parent-pos (throw 'dont-block t)) ; no parent
12869 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12870 (forward-line 1)
12871 (re-search-forward org-not-done-heading-regexp pos t)
12872 (setq org-block-entry-blocking (org-get-heading)))
12873 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12875 (defcustom org-track-ordered-property-with-tag nil
12876 "Should the ORDERED property also be shown as a tag?
12877 The ORDERED property decides if an entry should require subtasks to be
12878 completed in sequence. Since a property is not very visible, setting
12879 this option means that toggling the ORDERED property with the command
12880 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12881 not relevant for the behavior, but it makes things more visible.
12883 Note that toggling the tag with tags commands will not change the property
12884 and therefore not influence behavior!
12886 This can be t, meaning the tag ORDERED should be used, It can also be a
12887 string to select a different tag for this task."
12888 :group 'org-todo
12889 :type '(choice
12890 (const :tag "No tracking" nil)
12891 (const :tag "Track with ORDERED tag" t)
12892 (string :tag "Use other tag")))
12894 (defun org-toggle-ordered-property ()
12895 "Toggle the ORDERED property of the current entry.
12896 For better visibility, you can track the value of this property with a tag.
12897 See variable `org-track-ordered-property-with-tag'."
12898 (interactive)
12899 (let* ((t1 org-track-ordered-property-with-tag)
12900 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12901 (save-excursion
12902 (org-back-to-heading)
12903 (if (org-entry-get nil "ORDERED")
12904 (progn
12905 (org-delete-property "ORDERED")
12906 (and tag (org-toggle-tag tag 'off))
12907 (message "Subtasks can be completed in arbitrary order"))
12908 (org-entry-put nil "ORDERED" "t")
12909 (and tag (org-toggle-tag tag 'on))
12910 (message "Subtasks must be completed in sequence")))))
12912 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12913 (defun org-block-todo-from-checkboxes (change-plist)
12914 "Block turning an entry into a TODO, using checkboxes.
12915 This checks whether the current task should be blocked from state
12916 changes because there are unchecked boxes in this entry."
12917 (if (not org-enforce-todo-checkbox-dependencies)
12918 t ; if locally turned off don't block
12919 (catch 'dont-block
12920 ;; If this is not a todo state change, or if this entry is already DONE,
12921 ;; do not block
12922 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12923 (member (plist-get change-plist :from)
12924 (cons 'done org-done-keywords))
12925 (member (plist-get change-plist :to)
12926 (cons 'todo org-not-done-keywords))
12927 (not (plist-get change-plist :to)))
12928 (throw 'dont-block t))
12929 ;; If this task has checkboxes that are not checked, it's blocked
12930 (save-excursion
12931 (org-back-to-heading t)
12932 (let ((beg (point)) end)
12933 (outline-next-heading)
12934 (setq end (point))
12935 (goto-char beg)
12936 (when (org-list-search-forward
12937 (concat (org-item-beginning-re)
12938 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12939 "\\[[- ]\\]")
12940 end t)
12941 (when (boundp 'org-blocked-by-checkboxes)
12942 (setq org-blocked-by-checkboxes t))
12943 (throw 'dont-block nil))))
12944 t))) ; do not block
12946 (defun org-entry-blocked-p ()
12947 "Non-nil if entry at point is blocked."
12948 (and (not (org-entry-get nil "NOBLOCKING"))
12949 (member (org-entry-get nil "TODO") org-not-done-keywords)
12950 (not (run-hook-with-args-until-failure
12951 'org-blocker-hook
12952 (list :type 'todo-state-change
12953 :position (point)
12954 :from 'todo
12955 :to 'done)))))
12957 (defun org-update-statistics-cookies (all)
12958 "Update the statistics cookie, either from TODO or from checkboxes.
12959 This should be called with the cursor in a line with a statistics cookie."
12960 (interactive "P")
12961 (if all
12962 (progn
12963 (org-update-checkbox-count 'all)
12964 (org-map-entries 'org-update-parent-todo-statistics))
12965 (if (not (org-at-heading-p))
12966 (org-update-checkbox-count)
12967 (let ((pos (point-marker))
12968 end l1 l2)
12969 (ignore-errors (org-back-to-heading t))
12970 (if (not (org-at-heading-p))
12971 (org-update-checkbox-count)
12972 (setq l1 (org-outline-level))
12973 (setq end (save-excursion
12974 (outline-next-heading)
12975 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12976 (point)))
12977 (if (and (save-excursion
12978 (re-search-forward
12979 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12980 (not (save-excursion (re-search-forward
12981 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12982 (org-update-checkbox-count)
12983 (if (and l2 (> l2 l1))
12984 (progn
12985 (goto-char end)
12986 (org-update-parent-todo-statistics))
12987 (goto-char pos)
12988 (beginning-of-line 1)
12989 (while (re-search-forward
12990 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12991 (point-at-eol) t)
12992 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12993 (goto-char pos)
12994 (move-marker pos nil)))))
12996 (defvar org-entry-property-inherited-from) ;; defined below
12997 (defun org-update-parent-todo-statistics ()
12998 "Update any statistics cookie in the parent of the current headline.
12999 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13000 the entire subtree and this will travel up the hierarchy and update
13001 statistics everywhere."
13002 (let* ((prop (save-excursion (org-up-heading-safe)
13003 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13004 (recursive (or (not org-hierarchical-todo-statistics)
13005 (and prop (string-match "\\<recursive\\>" prop))))
13006 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13008 (first t)
13009 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13010 level ltoggle l1 new ndel
13011 (cnt-all 0) (cnt-done 0) is-percent kwd
13012 checkbox-beg ov ovs ove cookie-present)
13013 (catch 'exit
13014 (save-excursion
13015 (beginning-of-line 1)
13016 (setq ltoggle (funcall outline-level))
13017 ;; Three situations are to consider:
13019 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13020 ;; to the top-level ancestor on the headline;
13022 ;; 2. If parent has "recursive" property, repeat up to the
13023 ;; headline setting that property, taking inheritance into
13024 ;; account;
13026 ;; 3. Else, move up to direct parent and proceed only once.
13027 (while (and (setq level (org-up-heading-safe))
13028 (or recursive first)
13029 (>= (point) lim))
13030 (setq first nil cookie-present nil)
13031 (unless (and level
13032 (not (string-match
13033 "\\<checkbox\\>"
13034 (downcase (or (org-entry-get nil "COOKIE_DATA")
13035 "")))))
13036 (throw 'exit nil))
13037 (while (re-search-forward box-re (point-at-eol) t)
13038 (setq cnt-all 0 cnt-done 0 cookie-present t)
13039 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13040 (save-match-data
13041 (unless (outline-next-heading) (throw 'exit nil))
13042 (while (and (looking-at org-complex-heading-regexp)
13043 (> (setq l1 (length (match-string 1))) level))
13044 (setq kwd (and (or recursive (= l1 ltoggle))
13045 (match-string 2)))
13046 (if (or (eq org-provide-todo-statistics 'all-headlines)
13047 (and (eq org-provide-todo-statistics t)
13048 (or (member kwd org-done-keywords)))
13049 (and (listp org-provide-todo-statistics)
13050 (stringp (car org-provide-todo-statistics))
13051 (or (member kwd org-provide-todo-statistics)
13052 (member kwd org-done-keywords)))
13053 (and (listp org-provide-todo-statistics)
13054 (listp (car org-provide-todo-statistics))
13055 (or (member kwd (car org-provide-todo-statistics))
13056 (and (member kwd org-done-keywords)
13057 (member kwd (cadr org-provide-todo-statistics))))))
13058 (setq cnt-all (1+ cnt-all))
13059 (and (eq org-provide-todo-statistics t)
13061 (setq cnt-all (1+ cnt-all))))
13062 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13063 (member kwd org-done-keywords))
13064 (and (listp org-provide-todo-statistics)
13065 (listp (car org-provide-todo-statistics))
13066 (member kwd org-done-keywords)
13067 (member kwd (cadr org-provide-todo-statistics)))
13068 (and (listp org-provide-todo-statistics)
13069 (stringp (car org-provide-todo-statistics))
13070 (member kwd org-done-keywords)))
13071 (setq cnt-done (1+ cnt-done)))
13072 (outline-next-heading)))
13073 (setq new
13074 (if is-percent
13075 (format "[%d%%]" (floor (* 100.0 cnt-done)
13076 (max 1 cnt-all)))
13077 (format "[%d/%d]" cnt-done cnt-all))
13078 ndel (- (match-end 0) checkbox-beg))
13079 ;; handle overlays when updating cookie from column view
13080 (when (setq ov (car (overlays-at checkbox-beg)))
13081 (setq ovs (overlay-start ov) ove (overlay-end ov))
13082 (delete-overlay ov))
13083 (goto-char checkbox-beg)
13084 (insert new)
13085 (delete-region (point) (+ (point) ndel))
13086 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13087 (when ov (move-overlay ov ovs ove)))
13088 (when cookie-present
13089 (run-hook-with-args 'org-after-todo-statistics-hook
13090 cnt-done (- cnt-all cnt-done))))))
13091 (run-hooks 'org-todo-statistics-hook)))
13093 (defvar org-after-todo-statistics-hook nil
13094 "Hook that is called after a TODO statistics cookie has been updated.
13095 Each function is called with two arguments: the number of not-done entries
13096 and the number of done entries.
13098 For example, the following function, when added to this hook, will switch
13099 an entry to DONE when all children are done, and back to TODO when new
13100 entries are set to a TODO status. Note that this hook is only called
13101 when there is a statistics cookie in the headline!
13103 \(defun org-summary-todo (n-done n-not-done)
13104 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13105 \(let (org-log-done org-log-states) ; turn off logging
13106 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13109 (defvar org-todo-statistics-hook nil
13110 "Hook that is run whenever Org thinks TODO statistics should be updated.
13111 This hook runs even if there is no statistics cookie present, in which case
13112 `org-after-todo-statistics-hook' would not run.")
13114 (defun org-todo-trigger-tag-changes (state)
13115 "Apply the changes defined in `org-todo-state-tags-triggers'."
13116 (let ((l org-todo-state-tags-triggers)
13117 changes)
13118 (when (or (not state) (equal state ""))
13119 (setq changes (append changes (cdr (assoc "" l)))))
13120 (when (and (stringp state) (> (length state) 0))
13121 (setq changes (append changes (cdr (assoc state l)))))
13122 (when (member state org-not-done-keywords)
13123 (setq changes (append changes (cdr (assoc 'todo l)))))
13124 (when (member state org-done-keywords)
13125 (setq changes (append changes (cdr (assoc 'done l)))))
13126 (dolist (c changes)
13127 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13129 (defun org-local-logging (value)
13130 "Get logging settings from a property VALUE."
13131 ;; Directly set the variables, they are already local.
13132 (setq org-log-done nil
13133 org-log-repeat nil
13134 org-todo-log-states nil)
13135 (dolist (w (org-split-string value))
13136 (let (a)
13137 (cond
13138 ((setq a (assoc w org-startup-options))
13139 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13140 (set (nth 1 a) (nth 2 a))))
13141 ((setq a (org-extract-log-state-settings w))
13142 (and (member (car a) org-todo-keywords-1)
13143 (push a org-todo-log-states)))))))
13145 (defun org-get-todo-sequence-head (kwd)
13146 "Return the head of the TODO sequence to which KWD belongs.
13147 If KWD is not set, check if there is a text property remembering the
13148 right sequence."
13149 (let (p)
13150 (cond
13151 ((not kwd)
13152 (or (get-text-property (point-at-bol) 'org-todo-head)
13153 (progn
13154 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13155 nil (point-at-eol)))
13156 (get-text-property p 'org-todo-head))))
13157 ((not (member kwd org-todo-keywords-1))
13158 (car org-todo-keywords-1))
13159 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13161 (defun org-fast-todo-selection ()
13162 "Fast TODO keyword selection with single keys.
13163 Returns the new TODO keyword, or nil if no state change should occur."
13164 (let* ((fulltable org-todo-key-alist)
13165 (done-keywords org-done-keywords) ;; needed for the faces.
13166 (maxlen (apply 'max (mapcar
13167 (lambda (x)
13168 (if (stringp (car x)) (string-width (car x)) 0))
13169 fulltable)))
13170 (expert nil)
13171 (fwidth (+ maxlen 3 1 3))
13172 (ncol (/ (- (window-width) 4) fwidth))
13173 tg cnt e c tbl
13174 groups ingroup)
13175 (save-excursion
13176 (save-window-excursion
13177 (if expert
13178 (set-buffer (get-buffer-create " *Org todo*"))
13179 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13180 (erase-buffer)
13181 (setq-local org-done-keywords done-keywords)
13182 (setq tbl fulltable cnt 0)
13183 (while (setq e (pop tbl))
13184 (cond
13185 ((equal e '(:startgroup))
13186 (push '() groups) (setq ingroup t)
13187 (unless (= cnt 0)
13188 (setq cnt 0)
13189 (insert "\n"))
13190 (insert "{ "))
13191 ((equal e '(:endgroup))
13192 (setq ingroup nil cnt 0)
13193 (insert "}\n"))
13194 ((equal e '(:newline))
13195 (unless (= cnt 0)
13196 (setq cnt 0)
13197 (insert "\n")
13198 (setq e (car tbl))
13199 (while (equal (car tbl) '(:newline))
13200 (insert "\n")
13201 (setq tbl (cdr tbl)))))
13203 (setq tg (car e) c (cdr e))
13204 (when ingroup (push tg (car groups)))
13205 (setq tg (org-add-props tg nil 'face
13206 (org-get-todo-face tg)))
13207 (when (and (= cnt 0) (not ingroup)) (insert " "))
13208 (insert "[" c "] " tg (make-string
13209 (- fwidth 4 (length tg)) ?\ ))
13210 (when (= (setq cnt (1+ cnt)) ncol)
13211 (insert "\n")
13212 (when ingroup (insert " "))
13213 (setq cnt 0)))))
13214 (insert "\n")
13215 (goto-char (point-min))
13216 (unless expert (org-fit-window-to-buffer))
13217 (message "[a-z..]:Set [SPC]:clear")
13218 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13219 (cond
13220 ((or (= c ?\C-g)
13221 (and (= c ?q) (not (rassoc c fulltable))))
13222 (setq quit-flag t))
13223 ((= c ?\ ) nil)
13224 ((setq e (rassoc c fulltable) tg (car e))
13226 (t (setq quit-flag t)))))))
13228 (defun org-entry-is-todo-p ()
13229 (member (org-get-todo-state) org-not-done-keywords))
13231 (defun org-entry-is-done-p ()
13232 (member (org-get-todo-state) org-done-keywords))
13234 (defun org-get-todo-state ()
13235 "Return the TODO keyword of the current subtree."
13236 (save-excursion
13237 (org-back-to-heading t)
13238 (and (looking-at org-todo-line-regexp)
13239 (match-end 2)
13240 (match-string 2))))
13242 (defun org-at-date-range-p (&optional inactive-ok)
13243 "Non-nil if point is inside a date range.
13245 When optional argument INACTIVE-OK is non-nil, also consider
13246 inactive time ranges.
13248 When this function returns a non-nil value, match data is set
13249 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13250 on INACTIVE-OK."
13251 (interactive)
13252 (save-excursion
13253 (catch 'exit
13254 (let ((pos (point)))
13255 (skip-chars-backward "^[<\r\n")
13256 (skip-chars-backward "<[")
13257 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13258 (>= (match-end 0) pos)
13259 (throw 'exit t))
13260 (skip-chars-backward "^<[\r\n")
13261 (skip-chars-backward "<[")
13262 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13263 (>= (match-end 0) pos)
13264 (throw 'exit t)))
13265 nil)))
13267 (defun org-get-repeat (&optional tagline)
13268 "Check if there is a deadline/schedule with repeater in this entry."
13269 (save-match-data
13270 (save-excursion
13271 (org-back-to-heading t)
13272 (and (re-search-forward (if tagline
13273 (concat tagline "\\s-*" org-repeat-re)
13274 org-repeat-re)
13275 (org-entry-end-position) t)
13276 (match-string-no-properties 1)))))
13278 (defvar org-last-changed-timestamp)
13279 (defvar org-last-inserted-timestamp)
13280 (defvar org-log-post-message)
13281 (defvar org-log-note-purpose)
13282 (defvar org-log-note-how nil)
13283 (defvar org-log-note-extra)
13284 (defun org-auto-repeat-maybe (done-word)
13285 "Check if the current headline contains a repeated time-stamp.
13287 If yes, set TODO state back to what it was and change the base date
13288 of repeating deadline/scheduled time stamps to new date.
13290 This function is run automatically after each state change to a DONE state."
13291 (let* ((repeat (org-get-repeat))
13292 (aa (assoc org-last-state org-todo-kwd-alist))
13293 (interpret (nth 1 aa))
13294 (head (nth 2 aa))
13295 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13296 (msg "Entry repeats: ")
13297 (org-log-done nil)
13298 (org-todo-log-states nil))
13299 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13300 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13301 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13302 org-todo-repeat-to-state)))
13303 (unless (and to-state (member to-state org-todo-keywords-1))
13304 (setq to-state (if (eq interpret 'type) org-last-state head)))
13305 (org-todo to-state))
13306 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13307 (org-entry-put nil "LAST_REPEAT" (format-time-string
13308 (org-time-stamp-format t t))))
13309 (when org-log-repeat
13310 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13311 (memq 'org-add-log-note post-command-hook))
13312 ;; We are already setup for some record.
13313 (when (eq org-log-repeat 'note)
13314 ;; Make sure we take a note, not only a time stamp.
13315 (setq org-log-note-how 'note))
13316 ;; Set up for taking a record.
13317 (org-add-log-setup 'state
13318 (or done-word (car org-done-keywords))
13319 org-last-state
13320 org-log-repeat)))
13321 (org-back-to-heading t)
13322 (org-add-planning-info nil nil 'closed)
13323 (let ((end (save-excursion (outline-next-heading) (point))))
13324 (while (re-search-forward org-ts-regexp end t)
13325 (when (save-match-data
13326 (or (org-at-planning-p)
13327 (org-at-property-p)
13328 (eq (org-element-type (save-excursion
13329 (backward-char)
13330 (org-element-context)))
13331 'timestamp)))
13332 (let ((type (cond ((match-end 1) org-scheduled-string)
13333 ((match-end 3) org-deadline-string)
13334 (t "Plain:")))
13335 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13336 (cond
13337 ((not
13338 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13339 ;; Time-stamps without a repeater are usually skipped.
13340 ;; However, a SCHEDULED time-stamp without one is
13341 ;; removed, as it is considered as no longer relevant.
13342 (when (equal type org-scheduled-string)
13343 (org-remove-timestamp-with-keyword type)))
13345 (let ((n (string-to-number (match-string 2 ts)))
13346 (what (match-string 3 ts)))
13347 (when (equal what "w") (setq n (* n 7) what "d"))
13348 (when (and (equal what "h")
13349 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13350 ts)))
13351 (user-error
13352 "Cannot repeat in Repeat in %d hour(s) because no hour \
13353 has been set"
13355 ;; Preparation, see if we need to modify the start
13356 ;; date for the change.
13357 (when (match-end 1)
13358 (let ((time (save-match-data (org-time-string-to-time ts))))
13359 (cond
13360 ((equal (match-string 1 ts) ".")
13361 ;; Shift starting date to today
13362 (org-timestamp-change
13363 (- (org-today) (time-to-days time))
13364 'day))
13365 ((equal (match-string 1 ts) "+")
13366 (let ((nshiftmax 10)
13367 (nshift 0))
13368 (while (or (= nshift 0)
13369 (not (time-less-p (current-time) time)))
13370 (when (= (cl-incf nshift) nshiftmax)
13371 (or (y-or-n-p
13372 (format "%d repeater intervals were not \
13373 enough to shift date past today. Continue? "
13374 nshift))
13375 (user-error "Abort")))
13376 (org-timestamp-change n (cdr (assoc what whata)))
13377 (org-at-timestamp-p t)
13378 (setq ts (match-string 1))
13379 (setq time
13380 (save-match-data
13381 (org-time-string-to-time ts)))))
13382 (org-timestamp-change (- n) (cdr (assoc what whata)))
13383 ;; Rematch, so that we have everything in
13384 ;; place for the real shift.
13385 (org-at-timestamp-p t)
13386 (setq ts (match-string 1))
13387 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13388 ts)))))
13389 (save-excursion
13390 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13391 (setq msg
13392 (concat
13393 msg type " " org-last-changed-timestamp " ")))))))))
13394 (setq org-log-post-message msg)
13395 (message "%s" msg))))
13397 (defun org-show-todo-tree (arg)
13398 "Make a compact tree which shows all headlines marked with TODO.
13399 The tree will show the lines where the regexp matches, and all higher
13400 headlines above the match.
13401 With a \\[universal-argument] prefix, prompt for a regexp to match.
13402 With a numeric prefix N, construct a sparse tree for the Nth element
13403 of `org-todo-keywords-1'."
13404 (interactive "P")
13405 (let ((case-fold-search nil)
13406 (kwd-re
13407 (cond ((null arg) org-not-done-regexp)
13408 ((equal arg '(4))
13409 (let ((kwd
13410 (completing-read "Keyword (or KWD1|KWD2|...): "
13411 (mapcar #'list org-todo-keywords-1))))
13412 (concat "\\("
13413 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13414 "\\)\\>")))
13415 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13416 (regexp-quote (nth (1- (prefix-numeric-value arg))
13417 org-todo-keywords-1)))
13418 (t (user-error "Invalid prefix argument: %s" arg)))))
13419 (message "%d TODO entries found"
13420 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13422 (defun org-deadline (arg &optional time)
13423 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13424 With one universal prefix argument, remove any deadline from the item.
13425 With two universal prefix arguments, prompt for a warning delay.
13426 With argument TIME, set the deadline at the corresponding date. TIME
13427 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13428 (interactive "P")
13429 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13430 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13431 'region-start-level 'region))
13432 org-loop-over-headlines-in-active-region)
13433 (org-map-entries
13434 `(org-deadline ',arg ,time)
13435 org-loop-over-headlines-in-active-region
13436 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13437 (let* ((old-date (org-entry-get nil "DEADLINE"))
13438 (old-date-time (when old-date (org-time-string-to-time old-date)))
13439 (repeater (and old-date
13440 (string-match
13441 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13442 old-date)
13443 (match-string 1 old-date))))
13444 (cond
13445 ((equal arg '(4))
13446 (when (and old-date org-log-redeadline)
13447 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13448 (org-remove-timestamp-with-keyword org-deadline-string)
13449 (message "Item no longer has a deadline."))
13450 ((equal arg '(16))
13451 (save-excursion
13452 (org-back-to-heading t)
13453 (if (re-search-forward
13454 org-deadline-time-regexp
13455 (save-excursion (outline-next-heading) (point)) t)
13456 (let* ((rpl0 (match-string 1))
13457 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13458 (replace-match
13459 (concat org-deadline-string
13460 " <" rpl
13461 (format " -%dd"
13462 (abs
13463 (- (time-to-days
13464 (save-match-data
13465 (org-read-date nil t nil "Warn starting from" old-date-time)))
13466 (time-to-days old-date-time))))
13467 ">") t t))
13468 (user-error "No deadline information to update"))))
13470 (org-add-planning-info 'deadline time 'closed)
13471 (when (and old-date
13472 org-log-redeadline
13473 (not (equal old-date org-last-inserted-timestamp)))
13474 (org-add-log-setup
13475 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13476 (when repeater
13477 (save-excursion
13478 (org-back-to-heading t)
13479 (when (re-search-forward (concat org-deadline-string " "
13480 org-last-inserted-timestamp)
13481 (save-excursion
13482 (outline-next-heading) (point)) t)
13483 (goto-char (1- (match-end 0)))
13484 (insert " " repeater)
13485 (setq org-last-inserted-timestamp
13486 (concat (substring org-last-inserted-timestamp 0 -1)
13487 " " repeater
13488 (substring org-last-inserted-timestamp -1))))))
13489 (message "Deadline on %s" org-last-inserted-timestamp))))))
13491 (defun org-schedule (arg &optional time)
13492 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13493 With one universal prefix argument, remove any scheduling date from the item.
13494 With two universal prefix arguments, prompt for a delay cookie.
13495 With argument TIME, scheduled at the corresponding date. TIME can
13496 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13497 (interactive "P")
13498 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13499 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13500 'region-start-level 'region))
13501 org-loop-over-headlines-in-active-region)
13502 (org-map-entries
13503 `(org-schedule ',arg ,time)
13504 org-loop-over-headlines-in-active-region
13505 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13506 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13507 (old-date-time (when old-date (org-time-string-to-time old-date)))
13508 (repeater (and old-date
13509 (string-match
13510 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13511 old-date)
13512 (match-string 1 old-date))))
13513 (cond
13514 ((equal arg '(4))
13515 (progn
13516 (when (and old-date org-log-reschedule)
13517 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13518 (org-remove-timestamp-with-keyword org-scheduled-string)
13519 (message "Item is no longer scheduled.")))
13520 ((equal arg '(16))
13521 (save-excursion
13522 (org-back-to-heading t)
13523 (if (re-search-forward
13524 org-scheduled-time-regexp
13525 (save-excursion (outline-next-heading) (point)) t)
13526 (let* ((rpl0 (match-string 1))
13527 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13528 (replace-match
13529 (concat org-scheduled-string
13530 " <" rpl
13531 (format " -%dd"
13532 (abs
13533 (- (time-to-days
13534 (save-match-data
13535 (org-read-date nil t nil "Delay until" old-date-time)))
13536 (time-to-days old-date-time))))
13537 ">") t t))
13538 (user-error "No scheduled information to update"))))
13540 (org-add-planning-info 'scheduled time 'closed)
13541 (when (and old-date
13542 org-log-reschedule
13543 (not (equal old-date org-last-inserted-timestamp)))
13544 (org-add-log-setup
13545 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13546 (when repeater
13547 (save-excursion
13548 (org-back-to-heading t)
13549 (when (re-search-forward (concat org-scheduled-string " "
13550 org-last-inserted-timestamp)
13551 (save-excursion
13552 (outline-next-heading) (point)) t)
13553 (goto-char (1- (match-end 0)))
13554 (insert " " repeater)
13555 (setq org-last-inserted-timestamp
13556 (concat (substring org-last-inserted-timestamp 0 -1)
13557 " " repeater
13558 (substring org-last-inserted-timestamp -1))))))
13559 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13561 (defun org-get-scheduled-time (pom &optional inherit)
13562 "Get the scheduled time as a time tuple, of a format suitable
13563 for calling org-schedule with, or if there is no scheduling,
13564 returns nil."
13565 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13566 (when time
13567 (apply 'encode-time (org-parse-time-string time)))))
13569 (defun org-get-deadline-time (pom &optional inherit)
13570 "Get the deadline as a time tuple, of a format suitable for
13571 calling org-deadline with, or if there is no scheduling, returns
13572 nil."
13573 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13574 (when time
13575 (apply 'encode-time (org-parse-time-string time)))))
13577 (defun org-remove-timestamp-with-keyword (keyword)
13578 "Remove all time stamps with KEYWORD in the current entry."
13579 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13580 beg)
13581 (save-excursion
13582 (org-back-to-heading t)
13583 (setq beg (point))
13584 (outline-next-heading)
13585 (while (re-search-backward re beg t)
13586 (replace-match "")
13587 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13588 (equal (char-before) ?\ ))
13589 (backward-delete-char 1)
13590 (when (string-match "^[ \t]*$" (buffer-substring
13591 (point-at-bol) (point-at-eol)))
13592 (delete-region (point-at-bol)
13593 (min (point-max) (1+ (point-at-eol))))))))))
13595 (defvar org-time-was-given) ; dynamically scoped parameter
13596 (defvar org-end-time-was-given) ; dynamically scoped parameter
13598 (defun org-at-planning-p ()
13599 "Non-nil when point is on a planning info line."
13600 ;; This is as accurate and faster than `org-element-at-point' since
13601 ;; planning info location is fixed in the section.
13602 (org-with-wide-buffer
13603 (beginning-of-line)
13604 (and (looking-at-p org-planning-line-re)
13605 (eq (point)
13606 (ignore-errors
13607 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13608 (org-back-to-heading t)
13609 (org-with-limited-levels (org-back-to-heading t)))
13610 (line-beginning-position 2))))))
13612 (defun org-add-planning-info (what &optional time &rest remove)
13613 "Insert new timestamp with keyword in the planning line.
13614 WHAT indicates what kind of time stamp to add. It is a symbol
13615 among `closed', `deadline', `scheduled' and nil. TIME indicates
13616 the time to use. If none is given, the user is prompted for
13617 a date. REMOVE indicates what kind of entries to remove. An old
13618 WHAT entry will also be removed."
13619 (let (org-time-was-given org-end-time-was-given default-time default-input)
13620 (catch 'exit
13621 (when (and (memq what '(scheduled deadline))
13622 (or (not time)
13623 (and (stringp time)
13624 (string-match "^[-+]+[0-9]" time))))
13625 ;; Try to get a default date/time from existing timestamp
13626 (save-excursion
13627 (org-back-to-heading t)
13628 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13629 (when (re-search-forward (if (eq what 'scheduled)
13630 org-scheduled-time-regexp
13631 org-deadline-time-regexp)
13632 end t)
13633 (setq ts (match-string 1)
13634 default-time (apply 'encode-time (org-parse-time-string ts))
13635 default-input (and ts (org-get-compact-tod ts)))))))
13636 (when what
13637 (setq time
13638 (if (stringp time)
13639 ;; This is a string (relative or absolute), set
13640 ;; proper date.
13641 (apply #'encode-time
13642 (org-read-date-analyze
13643 time default-time (decode-time default-time)))
13644 ;; If necessary, get the time from the user
13645 (or time (org-read-date nil 'to-time nil nil
13646 default-time default-input)))))
13648 (org-with-wide-buffer
13649 (org-back-to-heading t)
13650 (forward-line)
13651 (unless (bolp) (insert "\n"))
13652 (cond ((looking-at-p org-planning-line-re)
13653 ;; Move to current indentation.
13654 (skip-chars-forward " \t")
13655 ;; Check if we have to remove something.
13656 (dolist (type (if what (cons what remove) remove))
13657 (save-excursion
13658 (when (re-search-forward
13659 (cl-case type
13660 (closed org-closed-time-regexp)
13661 (deadline org-deadline-time-regexp)
13662 (scheduled org-scheduled-time-regexp)
13663 (otherwise
13664 (error "Invalid planning type: %s" type)))
13665 (line-end-position) t)
13666 ;; Delete until next keyword or end of line.
13667 (delete-region
13668 (match-beginning 0)
13669 (if (re-search-forward org-keyword-time-not-clock-regexp
13670 (line-end-position)
13672 (match-beginning 0)
13673 (line-end-position))))))
13674 ;; If there is nothing more to add and no more keyword
13675 ;; is left, remove the line completely.
13676 (if (and (looking-at-p "[ \t]*$") (not what))
13677 (delete-region (line-beginning-position)
13678 (line-beginning-position 2))
13679 ;; If we removed last keyword, do not leave trailing
13680 ;; white space at the end of line.
13681 (let ((p (point)))
13682 (save-excursion
13683 (end-of-line)
13684 (unless (= (skip-chars-backward " \t" p) 0)
13685 (delete-region (point) (line-end-position)))))))
13686 ((not what) (throw 'exit nil)) ; Nothing to do.
13687 (t (insert-before-markers "\n")
13688 (backward-char 1)
13689 (when org-adapt-indentation
13690 (indent-to-column (1+ (org-outline-level))))))
13691 (when what
13692 ;; Insert planning keyword.
13693 (insert (cl-case what
13694 (closed org-closed-string)
13695 (deadline org-deadline-string)
13696 (scheduled org-scheduled-string)
13697 (otherwise (error "Invalid planning type: %s" what)))
13698 " ")
13699 ;; Insert associated timestamp.
13700 (let ((ts (org-insert-time-stamp
13701 time
13702 (or org-time-was-given
13703 (and (eq what 'closed) org-log-done-with-time))
13704 (eq what 'closed)
13705 nil nil (list org-end-time-was-given))))
13706 (unless (eolp) (insert " "))
13707 ts))))))
13709 (defvar org-log-note-marker (make-marker)
13710 "Marker pointing at the entry where the note is to be inserted.")
13711 (defvar org-log-note-purpose nil)
13712 (defvar org-log-note-state nil)
13713 (defvar org-log-note-previous-state nil)
13714 (defvar org-log-note-extra nil)
13715 (defvar org-log-note-window-configuration nil)
13716 (defvar org-log-note-return-to (make-marker))
13717 (defvar org-log-note-effective-time nil
13718 "Remembered current time so that dynamically scoped
13719 `org-extend-today-until' affects timestamps in state change log")
13721 (defvar org-log-post-message nil
13722 "Message to be displayed after a log note has been stored.
13723 The auto-repeater uses this.")
13725 (defun org-add-note ()
13726 "Add a note to the current entry.
13727 This is done in the same way as adding a state change note."
13728 (interactive)
13729 (org-add-log-setup 'note))
13731 (defun org-log-beginning (&optional create)
13732 "Return expected start of log notes in current entry.
13733 When optional argument CREATE is non-nil, the function creates
13734 a drawer to store notes, if necessary. Returned position ignores
13735 narrowing."
13736 (org-with-wide-buffer
13737 (let ((drawer (org-log-into-drawer)))
13738 (cond
13739 (drawer
13740 (org-end-of-meta-data)
13741 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13742 (end (if (org-at-heading-p) (point)
13743 (save-excursion (outline-next-heading) (point))))
13744 (case-fold-search t))
13745 (catch 'exit
13746 ;; Try to find existing drawer.
13747 (while (re-search-forward regexp end t)
13748 (let ((element (org-element-at-point)))
13749 (when (eq (org-element-type element) 'drawer)
13750 (let ((cend (org-element-property :contents-end element)))
13751 (when (and (not org-log-states-order-reversed) cend)
13752 (goto-char cend)))
13753 (throw 'exit nil))))
13754 ;; No drawer found. Create one, if permitted.
13755 (when create
13756 (unless (bolp) (insert "\n"))
13757 (let ((beg (point)))
13758 (insert ":" drawer ":\n:END:\n")
13759 (org-indent-region beg (point)))
13760 (end-of-line -1)))))
13762 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13763 (skip-chars-forward " \t\n")
13764 (beginning-of-line)
13765 (unless org-log-states-order-reversed
13766 (org-skip-over-state-notes)
13767 (skip-chars-backward " \t\n")
13768 (forward-line)))))
13769 (if (bolp) (point) (line-beginning-position 2))))
13771 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13772 "Set up the post command hook to take a note.
13773 If this is about to TODO state change, the new state is expected in STATE.
13774 HOW is an indicator what kind of note should be created.
13775 EXTRA is additional text that will be inserted into the notes buffer."
13776 (move-marker org-log-note-marker (point))
13777 (setq org-log-note-purpose purpose
13778 org-log-note-state state
13779 org-log-note-previous-state prev-state
13780 org-log-note-how how
13781 org-log-note-extra extra
13782 org-log-note-effective-time (org-current-effective-time))
13783 (add-hook 'post-command-hook 'org-add-log-note 'append))
13785 (defun org-skip-over-state-notes ()
13786 "Skip past the list of State notes in an entry."
13787 (when (ignore-errors (goto-char (org-in-item-p)))
13788 (let* ((struct (org-list-struct))
13789 (prevs (org-list-prevs-alist struct))
13790 (regexp
13791 (concat "[ \t]*- +"
13792 (replace-regexp-in-string
13793 " +" " +"
13794 (org-replace-escapes
13795 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13796 `(("%d" . ,org-ts-regexp-inactive)
13797 ("%D" . ,org-ts-regexp)
13798 ("%s" . "\"\\S-+\"")
13799 ("%S" . "\"\\S-+\"")
13800 ("%t" . ,org-ts-regexp-inactive)
13801 ("%T" . ,org-ts-regexp)
13802 ("%u" . ".*?")
13803 ("%U" . ".*?")))))))
13804 (while (looking-at-p regexp)
13805 (goto-char (or (org-list-get-next-item (point) struct prevs)
13806 (org-list-get-item-end (point) struct)))))))
13808 (defun org-add-log-note (&optional _purpose)
13809 "Pop up a window for taking a note, and add this note later."
13810 (remove-hook 'post-command-hook 'org-add-log-note)
13811 (setq org-log-note-window-configuration (current-window-configuration))
13812 (delete-other-windows)
13813 (move-marker org-log-note-return-to (point))
13814 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13815 (goto-char org-log-note-marker)
13816 (org-switch-to-buffer-other-window "*Org Note*")
13817 (erase-buffer)
13818 (if (memq org-log-note-how '(time state))
13819 (let (current-prefix-arg) (org-store-log-note))
13820 (let ((org-inhibit-startup t)) (org-mode))
13821 (insert (format "# Insert note for %s.
13822 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13823 (cond
13824 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13825 ((eq org-log-note-purpose 'done) "closed todo item")
13826 ((eq org-log-note-purpose 'state)
13827 (format "state change from \"%s\" to \"%s\""
13828 (or org-log-note-previous-state "")
13829 (or org-log-note-state "")))
13830 ((eq org-log-note-purpose 'reschedule)
13831 "rescheduling")
13832 ((eq org-log-note-purpose 'delschedule)
13833 "no longer scheduled")
13834 ((eq org-log-note-purpose 'redeadline)
13835 "changing deadline")
13836 ((eq org-log-note-purpose 'deldeadline)
13837 "removing deadline")
13838 ((eq org-log-note-purpose 'refile)
13839 "refiling")
13840 ((eq org-log-note-purpose 'note)
13841 "this entry")
13842 (t (error "This should not happen")))))
13843 (when org-log-note-extra (insert org-log-note-extra))
13844 (setq-local org-finish-function 'org-store-log-note)
13845 (run-hooks 'org-log-buffer-setup-hook)))
13847 (defvar org-note-abort nil) ; dynamically scoped
13848 (defun org-store-log-note ()
13849 "Finish taking a log note, and insert it to where it belongs."
13850 (let ((txt (prog1 (buffer-string)
13851 (kill-buffer)))
13852 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13853 lines)
13854 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13855 (setq txt (replace-match "" t t txt)))
13856 (when (string-match "\\s-+\\'" txt)
13857 (setq txt (replace-match "" t t txt)))
13858 (setq lines (org-split-string txt "\n"))
13859 (when (org-string-nw-p note)
13860 (setq note
13861 (org-replace-escapes
13862 note
13863 (list (cons "%u" (user-login-name))
13864 (cons "%U" user-full-name)
13865 (cons "%t" (format-time-string
13866 (org-time-stamp-format 'long 'inactive)
13867 org-log-note-effective-time))
13868 (cons "%T" (format-time-string
13869 (org-time-stamp-format 'long nil)
13870 org-log-note-effective-time))
13871 (cons "%d" (format-time-string
13872 (org-time-stamp-format nil 'inactive)
13873 org-log-note-effective-time))
13874 (cons "%D" (format-time-string
13875 (org-time-stamp-format nil nil)
13876 org-log-note-effective-time))
13877 (cons "%s" (cond
13878 ((not org-log-note-state) "")
13879 ((string-match-p org-ts-regexp
13880 org-log-note-state)
13881 (format "\"[%s]\""
13882 (substring org-log-note-state 1 -1)))
13883 (t (format "\"%s\"" org-log-note-state))))
13884 (cons "%S"
13885 (cond
13886 ((not org-log-note-previous-state) "")
13887 ((string-match-p org-ts-regexp
13888 org-log-note-previous-state)
13889 (format "\"[%s]\""
13890 (substring
13891 org-log-note-previous-state 1 -1)))
13892 (t (format "\"%s\""
13893 org-log-note-previous-state)))))))
13894 (when lines (setq note (concat note " \\\\")))
13895 (push note lines))
13896 (when (and lines (not (or current-prefix-arg org-note-abort)))
13897 (with-current-buffer (marker-buffer org-log-note-marker)
13898 (org-with-wide-buffer
13899 ;; Find location for the new note.
13900 (goto-char org-log-note-marker)
13901 (set-marker org-log-note-marker nil)
13902 (goto-char (org-log-beginning t))
13903 ;; Make sure point is at the beginning of an empty line.
13904 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13905 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13906 ;; In an existing list, add a new item at the top level.
13907 ;; Otherwise, indent line like a regular one.
13908 (let ((itemp (org-in-item-p)))
13909 (if itemp
13910 (indent-line-to
13911 (let ((struct (save-excursion
13912 (goto-char itemp) (org-list-struct))))
13913 (org-list-get-ind (org-list-get-top-point struct) struct)))
13914 (org-indent-line)))
13915 (insert (org-list-bullet-string "-") (pop lines))
13916 (let ((ind (org-list-item-body-column (line-beginning-position))))
13917 (dolist (line lines)
13918 (insert "\n")
13919 (indent-line-to ind)
13920 (insert line)))
13921 (message "Note stored")
13922 (org-back-to-heading t)
13923 (org-cycle-hide-drawers 'children))
13924 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13925 ;; from within `org-add-log-note' because `buffer-undo-list'
13926 ;; is then modified outside of `org-with-remote-undo'.
13927 (when (eq this-command 'org-agenda-todo)
13928 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13929 ;; Don't add undo information when called from `org-agenda-todo'.
13930 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13931 (set-window-configuration org-log-note-window-configuration)
13932 (with-current-buffer (marker-buffer org-log-note-return-to)
13933 (goto-char org-log-note-return-to))
13934 (move-marker org-log-note-return-to nil)
13935 (when org-log-post-message (message "%s" org-log-post-message))))
13937 (defun org-remove-empty-drawer-at (pos)
13938 "Remove an empty drawer at position POS.
13939 POS may also be a marker."
13940 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13941 (org-with-wide-buffer
13942 (goto-char pos)
13943 (let ((drawer (org-element-at-point)))
13944 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13945 (not (org-element-property :contents-begin drawer)))
13946 (delete-region (org-element-property :begin drawer)
13947 (progn (goto-char (org-element-property :end drawer))
13948 (skip-chars-backward " \r\t\n")
13949 (forward-line)
13950 (point))))))))
13952 (defvar org-ts-type nil)
13953 (defun org-sparse-tree (&optional arg type)
13954 "Create a sparse tree, prompt for the details.
13955 This command can create sparse trees. You first need to select the type
13956 of match used to create the tree:
13958 t Show all TODO entries.
13959 T Show entries with a specific TODO keyword.
13960 m Show entries selected by a tags/property match.
13961 p Enter a property name and its value (both with completion on existing
13962 names/values) and show entries with that property.
13963 r Show entries matching a regular expression (`/' can be used as well).
13964 b Show deadlines and scheduled items before a date.
13965 a Show deadlines and scheduled items after a date.
13966 d Show deadlines due within `org-deadline-warning-days'.
13967 D Show deadlines and scheduled items between a date range."
13968 (interactive "P")
13969 (setq type (or type org-sparse-tree-default-date-type))
13970 (setq org-ts-type type)
13971 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13972 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13973 \[c]ycle through date types: %s"
13974 (cl-case type
13975 (all "all timestamps")
13976 (scheduled "only scheduled")
13977 (deadline "only deadline")
13978 (active "only active timestamps")
13979 (inactive "only inactive timestamps")
13980 (closed "with a closed time-stamp")
13981 (otherwise "scheduled/deadline")))
13982 (let ((answer (read-char-exclusive)))
13983 (cl-case answer
13985 (org-sparse-tree
13987 (cadr
13988 (memq type '(nil all scheduled deadline active inactive closed)))))
13989 (?d (call-interactively 'org-check-deadlines))
13990 (?b (call-interactively 'org-check-before-date))
13991 (?a (call-interactively 'org-check-after-date))
13992 (?D (call-interactively 'org-check-dates-range))
13993 (?t (call-interactively 'org-show-todo-tree))
13994 (?T (org-show-todo-tree '(4)))
13995 (?m (call-interactively 'org-match-sparse-tree))
13996 ((?p ?P)
13997 (let* ((kwd (completing-read
13998 "Property: " (mapcar #'list (org-buffer-property-keys))))
13999 (value (completing-read
14000 "Value: " (mapcar #'list (org-property-values kwd)))))
14001 (unless (string-match "\\`{.*}\\'" value)
14002 (setq value (concat "\"" value "\"")))
14003 (org-match-sparse-tree arg (concat kwd "=" value))))
14004 ((?r ?R ?/) (call-interactively 'org-occur))
14005 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14007 (defvar-local org-occur-highlights nil
14008 "List of overlays used for occur matches.")
14009 (defvar-local org-occur-parameters nil
14010 "Parameters of the active org-occur calls.
14011 This is a list, each call to org-occur pushes as cons cell,
14012 containing the regular expression and the callback, onto the list.
14013 The list can contain several entries if `org-occur' has been called
14014 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14015 will only contain one set of parameters. When the highlights are
14016 removed (for example with `C-c C-c', or with the next edit (depending
14017 on `org-remove-highlights-with-change'), this variable is emptied
14018 as well.")
14020 (defun org-occur (regexp &optional keep-previous callback)
14021 "Make a compact tree which shows all matches of REGEXP.
14023 The tree will show the lines where the regexp matches, and any other context
14024 defined in `org-show-context-detail', which see.
14026 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14027 done by a previous call to `org-occur' will be kept, to allow stacking of
14028 calls to this command.
14030 Optional argument CALLBACK can be a function of no argument. In this case,
14031 it is called with point at the end of the match, match data being set
14032 accordingly. Current match is shown only if the return value is non-nil.
14033 The function must neither move point nor alter narrowing."
14034 (interactive "sRegexp: \nP")
14035 (when (equal regexp "")
14036 (user-error "Regexp cannot be empty"))
14037 (unless keep-previous
14038 (org-remove-occur-highlights nil nil t))
14039 (push (cons regexp callback) org-occur-parameters)
14040 (let ((cnt 0))
14041 (save-excursion
14042 (goto-char (point-min))
14043 (when (or (not keep-previous) ; do not want to keep
14044 (not org-occur-highlights)) ; no previous matches
14045 ;; hide everything
14046 (org-overview))
14047 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14048 (isearch-no-upper-case-p regexp t)
14049 org-occur-case-fold-search)))
14050 (while (re-search-forward regexp nil t)
14051 (when (or (not callback)
14052 (save-match-data (funcall callback)))
14053 (setq cnt (1+ cnt))
14054 (when org-highlight-sparse-tree-matches
14055 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14056 (org-show-context 'occur-tree)))))
14057 (when org-remove-highlights-with-change
14058 (add-hook 'before-change-functions 'org-remove-occur-highlights
14059 nil 'local))
14060 (unless org-sparse-tree-open-archived-trees
14061 (org-hide-archived-subtrees (point-min) (point-max)))
14062 (run-hooks 'org-occur-hook)
14063 (when (called-interactively-p 'interactive)
14064 (message "%d match(es) for regexp %s" cnt regexp))
14065 cnt))
14067 (defun org-occur-next-match (&optional n _reset)
14068 "Function for `next-error-function' to find sparse tree matches.
14069 N is the number of matches to move, when negative move backwards.
14070 This function always goes back to the starting point when no
14071 match is found."
14072 (let* ((limit (if (< n 0) (point-min) (point-max)))
14073 (search-func (if (< n 0)
14074 'previous-single-char-property-change
14075 'next-single-char-property-change))
14076 (n (abs n))
14077 (pos (point))
14079 (catch 'exit
14080 (while (setq p1 (funcall search-func (point) 'org-type))
14081 (when (equal p1 limit)
14082 (goto-char pos)
14083 (user-error "No more matches"))
14084 (when (equal (get-char-property p1 'org-type) 'org-occur)
14085 (setq n (1- n))
14086 (when (= n 0)
14087 (goto-char p1)
14088 (throw 'exit (point))))
14089 (goto-char p1))
14090 (goto-char p1)
14091 (user-error "No more matches"))))
14093 (defun org-show-context (&optional key)
14094 "Make sure point and context are visible.
14095 Optional argument KEY, when non-nil, is a symbol. See
14096 `org-show-context-detail' for allowed values and how much is to
14097 be shown."
14098 (org-show-set-visibility
14099 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14100 ((cdr (assq key org-show-context-detail)))
14101 (t (cdr (assq 'default org-show-context-detail))))))
14103 (defun org-show-set-visibility (detail)
14104 "Set visibility around point according to DETAIL.
14105 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14106 `tree', `canonical' or t. See `org-show-context-detail' for more
14107 information."
14108 ;; Show current heading and possibly its entry, following headline
14109 ;; or all children.
14110 (if (and (org-at-heading-p) (not (eq detail 'local)))
14111 (org-flag-heading nil)
14112 (org-show-entry)
14113 ;; If point is hidden within a drawer or a block, make sure to
14114 ;; expose it.
14115 (dolist (o (overlays-at (point)))
14116 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14117 (delete-overlay o)))
14118 (unless (org-before-first-heading-p)
14119 (org-with-limited-levels
14120 (cl-case detail
14121 ((tree canonical t) (org-show-children))
14122 ((nil minimal ancestors))
14123 (t (save-excursion
14124 (outline-next-heading)
14125 (org-flag-heading nil)))))))
14126 ;; Show all siblings.
14127 (when (eq detail 'lineage) (org-show-siblings))
14128 ;; Show ancestors, possibly with their children.
14129 (when (memq detail '(ancestors lineage tree canonical t))
14130 (save-excursion
14131 (while (org-up-heading-safe)
14132 (org-flag-heading nil)
14133 (when (memq detail '(canonical t)) (org-show-entry))
14134 (when (memq detail '(tree canonical t)) (org-show-children))))))
14136 (defvar org-reveal-start-hook nil
14137 "Hook run before revealing a location.")
14139 (defun org-reveal (&optional siblings)
14140 "Show current entry, hierarchy above it, and the following headline.
14142 This can be used to show a consistent set of context around
14143 locations exposed with `org-show-context'.
14145 With optional argument SIBLINGS, on each level of the hierarchy all
14146 siblings are shown. This repairs the tree structure to what it would
14147 look like when opened with hierarchical calls to `org-cycle'.
14149 With double optional argument \\[universal-argument] \\[universal-argument], \
14150 go to the parent and show the
14151 entire tree."
14152 (interactive "P")
14153 (run-hooks 'org-reveal-start-hook)
14154 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14155 ((equal siblings '(16))
14156 (save-excursion
14157 (when (org-up-heading-safe)
14158 (org-show-subtree)
14159 (run-hook-with-args 'org-cycle-hook 'subtree))))
14160 (t (org-show-set-visibility 'lineage))))
14162 (defun org-highlight-new-match (beg end)
14163 "Highlight from BEG to END and mark the highlight is an occur headline."
14164 (let ((ov (make-overlay beg end)))
14165 (overlay-put ov 'face 'secondary-selection)
14166 (overlay-put ov 'org-type 'org-occur)
14167 (push ov org-occur-highlights)))
14169 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14170 "Remove the occur highlights from the buffer.
14171 BEG and END are ignored. If NOREMOVE is nil, remove this function
14172 from the `before-change-functions' in the current buffer."
14173 (interactive)
14174 (unless org-inhibit-highlight-removal
14175 (mapc #'delete-overlay org-occur-highlights)
14176 (setq org-occur-highlights nil)
14177 (setq org-occur-parameters nil)
14178 (unless noremove
14179 (remove-hook 'before-change-functions
14180 'org-remove-occur-highlights 'local))))
14182 ;;;; Priorities
14184 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14185 "Regular expression matching the priority indicator.")
14187 (defvar org-remove-priority-next-time nil)
14189 (defun org-priority-up ()
14190 "Increase the priority of the current item."
14191 (interactive)
14192 (org-priority 'up))
14194 (defun org-priority-down ()
14195 "Decrease the priority of the current item."
14196 (interactive)
14197 (org-priority 'down))
14199 (defun org-priority (&optional action _show)
14200 "Change the priority of an item.
14201 ACTION can be `set', `up', `down', or a character."
14202 (interactive "P")
14203 (if (equal action '(4))
14204 (org-show-priority)
14205 (unless org-enable-priority-commands
14206 (user-error "Priority commands are disabled"))
14207 (setq action (or action 'set))
14208 (let (current new news have remove)
14209 (save-excursion
14210 (org-back-to-heading t)
14211 (when (looking-at org-priority-regexp)
14212 (setq current (string-to-char (match-string 2))
14213 have t))
14214 (cond
14215 ((eq action 'remove)
14216 (setq remove t new ?\ ))
14217 ((or (eq action 'set)
14218 (integerp action))
14219 (if (not (eq action 'set))
14220 (setq new action)
14221 (message "Priority %c-%c, SPC to remove: "
14222 org-highest-priority org-lowest-priority)
14223 (save-match-data
14224 (setq new (read-char-exclusive))))
14225 (when (and (= (upcase org-highest-priority) org-highest-priority)
14226 (= (upcase org-lowest-priority) org-lowest-priority))
14227 (setq new (upcase new)))
14228 (cond ((equal new ?\ ) (setq remove t))
14229 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14230 (user-error "Priority must be between `%c' and `%c'"
14231 org-highest-priority org-lowest-priority))))
14232 ((eq action 'up)
14233 (setq new (if have
14234 (1- current) ; normal cycling
14235 ;; last priority was empty
14236 (if (eq last-command this-command)
14237 org-lowest-priority ; wrap around empty to lowest
14238 ;; default
14239 (if org-priority-start-cycle-with-default
14240 org-default-priority
14241 (1- org-default-priority))))))
14242 ((eq action 'down)
14243 (setq new (if have
14244 (1+ current) ; normal cycling
14245 ;; last priority was empty
14246 (if (eq last-command this-command)
14247 org-highest-priority ; wrap around empty to highest
14248 ;; default
14249 (if org-priority-start-cycle-with-default
14250 org-default-priority
14251 (1+ org-default-priority))))))
14252 (t (user-error "Invalid action")))
14253 (when (or (< (upcase new) org-highest-priority)
14254 (> (upcase new) org-lowest-priority))
14255 (if (and (memq action '(up down))
14256 (not have) (not (eq last-command this-command)))
14257 ;; `new' is from default priority
14258 (error
14259 "The default can not be set, see `org-default-priority' why")
14260 ;; normal cycling: `new' is beyond highest/lowest priority
14261 ;; and is wrapped around to the empty priority
14262 (setq remove t)))
14263 (setq news (format "%c" new))
14264 (if have
14265 (if remove
14266 (replace-match "" t t nil 1)
14267 (replace-match news t t nil 2))
14268 (if remove
14269 (user-error "No priority cookie found in line")
14270 (let ((case-fold-search nil))
14271 (looking-at org-todo-line-regexp))
14272 (if (match-end 2)
14273 (progn
14274 (goto-char (match-end 2))
14275 (insert " [#" news "]"))
14276 (goto-char (match-beginning 3))
14277 (insert "[#" news "] "))))
14278 (org-set-tags nil 'align))
14279 (if remove
14280 (message "Priority removed")
14281 (message "Priority of current item set to %s" news)))))
14283 (defun org-show-priority ()
14284 "Show the priority of the current item.
14285 This priority is composed of the main priority given with the [#A] cookies,
14286 and by additional input from the age of a schedules or deadline entry."
14287 (interactive)
14288 (let ((pri (if (eq major-mode 'org-agenda-mode)
14289 (org-get-at-bol 'priority)
14290 (save-excursion
14291 (save-match-data
14292 (beginning-of-line)
14293 (and (looking-at org-heading-regexp)
14294 (org-get-priority (match-string 0))))))))
14295 (message "Priority is %d" (if pri pri -1000))))
14297 (defun org-get-priority (s)
14298 "Find priority cookie and return priority."
14299 (save-match-data
14300 (if (functionp org-get-priority-function)
14301 (funcall org-get-priority-function)
14302 (if (not (string-match org-priority-regexp s))
14303 (* 1000 (- org-lowest-priority org-default-priority))
14304 (* 1000 (- org-lowest-priority
14305 (string-to-char (match-string 2 s))))))))
14307 ;;;; Tags
14309 (defvar org-agenda-archives-mode)
14310 (defvar org-map-continue-from nil
14311 "Position from where mapping should continue.
14312 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14314 (defvar org-scanner-tags nil
14315 "The current tag list while the tags scanner is running.")
14317 (defvar org-trust-scanner-tags nil
14318 "Should `org-get-tags-at' use the tags for the scanner.
14319 This is for internal dynamical scoping only.
14320 When this is non-nil, the function `org-get-tags-at' will return the value
14321 of `org-scanner-tags' instead of building the list by itself. This
14322 can lead to large speed-ups when the tags scanner is used in a file with
14323 many entries, and when the list of tags is retrieved, for example to
14324 obtain a list of properties. Building the tags list for each entry in such
14325 a file becomes an N^2 operation - but with this variable set, it scales
14326 as N.")
14328 (defvar org--matcher-tags-todo-only nil)
14330 (defun org-scan-tags (action matcher todo-only &optional start-level)
14331 "Scan headline tags with inheritance and produce output ACTION.
14333 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14334 or `agenda' to produce an entry list for an agenda view. It can also be
14335 a Lisp form or a function that should be called at each matched headline, in
14336 this case the return value is a list of all return values from these calls.
14338 MATCHER is a function accepting three arguments, returning
14339 a non-nil value whenever a given set of tags qualifies a headline
14340 for inclusion. See `org-make-tags-matcher' for more information.
14341 As a special case, it can also be set to t (respectively nil) in
14342 order to match all (respectively none) headline.
14344 When TODO-ONLY is non-nil, only lines with a not-done TODO
14345 keyword are included in the output.
14347 START-LEVEL can be a string with asterisks, reducing the scope to
14348 headlines matching this string."
14349 (require 'org-agenda)
14350 (let* ((re (concat "^"
14351 (if start-level
14352 ;; Get the correct level to match
14353 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14354 org-outline-regexp)
14355 " *\\(\\<\\("
14356 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14357 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14358 (props (list 'face 'default
14359 'done-face 'org-agenda-done
14360 'undone-face 'default
14361 'mouse-face 'highlight
14362 'org-not-done-regexp org-not-done-regexp
14363 'org-todo-regexp org-todo-regexp
14364 'org-complex-heading-regexp org-complex-heading-regexp
14365 'help-echo
14366 (format "mouse-2 or RET jump to org file %s"
14367 (abbreviate-file-name
14368 (or (buffer-file-name (buffer-base-buffer))
14369 (buffer-name (buffer-base-buffer)))))))
14370 (org-map-continue-from nil)
14371 lspos tags tags-list
14372 (tags-alist (list (cons 0 org-file-tags)))
14373 (llast 0) rtn rtn1 level category i txt
14374 todo marker entry priority
14375 ts-date ts-date-type ts-date-pair)
14376 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14377 (setq action (list 'lambda nil action)))
14378 (save-excursion
14379 (goto-char (point-min))
14380 (when (eq action 'sparse-tree)
14381 (org-overview)
14382 (org-remove-occur-highlights))
14383 (while (let (case-fold-search)
14384 (re-search-forward re nil t))
14385 (setq org-map-continue-from nil)
14386 (catch :skip
14387 (setq todo
14388 ;; TODO: is the 1-2 difference a bug?
14389 (when (match-end 1) (match-string-no-properties 2))
14390 tags (when (match-end 4) (match-string-no-properties 4)))
14391 (goto-char (setq lspos (match-beginning 0)))
14392 (setq level (org-reduced-level (org-outline-level))
14393 category (org-get-category))
14394 (when (eq action 'agenda)
14395 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14396 ts-date (car ts-date-pair)
14397 ts-date-type (cdr ts-date-pair)))
14398 (setq i llast llast level)
14399 ;; remove tag lists from same and sublevels
14400 (while (>= i level)
14401 (when (setq entry (assoc i tags-alist))
14402 (setq tags-alist (delete entry tags-alist)))
14403 (setq i (1- i)))
14404 ;; add the next tags
14405 (when tags
14406 (setq tags (org-split-string tags ":")
14407 tags-alist
14408 (cons (cons level tags) tags-alist)))
14409 ;; compile tags for current headline
14410 (setq tags-list
14411 (if org-use-tag-inheritance
14412 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14413 tags)
14414 org-scanner-tags tags-list)
14415 (when org-use-tag-inheritance
14416 (setcdr (car tags-alist)
14417 (mapcar (lambda (x)
14418 (setq x (copy-sequence x))
14419 (org-add-prop-inherited x))
14420 (cdar tags-alist))))
14421 (when (and tags org-use-tag-inheritance
14422 (or (not (eq t org-use-tag-inheritance))
14423 org-tags-exclude-from-inheritance))
14424 ;; Selective inheritance, remove uninherited ones.
14425 (setcdr (car tags-alist)
14426 (org-remove-uninherited-tags (cdar tags-alist))))
14427 (when (and
14429 ;; eval matcher only when the todo condition is OK
14430 (and (or (not todo-only) (member todo org-not-done-keywords))
14431 (if (functionp matcher)
14432 (let ((case-fold-search t) (org-trust-scanner-tags t))
14433 (funcall matcher todo tags-list level))
14434 matcher))
14436 ;; Call the skipper, but return t if it does not
14437 ;; skip, so that the `and' form continues evaluating.
14438 (progn
14439 (unless (eq action 'sparse-tree) (org-agenda-skip))
14442 ;; Check if timestamps are deselecting this entry
14443 (or (not todo-only)
14444 (and (member todo org-not-done-keywords)
14445 (or (not org-agenda-tags-todo-honor-ignore-options)
14446 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14448 ;; select this headline
14449 (cond
14450 ((eq action 'sparse-tree)
14451 (and org-highlight-sparse-tree-matches
14452 (org-get-heading) (match-end 0)
14453 (org-highlight-new-match
14454 (match-beginning 1) (match-end 1)))
14455 (org-show-context 'tags-tree))
14456 ((eq action 'agenda)
14457 (setq txt (org-agenda-format-item
14459 (concat
14460 (if (eq org-tags-match-list-sublevels 'indented)
14461 (make-string (1- level) ?.) "")
14462 (org-get-heading))
14463 (make-string level ?\s)
14464 category
14465 tags-list)
14466 priority (org-get-priority txt))
14467 (goto-char lspos)
14468 (setq marker (org-agenda-new-marker))
14469 (org-add-props txt props
14470 'org-marker marker 'org-hd-marker marker 'org-category category
14471 'todo-state todo
14472 'ts-date ts-date
14473 'priority priority
14474 'type (concat "tagsmatch" ts-date-type))
14475 (push txt rtn))
14476 ((functionp action)
14477 (setq org-map-continue-from nil)
14478 (save-excursion
14479 (setq rtn1 (funcall action))
14480 (push rtn1 rtn)))
14481 (t (user-error "Invalid action")))
14483 ;; if we are to skip sublevels, jump to end of subtree
14484 (unless org-tags-match-list-sublevels
14485 (org-end-of-subtree t)
14486 (backward-char 1))))
14487 ;; Get the correct position from where to continue
14488 (if org-map-continue-from
14489 (goto-char org-map-continue-from)
14490 (and (= (point) lspos) (end-of-line 1)))))
14491 (when (and (eq action 'sparse-tree)
14492 (not org-sparse-tree-open-archived-trees))
14493 (org-hide-archived-subtrees (point-min) (point-max)))
14494 (nreverse rtn)))
14496 (defun org-remove-uninherited-tags (tags)
14497 "Remove all tags that are not inherited from the list TAGS."
14498 (cond
14499 ((eq org-use-tag-inheritance t)
14500 (if org-tags-exclude-from-inheritance
14501 (org-delete-all org-tags-exclude-from-inheritance tags)
14502 tags))
14503 ((not org-use-tag-inheritance) nil)
14504 ((stringp org-use-tag-inheritance)
14505 (delq nil (mapcar
14506 (lambda (x)
14507 (if (and (string-match org-use-tag-inheritance x)
14508 (not (member x org-tags-exclude-from-inheritance)))
14509 x nil))
14510 tags)))
14511 ((listp org-use-tag-inheritance)
14512 (delq nil (mapcar
14513 (lambda (x)
14514 (if (member x org-use-tag-inheritance) x nil))
14515 tags)))))
14517 (defun org-match-sparse-tree (&optional todo-only match)
14518 "Create a sparse tree according to tags string MATCH.
14519 MATCH can contain positive and negative selection of tags, like
14520 \"+WORK+URGENT-WITHBOSS\".
14521 If optional argument TODO-ONLY is non-nil, only select lines that are
14522 also TODO lines."
14523 (interactive "P")
14524 (org-agenda-prepare-buffers (list (current-buffer)))
14525 (let ((org--matcher-tags-todo-only todo-only))
14526 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14527 org--matcher-tags-todo-only)))
14529 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14531 (defvar org-cached-props nil)
14532 (defun org-cached-entry-get (pom property)
14533 (if (or (eq t org-use-property-inheritance)
14534 (and (stringp org-use-property-inheritance)
14535 (let ((case-fold-search t))
14536 (string-match-p org-use-property-inheritance property)))
14537 (and (listp org-use-property-inheritance)
14538 (member-ignore-case property org-use-property-inheritance)))
14539 ;; Caching is not possible, check it directly.
14540 (org-entry-get pom property 'inherit)
14541 ;; Get all properties, so we can do complicated checks easily.
14542 (cdr (assoc-string property
14543 (or org-cached-props
14544 (setq org-cached-props (org-entry-properties pom)))
14545 t))))
14547 (defun org-global-tags-completion-table (&optional files)
14548 "Return the list of all tags in all agenda buffer/files.
14549 Optional FILES argument is a list of files which can be used
14550 instead of the agenda files."
14551 (save-excursion
14552 (org-uniquify
14553 (delq nil
14554 (apply #'append
14555 (mapcar
14556 (lambda (file)
14557 (set-buffer (find-file-noselect file))
14558 (mapcar (lambda (x)
14559 (and (stringp (car-safe x))
14560 (list (car-safe x))))
14561 (or org-current-tag-alist (org-get-buffer-tags))))
14562 (if (car-safe files) files
14563 (org-agenda-files))))))))
14565 (defun org-make-tags-matcher (match)
14566 "Create the TAGS/TODO matcher form for the selection string MATCH.
14568 Returns a cons of the selection string MATCH and a function
14569 implementing the matcher.
14571 The matcher is to be called at an Org entry, with point on the
14572 headline, and returns non-nil if the entry matches the selection
14573 string MATCH. It must be called with three arguments: the TODO
14574 keyword at the entry (or nil if none), the list of all tags at
14575 the entry including inherited ones and the reduced level of the
14576 headline. Additionally, the category of the entry, if any, must
14577 be specified as the text property `org-category' on the headline.
14579 This function sets the variable `org--matcher-tags-todo-only' to
14580 a non-nil value if the matcher restricts matching to TODO
14581 entries, otherwise it is not touched.
14583 See also `org-scan-tags'."
14584 (unless match
14585 ;; Get a new match request, with completion against the global
14586 ;; tags table and the local tags in current buffer.
14587 (let ((org-last-tags-completion-table
14588 (org-uniquify
14589 (delq nil (append (org-get-buffer-tags)
14590 (org-global-tags-completion-table))))))
14591 (setq match
14592 (completing-read
14593 "Match: "
14594 'org-tags-completion-function nil nil nil 'org-tags-history))))
14596 (let ((match0 match)
14597 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14598 (start 0)
14599 tagsmatch todomatch tagsmatcher todomatcher)
14601 ;; Expand group tags.
14602 (setq match (org-tags-expand match))
14604 ;; Check if there is a TODO part of this match, which would be the
14605 ;; part after a "/". To make sure that this slash is not part of
14606 ;; a property value to be matched against, we also check that
14607 ;; there is no / after that slash. First, find the last slash.
14608 (let ((s 0))
14609 (while (string-match "/+" match s)
14610 (setq start (match-beginning 0))
14611 (setq s (match-end 0))))
14612 (if (and (string-match "/+" match start)
14613 (not (string-match-p "\"" match start)))
14614 ;; Match contains also a TODO-matching request.
14615 (progn
14616 (setq tagsmatch (substring match 0 (match-beginning 0)))
14617 (setq todomatch (substring match (match-end 0)))
14618 (when (string-match "\\`!" todomatch)
14619 (setq org--matcher-tags-todo-only t)
14620 (setq todomatch (substring todomatch 1)))
14621 (when (string-match "\\`\\s-*\\'" todomatch)
14622 (setq todomatch nil)))
14623 ;; Only matching tags.
14624 (setq tagsmatch match)
14625 (setq todomatch nil))
14627 ;; Make the tags matcher.
14628 (when (org-string-nw-p tagsmatch)
14629 (let ((orlist nil)
14630 (orterms (org-split-string tagsmatch "|"))
14631 term)
14632 (while (setq term (pop orterms))
14633 (while (and (equal (substring term -1) "\\") orterms)
14634 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14635 (while (string-match re term)
14636 (let* ((rest (substring term (match-end 0)))
14637 (minus (and (match-end 1)
14638 (equal (match-string 1 term) "-")))
14639 (tag (save-match-data
14640 (replace-regexp-in-string
14641 "\\\\-" "-" (match-string 2 term))))
14642 (regexp (eq (string-to-char tag) ?{))
14643 (levelp (match-end 4))
14644 (propp (match-end 5))
14646 (cond
14647 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14648 (levelp
14649 `(,(org-op-to-function (match-string 3 term))
14650 level
14651 ,(string-to-number (match-string 4 term))))
14652 (propp
14653 (let* ((gv (pcase (upcase (match-string 5 term))
14654 ("CATEGORY"
14655 '(get-text-property (point) 'org-category))
14656 ("TODO" 'todo)
14657 (p `(org-cached-entry-get nil ,p))))
14658 (pv (match-string 7 term))
14659 (regexp (eq (string-to-char pv) ?{))
14660 (strp (eq (string-to-char pv) ?\"))
14661 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14662 (po (org-op-to-function (match-string 6 term)
14663 (if timep 'time strp))))
14664 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14665 (when timep (setq pv (org-matcher-time pv)))
14666 (cond ((and regexp (eq po 'org<>))
14667 `(not (string-match ,pv (or ,gv ""))))
14668 (regexp `(string-match ,pv (or ,gv "")))
14669 (strp `(,po (or ,gv "") ,pv))
14671 `(,po
14672 (string-to-number (or ,gv ""))
14673 ,(string-to-number pv))))))
14674 (t `(member ,tag tags-list)))))
14675 (push (if minus `(not ,mm) mm) tagsmatcher)
14676 (setq term rest)))
14677 (push `(and ,@tagsmatcher) orlist)
14678 (setq tagsmatcher nil))
14679 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14681 ;; Make the TODO matcher.
14682 (when (org-string-nw-p todomatch)
14683 (let ((orlist nil))
14684 (dolist (term (org-split-string todomatch "|"))
14685 (while (string-match re term)
14686 (let* ((minus (and (match-end 1)
14687 (equal (match-string 1 term) "-")))
14688 (kwd (match-string 2 term))
14689 (regexp (eq (string-to-char kwd) ?{))
14690 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14691 `(equal todo ,kwd))))
14692 (push (if minus `(not ,mm) mm) todomatcher))
14693 (setq term (substring term (match-end 0))))
14694 (push (if (> (length todomatcher) 1)
14695 (cons 'and todomatcher)
14696 (car todomatcher))
14697 orlist)
14698 (setq todomatcher nil))
14699 (setq todomatcher (cons 'or orlist))))
14701 ;; Return the string and function of the matcher. If no
14702 ;; tags-specific or todo-specific matcher exists, match
14703 ;; everything.
14704 (let ((matcher (if (and tagsmatcher todomatcher)
14705 `(and ,tagsmatcher ,todomatcher)
14706 (or tagsmatcher todomatcher t))))
14707 (when org--matcher-tags-todo-only
14708 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14709 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14711 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14712 "Expand group tags in MATCH.
14714 This replaces every group tag in MATCH with a regexp tag search.
14715 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14716 will be replaced like this:
14718 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14719 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14720 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14722 Replacing by a regexp preserves the structure of the match.
14723 E.g., this expansion
14725 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14727 will match anything tagged with \"Lab\" and \"Home\", or tagged
14728 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14730 A group tag in MATCH can contain regular expressions of its own.
14731 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14732 will be replaced like this:
14734 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14736 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14737 assumed to be a single group tag, and the function will return
14738 the list of tags in this group.
14740 When DOWNCASE is non-nil, expand downcased TAGS."
14741 (if org-group-tags
14742 (let* ((case-fold-search t)
14743 (stable org-mode-syntax-table)
14744 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14745 (taggroups (if downcased
14746 (mapcar (lambda (tg) (mapcar #'downcase tg))
14747 taggroups)
14748 taggroups))
14749 (taggroups-keys (mapcar #'car taggroups))
14750 (return-match (if downcased (downcase match) match))
14751 (count 0)
14752 (work-already-expanded tags-already-expanded)
14753 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14754 ;; @ and _ are allowed as word-components in tags.
14755 (modify-syntax-entry ?@ "w" stable)
14756 (modify-syntax-entry ?_ "w" stable)
14757 ;; Temporarily replace regexp-expressions in the match-expression.
14758 (while (string-match "{.+?}" return-match)
14759 (cl-incf count)
14760 (push (match-string 0 return-match) regexps-in-match)
14761 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14762 (while (and taggroups-keys
14763 (with-syntax-table stable
14764 (string-match
14765 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14766 (regexp-opt taggroups-keys) "\\>\\)")
14767 return-match)))
14768 (let* ((dir (match-string 1 return-match))
14769 (tag (match-string 2 return-match))
14770 (tag (if downcased (downcase tag) tag)))
14771 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14772 (member tag work-already-expanded))
14773 (setq tags-in-group (assoc tag taggroups))
14774 (push tag work-already-expanded)
14775 ;; Recursively expand each tag in the group, if the tag hasn't
14776 ;; already been expanded. Restore the match-data after all recursive calls.
14777 (save-match-data
14778 (let (tags-expanded)
14779 (dolist (x (cdr tags-in-group))
14780 (if (and (member x taggroups-keys)
14781 (not (member x work-already-expanded)))
14782 (setq tags-expanded
14783 (delete-dups
14784 (append
14785 (org-tags-expand x t downcased
14786 work-already-expanded)
14787 tags-expanded)))
14788 (setq tags-expanded
14789 (append (list x) tags-expanded)))
14790 (setq work-already-expanded
14791 (delete-dups
14792 (append tags-expanded
14793 work-already-expanded))))
14794 (setq tags-in-group
14795 (delete-dups (cons (car tags-in-group)
14796 tags-expanded)))))
14797 ;; Filter tag-regexps from tags.
14798 (setq regexp-in-group-escaped
14799 (delq nil (mapcar (lambda (x)
14800 (if (stringp x)
14801 (and (equal "{" (substring x 0 1))
14802 (equal "}" (substring x -1))
14805 tags-in-group))
14806 regexp-in-group
14807 (mapcar (lambda (x)
14808 (substring x 1 -1))
14809 regexp-in-group-escaped)
14810 tags-in-group
14811 (delq nil (mapcar (lambda (x)
14812 (if (stringp x)
14813 (and (not (equal "{" (substring x 0 1)))
14814 (not (equal "}" (substring x -1)))
14817 tags-in-group)))
14818 ;; If single-as-list, do no more in the while-loop.
14819 (if (not single-as-list)
14820 (progn
14821 (when regexp-in-group
14822 (setq regexp-in-group
14823 (concat "\\|"
14824 (mapconcat 'identity regexp-in-group
14825 "\\|"))))
14826 (setq tags-in-group
14827 (concat dir
14828 "{\\<"
14829 (regexp-opt tags-in-group)
14830 "\\>"
14831 regexp-in-group
14832 "}"))
14833 (when (stringp tags-in-group)
14834 (org-add-props tags-in-group '(grouptag t)))
14835 (setq return-match
14836 (replace-match tags-in-group t t return-match)))
14837 (setq tags-in-group
14838 (append regexp-in-group-escaped tags-in-group))))
14839 (setq taggroups-keys (delete tag taggroups-keys))))
14840 ;; Add the regular expressions back into the match-expression again.
14841 (while regexps-in-match
14842 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14843 (pop regexps-in-match)
14844 return-match t t))
14845 (cl-decf count))
14846 (if single-as-list
14847 (if tags-in-group tags-in-group (list return-match))
14848 return-match))
14849 (if single-as-list
14850 (list (if downcased (downcase match) match))
14851 match)))
14853 (defun org-op-to-function (op &optional stringp)
14854 "Turn an operator into the appropriate function."
14855 (setq op
14856 (cond
14857 ((equal op "<" ) '(< string< org-time<))
14858 ((equal op ">" ) '(> org-string> org-time>))
14859 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14860 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14861 ((member op '("=" "==")) '(= string= org-time=))
14862 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14863 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14865 (defun org<> (a b) (not (= a b)))
14866 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14867 (defun org-string>= (a b) (not (string< a b)))
14868 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14869 (defun org-string<> (a b) (not (string= a b)))
14870 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14871 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14872 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14873 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14874 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14875 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14876 (defun org-2ft (s)
14877 "Convert S to a floating point time.
14878 If S is already a number, just return it. If it is a string, parse
14879 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14880 (cond
14881 ((numberp s) s)
14882 ((stringp s)
14883 (condition-case nil
14884 (float-time (apply 'encode-time (org-parse-time-string s)))
14885 (error 0.)))
14886 (t 0.)))
14888 (defun org-time-today ()
14889 "Time in seconds today at 0:00.
14890 Returns the float number of seconds since the beginning of the
14891 epoch to the beginning of today (00:00)."
14892 (float-time (apply 'encode-time
14893 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14895 (defun org-matcher-time (s)
14896 "Interpret a time comparison value."
14897 (save-match-data
14898 (cond
14899 ((string= s "<now>") (float-time))
14900 ((string= s "<today>") (org-time-today))
14901 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14902 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14903 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14904 (+ (org-time-today)
14905 (* (string-to-number (match-string 1 s))
14906 (cdr (assoc (match-string 2 s)
14907 '(("d" . 86400.0) ("w" . 604800.0)
14908 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14909 (t (org-2ft s)))))
14911 (defun org-match-any-p (re list)
14912 "Does re match any element of list?"
14913 (setq list (mapcar (lambda (x) (string-match re x)) list))
14914 (delq nil list))
14916 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14917 (defvar org-tags-overlay (make-overlay 1 1))
14918 (delete-overlay org-tags-overlay)
14920 (defun org-get-local-tags-at (&optional pos)
14921 "Get a list of tags defined in the current headline."
14922 (org-get-tags-at pos 'local))
14924 (defun org-get-local-tags ()
14925 "Get a list of tags defined in the current headline."
14926 (org-get-tags-at nil 'local))
14928 (defun org-get-tags-at (&optional pos local)
14929 "Get a list of all headline tags applicable at POS.
14930 POS defaults to point. If tags are inherited, the list contains
14931 the targets in the same sequence as the headlines appear, i.e.
14932 the tags of the current headline come last.
14933 When LOCAL is non-nil, only return tags from the current headline,
14934 ignore inherited ones."
14935 (interactive)
14936 (if (and org-trust-scanner-tags
14937 (or (not pos) (equal pos (point)))
14938 (not local))
14939 org-scanner-tags
14940 (let (tags ltags lastpos parent)
14941 (save-excursion
14942 (save-restriction
14943 (widen)
14944 (goto-char (or pos (point)))
14945 (save-match-data
14946 (catch 'done
14947 (condition-case nil
14948 (progn
14949 (org-back-to-heading t)
14950 (while (not (equal lastpos (point)))
14951 (setq lastpos (point))
14952 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14953 (setq ltags (org-split-string
14954 (match-string-no-properties 1) ":"))
14955 (when parent
14956 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14957 (setq tags (append
14958 (if parent
14959 (org-remove-uninherited-tags ltags)
14960 ltags)
14961 tags)))
14962 (or org-use-tag-inheritance (throw 'done t))
14963 (when local (throw 'done t))
14964 (or (org-up-heading-safe) (error nil))
14965 (setq parent t)))
14966 (error nil)))))
14967 (if local
14968 tags
14969 (reverse (delete-dups
14970 (reverse (append
14971 (org-remove-uninherited-tags
14972 org-file-tags)
14973 tags)))))))))
14975 (defun org-add-prop-inherited (s)
14976 (add-text-properties 0 (length s) '(inherited t) s)
14979 (defun org-toggle-tag (tag &optional onoff)
14980 "Toggle the tag TAG for the current line.
14981 If ONOFF is `on' or `off', don't toggle but set to this state."
14982 (let (res current)
14983 (save-excursion
14984 (org-back-to-heading t)
14985 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14986 (point-at-eol) t)
14987 (progn
14988 (setq current (match-string 1))
14989 (replace-match ""))
14990 (setq current ""))
14991 (setq current (nreverse (org-split-string current ":")))
14992 (cond
14993 ((eq onoff 'on)
14994 (setq res t)
14995 (or (member tag current) (push tag current)))
14996 ((eq onoff 'off)
14997 (or (not (member tag current)) (setq current (delete tag current))))
14998 (t (if (member tag current)
14999 (setq current (delete tag current))
15000 (setq res t)
15001 (push tag current))))
15002 (end-of-line 1)
15003 (if current
15004 (progn
15005 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15006 (org-set-tags nil t))
15007 (delete-horizontal-space))
15008 (run-hooks 'org-after-tags-change-hook))
15009 res))
15011 (defun org-align-tags-here (to-col)
15012 ;; Assumes that this is a headline
15013 "Align tags on the current headline to TO-COL."
15014 (let ((pos (point)) (col (current-column)) ncol tags-l p)
15015 (beginning-of-line 1)
15016 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15017 (< pos (match-beginning 2)))
15018 (progn
15019 (setq tags-l (string-width (match-string 2)))
15020 (goto-char (match-beginning 1))
15021 (insert " ")
15022 (delete-region (point) (1+ (match-beginning 2)))
15023 (setq ncol (max (current-column)
15024 (1+ col)
15025 (if (> to-col 0)
15026 to-col
15027 (- (abs to-col) tags-l))))
15028 (setq p (point))
15029 (insert (make-string (- ncol (current-column)) ?\ ))
15030 (setq ncol (current-column))
15031 (when indent-tabs-mode (tabify p (point-at-eol)))
15032 (org-move-to-column (min ncol col)))
15033 (goto-char pos))))
15035 (defun org-set-tags-command (&optional arg just-align)
15036 "Call the set-tags command for the current entry."
15037 (interactive "P")
15038 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15039 (org-set-tags arg just-align)
15040 (save-excursion
15041 (unless (and (org-region-active-p)
15042 org-loop-over-headlines-in-active-region)
15043 (org-back-to-heading t))
15044 (org-set-tags arg just-align))))
15046 (defun org-set-tags-to (data)
15047 "Set the tags of the current entry to DATA, replacing the current tags.
15048 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15049 If DATA is nil or the empty string, any tags will be removed."
15050 (interactive "sTags: ")
15051 (setq data
15052 (cond
15053 ((eq data nil) "")
15054 ((equal data "") "")
15055 ((stringp data)
15056 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15057 ":"))
15058 ((listp data)
15059 (concat ":" (mapconcat 'identity data ":") ":"))))
15060 (when data
15061 (save-excursion
15062 (org-back-to-heading t)
15063 (when (looking-at org-complex-heading-regexp)
15064 (if (match-end 5)
15065 (progn
15066 (goto-char (match-beginning 5))
15067 (insert data)
15068 (delete-region (point) (point-at-eol))
15069 (org-set-tags nil 'align))
15070 (goto-char (point-at-eol))
15071 (insert " " data)
15072 (org-set-tags nil 'align)))
15073 (beginning-of-line 1)
15074 (when (looking-at ".*?\\([ \t]+\\)$")
15075 (delete-region (match-beginning 1) (match-end 1))))))
15077 (defun org-align-all-tags ()
15078 "Align the tags in all headings."
15079 (interactive)
15080 (save-excursion
15081 (or (ignore-errors (org-back-to-heading t))
15082 (outline-next-heading))
15083 (if (org-at-heading-p)
15084 (org-set-tags t)
15085 (message "No headings"))))
15087 (defvar org-indent-indentation-per-level)
15088 (defun org-set-tags (&optional arg just-align)
15089 "Set the tags for the current headline.
15090 With prefix ARG, realign all tags in headings in the current buffer.
15091 When JUST-ALIGN is non-nil, only align tags."
15092 (interactive "P")
15093 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15094 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15095 'region-start-level
15096 'region))
15097 org-loop-over-headlines-in-active-region)
15098 (org-map-entries
15099 ;; We don't use ARG and JUST-ALIGN here because these args
15100 ;; are not useful when looping over headlines.
15101 #'org-set-tags
15102 org-loop-over-headlines-in-active-region
15104 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15105 (let ((org-setting-tags t))
15106 (if arg
15107 (save-excursion
15108 (goto-char (point-min))
15109 (while (re-search-forward org-outline-regexp-bol nil t)
15110 (org-set-tags nil t)
15111 (end-of-line))
15112 (message "All tags realigned to column %d" org-tags-column))
15113 (let* ((current (org-get-tags-string))
15114 (col (current-column))
15115 (tags
15116 (if just-align current
15117 ;; Get a new set of tags from the user.
15118 (save-excursion
15119 (let* ((seen)
15120 (table
15121 (setq
15122 org-last-tags-completion-table
15123 ;; Uniquify tags in alists, yet preserve
15124 ;; structure (i.e., keywords).
15125 (delq nil
15126 (mapcar
15127 (lambda (pair)
15128 (let ((head (car pair)))
15129 (cond ((symbolp head) pair)
15130 ((member head seen) nil)
15131 (t (push head seen)
15132 pair))))
15133 (append
15134 (or org-current-tag-alist
15135 (org-get-buffer-tags))
15136 (and
15137 org-complete-tags-always-offer-all-agenda-tags
15138 (org-global-tags-completion-table
15139 (org-agenda-files))))))))
15140 (current-tags (org-split-string current ":"))
15141 (inherited-tags
15142 (nreverse (nthcdr (length current-tags)
15143 (nreverse (org-get-tags-at))))))
15144 (replace-regexp-in-string
15145 "\\([-+&]+\\|,\\)"
15147 (if (or (eq t org-use-fast-tag-selection)
15148 (and org-use-fast-tag-selection
15149 (delq nil (mapcar #'cdr table))))
15150 (org-fast-tag-selection
15151 current-tags inherited-tags table
15152 (and org-fast-tag-selection-include-todo
15153 org-todo-key-alist))
15154 (let ((org-add-colon-after-tag-completion
15155 (< 1 (length table))))
15156 (org-trim
15157 (completing-read
15158 "Tags: "
15159 #'org-tags-completion-function
15160 nil nil current 'org-tags-history))))))))))
15162 (when org-tags-sort-function
15163 (setq tags
15164 (mapconcat
15165 #'identity
15166 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15167 org-tags-sort-function)
15168 ":")))
15170 (if (not (org-string-nw-p tags)) (setq tags "")
15171 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15172 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15174 ;; Insert new tags at the correct column
15175 (beginning-of-line)
15176 (let ((level (if (looking-at org-outline-regexp)
15177 (- (match-end 0) (point) 1)
15178 1)))
15179 (cond
15180 ((and (equal current "") (equal tags "")))
15181 ((re-search-forward
15182 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15183 (line-end-position)
15185 (if (equal tags "") (replace-match "" t t)
15186 (goto-char (match-beginning 0))
15187 (let* ((c0 (current-column))
15188 ;; Compute offset for the case of org-indent-mode
15189 ;; active.
15190 (di (if (bound-and-true-p org-indent-mode)
15191 (* (1- org-indent-indentation-per-level)
15192 (1- level))
15194 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15195 (tc (+ org-tags-column
15196 (if (> org-tags-column 0) (- di) di)))
15197 (c1 (max (1+ c0)
15198 (if (> tc 0) tc
15199 (- (- tc) (string-width tags)))))
15200 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15201 (replace-match rpl t t)
15202 (when indent-tabs-mode (tabify p0 (point))))))
15203 (t (error "Tags alignment failed"))))
15204 (org-move-to-column col))
15205 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15207 (defun org-change-tag-in-region (beg end tag off)
15208 "Add or remove TAG for each entry in the region.
15209 This works in the agenda, and also in an org-mode buffer."
15210 (interactive
15211 (list (region-beginning) (region-end)
15212 (let ((org-last-tags-completion-table
15213 (if (derived-mode-p 'org-mode)
15214 (org-uniquify
15215 (delq nil (append (org-get-buffer-tags)
15216 (org-global-tags-completion-table))))
15217 (org-global-tags-completion-table))))
15218 (completing-read
15219 "Tag: " 'org-tags-completion-function nil nil nil
15220 'org-tags-history))
15221 (progn
15222 (message "[s]et or [r]emove? ")
15223 (equal (read-char-exclusive) ?r))))
15224 (when (fboundp 'deactivate-mark) (deactivate-mark))
15225 (let ((agendap (equal major-mode 'org-agenda-mode))
15226 l1 l2 m buf pos newhead (cnt 0))
15227 (goto-char end)
15228 (setq l2 (1- (org-current-line)))
15229 (goto-char beg)
15230 (setq l1 (org-current-line))
15231 (cl-loop for l from l1 to l2 do
15232 (org-goto-line l)
15233 (setq m (get-text-property (point) 'org-hd-marker))
15234 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15235 (and agendap m))
15236 (setq buf (if agendap (marker-buffer m) (current-buffer))
15237 pos (if agendap m (point)))
15238 (with-current-buffer buf
15239 (save-excursion
15240 (save-restriction
15241 (goto-char pos)
15242 (setq cnt (1+ cnt))
15243 (org-toggle-tag tag (if off 'off 'on))
15244 (setq newhead (org-get-heading)))))
15245 (and agendap (org-agenda-change-all-lines newhead m))))
15246 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15248 (defun org-tags-completion-function (string _predicate &optional flag)
15249 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15250 (confirm (lambda (x) (stringp (car x)))))
15251 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15252 (setq s1 (match-string 1 string)
15253 s2 (match-string 2 string))
15254 (setq s1 "" s2 string))
15255 (cond
15256 ((eq flag nil)
15257 ;; try completion
15258 (setq rtn (try-completion s2 ctable confirm))
15259 (when (stringp rtn)
15260 (setq rtn
15261 (concat s1 s2 (substring rtn (length s2))
15262 (if (and org-add-colon-after-tag-completion
15263 (assoc rtn ctable))
15264 ":" ""))))
15265 rtn)
15266 ((eq flag t)
15267 ;; all-completions
15268 (all-completions s2 ctable confirm))
15269 ((eq flag 'lambda)
15270 ;; exact match?
15271 (assoc s2 ctable)))))
15273 (defun org-fast-tag-insert (kwd tags face &optional end)
15274 "Insert KDW, and the TAGS, the latter with face FACE.
15275 Also insert END."
15276 (insert (format "%-12s" (concat kwd ":"))
15277 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15278 (or end "")))
15280 (defun org-fast-tag-show-exit (flag)
15281 (save-excursion
15282 (org-goto-line 3)
15283 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15284 (replace-match ""))
15285 (when flag
15286 (end-of-line 1)
15287 (org-move-to-column (- (window-width) 19) t)
15288 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15290 (defun org-set-current-tags-overlay (current prefix)
15291 "Add an overlay to CURRENT tag with PREFIX."
15292 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15293 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15294 (org-overlay-display org-tags-overlay (concat prefix s))))
15296 (defvar org-last-tag-selection-key nil)
15297 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15298 "Fast tag selection with single keys.
15299 CURRENT is the current list of tags in the headline, INHERITED is the
15300 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15301 possibly with grouping information. TODO-TABLE is a similar table with
15302 TODO keywords, should these have keys assigned to them.
15303 If the keys are nil, a-z are automatically assigned.
15304 Returns the new tags string, or nil to not change the current settings."
15305 (let* ((fulltable (append table todo-table))
15306 (maxlen (apply 'max (mapcar
15307 (lambda (x)
15308 (if (stringp (car x)) (string-width (car x)) 0))
15309 fulltable)))
15310 (buf (current-buffer))
15311 (expert (eq org-fast-tag-selection-single-key 'expert))
15312 (buffer-tags nil)
15313 (fwidth (+ maxlen 3 1 3))
15314 (ncol (/ (- (window-width) 4) fwidth))
15315 (i-face 'org-done)
15316 (c-face 'org-todo)
15317 tg cnt e c char c1 c2 ntable tbl rtn
15318 ov-start ov-end ov-prefix
15319 (exit-after-next org-fast-tag-selection-single-key)
15320 (done-keywords org-done-keywords)
15321 groups ingroup intaggroup)
15322 (save-excursion
15323 (beginning-of-line 1)
15324 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15325 (setq ov-start (match-beginning 1)
15326 ov-end (match-end 1)
15327 ov-prefix "")
15328 (setq ov-start (1- (point-at-eol))
15329 ov-end (1+ ov-start))
15330 (skip-chars-forward "^\n\r")
15331 (setq ov-prefix
15332 (concat
15333 (buffer-substring (1- (point)) (point))
15334 (if (> (current-column) org-tags-column)
15336 (make-string (- org-tags-column (current-column)) ?\ ))))))
15337 (move-overlay org-tags-overlay ov-start ov-end)
15338 (save-window-excursion
15339 (if expert
15340 (set-buffer (get-buffer-create " *Org tags*"))
15341 (delete-other-windows)
15342 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15343 (org-switch-to-buffer-other-window " *Org tags*"))
15344 (erase-buffer)
15345 (setq-local org-done-keywords done-keywords)
15346 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15347 (org-fast-tag-insert "Current" current c-face "\n\n")
15348 (org-fast-tag-show-exit exit-after-next)
15349 (org-set-current-tags-overlay current ov-prefix)
15350 (setq tbl fulltable char ?a cnt 0)
15351 (while (setq e (pop tbl))
15352 (cond
15353 ((eq (car e) :startgroup)
15354 (push '() groups) (setq ingroup t)
15355 (unless (zerop cnt)
15356 (setq cnt 0)
15357 (insert "\n"))
15358 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15359 ((eq (car e) :endgroup)
15360 (setq ingroup nil cnt 0)
15361 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15362 ((eq (car e) :startgrouptag)
15363 (setq intaggroup t)
15364 (unless (zerop cnt)
15365 (setq cnt 0)
15366 (insert "\n"))
15367 (insert "[ "))
15368 ((eq (car e) :endgrouptag)
15369 (setq intaggroup nil cnt 0)
15370 (insert "]\n"))
15371 ((equal e '(:newline))
15372 (unless (zerop cnt)
15373 (setq cnt 0)
15374 (insert "\n")
15375 (setq e (car tbl))
15376 (while (equal (car tbl) '(:newline))
15377 (insert "\n")
15378 (setq tbl (cdr tbl)))))
15379 ((equal e '(:grouptags)) (insert " : "))
15381 (setq tg (copy-sequence (car e)) c2 nil)
15382 (if (cdr e)
15383 (setq c (cdr e))
15384 ;; automatically assign a character.
15385 (setq c1 (string-to-char
15386 (downcase (substring
15387 tg (if (= (string-to-char tg) ?@) 1 0)))))
15388 (if (or (rassoc c1 ntable) (rassoc c1 table))
15389 (while (or (rassoc char ntable) (rassoc char table))
15390 (setq char (1+ char)))
15391 (setq c2 c1))
15392 (setq c (or c2 char)))
15393 (when ingroup (push tg (car groups)))
15394 (setq tg (org-add-props tg nil 'face
15395 (cond
15396 ((not (assoc tg table))
15397 (org-get-todo-face tg))
15398 ((member tg current) c-face)
15399 ((member tg inherited) i-face))))
15400 (when (equal (caar tbl) :grouptags)
15401 (org-add-props tg nil 'face 'org-tag-group))
15402 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15403 (insert "[" c "] " tg (make-string
15404 (- fwidth 4 (length tg)) ?\ ))
15405 (push (cons tg c) ntable)
15406 (when (= (cl-incf cnt) ncol)
15407 (insert "\n")
15408 (when (or ingroup intaggroup) (insert " "))
15409 (setq cnt 0)))))
15410 (setq ntable (nreverse ntable))
15411 (insert "\n")
15412 (goto-char (point-min))
15413 (unless expert (org-fit-window-to-buffer))
15414 (setq rtn
15415 (catch 'exit
15416 (while t
15417 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15418 (if (not groups) "no " "")
15419 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15420 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15421 (setq org-last-tag-selection-key c)
15422 (cond
15423 ((= c ?\r) (throw 'exit t))
15424 ((= c ?!)
15425 (setq groups (not groups))
15426 (goto-char (point-min))
15427 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15428 ((= c ?\C-c)
15429 (if (not expert)
15430 (org-fast-tag-show-exit
15431 (setq exit-after-next (not exit-after-next)))
15432 (setq expert nil)
15433 (delete-other-windows)
15434 (set-window-buffer (split-window-vertically) " *Org tags*")
15435 (org-switch-to-buffer-other-window " *Org tags*")
15436 (org-fit-window-to-buffer)))
15437 ((or (= c ?\C-g)
15438 (and (= c ?q) (not (rassoc c ntable))))
15439 (delete-overlay org-tags-overlay)
15440 (setq quit-flag t))
15441 ((= c ?\ )
15442 (setq current nil)
15443 (when exit-after-next (setq exit-after-next 'now)))
15444 ((= c ?\t)
15445 (condition-case nil
15446 (setq tg (completing-read
15447 "Tag: "
15448 (or buffer-tags
15449 (with-current-buffer buf
15450 (setq buffer-tags
15451 (org-get-buffer-tags))))))
15452 (quit (setq tg "")))
15453 (when (string-match "\\S-" tg)
15454 (cl-pushnew (list tg) buffer-tags :test #'equal)
15455 (if (member tg current)
15456 (setq current (delete tg current))
15457 (push tg current)))
15458 (when exit-after-next (setq exit-after-next 'now)))
15459 ((setq e (rassoc c todo-table) tg (car e))
15460 (with-current-buffer buf
15461 (save-excursion (org-todo tg)))
15462 (when exit-after-next (setq exit-after-next 'now)))
15463 ((setq e (rassoc c ntable) tg (car e))
15464 (if (member tg current)
15465 (setq current (delete tg current))
15466 (cl-loop for g in groups do
15467 (when (member tg g)
15468 (dolist (x g) (setq current (delete x current)))))
15469 (push tg current))
15470 (when exit-after-next (setq exit-after-next 'now))))
15472 ;; Create a sorted list
15473 (setq current
15474 (sort current
15475 (lambda (a b)
15476 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15477 (when (eq exit-after-next 'now) (throw 'exit t))
15478 (goto-char (point-min))
15479 (beginning-of-line 2)
15480 (delete-region (point) (point-at-eol))
15481 (org-fast-tag-insert "Current" current c-face)
15482 (org-set-current-tags-overlay current ov-prefix)
15483 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15484 (setq tg (match-string 1))
15485 (add-text-properties
15486 (match-beginning 1) (match-end 1)
15487 (list 'face
15488 (cond
15489 ((member tg current) c-face)
15490 ((member tg inherited) i-face)
15491 (t (get-text-property (match-beginning 1) 'face))))))
15492 (goto-char (point-min)))))
15493 (delete-overlay org-tags-overlay)
15494 (if rtn
15495 (mapconcat 'identity current ":")
15496 nil))))
15498 (defun org-get-tags-string ()
15499 "Get the TAGS string in the current headline."
15500 (unless (org-at-heading-p t)
15501 (user-error "Not on a heading"))
15502 (save-excursion
15503 (beginning-of-line 1)
15504 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15505 (match-string-no-properties 1)
15506 "")))
15508 (defun org-get-tags ()
15509 "Get the list of tags specified in the current headline."
15510 (org-split-string (org-get-tags-string) ":"))
15512 (defun org-get-buffer-tags ()
15513 "Get a table of all tags used in the buffer, for completion."
15514 (org-with-wide-buffer
15515 (goto-char (point-min))
15516 (let ((tag-re (concat org-outline-regexp-bol
15517 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15518 tags)
15519 (while (re-search-forward tag-re nil t)
15520 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15521 (push tag tags)))
15522 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15524 ;;;; The mapping API
15526 (defvar org-agenda-skip-comment-trees)
15527 (defvar org-agenda-skip-function)
15528 (defun org-map-entries (func &optional match scope &rest skip)
15529 "Call FUNC at each headline selected by MATCH in SCOPE.
15531 FUNC is a function or a lisp form. The function will be called without
15532 arguments, with the cursor positioned at the beginning of the headline.
15533 The return values of all calls to the function will be collected and
15534 returned as a list.
15536 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15537 does not need to preserve point. After evaluation, the cursor will be
15538 moved to the end of the line (presumably of the headline of the
15539 processed entry) and search continues from there. Under some
15540 circumstances, this may not produce the wanted results. For example,
15541 if you have removed (e.g. archived) the current (sub)tree it could
15542 mean that the next entry will be skipped entirely. In such cases, you
15543 can specify the position from where search should continue by making
15544 FUNC set the variable `org-map-continue-from' to the desired buffer
15545 position.
15547 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15548 Only headlines that are matched by this query will be considered during
15549 the iteration. When MATCH is nil or t, all headlines will be
15550 visited by the iteration.
15552 SCOPE determines the scope of this command. It can be any of:
15554 nil The current buffer, respecting the restriction if any
15555 tree The subtree started with the entry at point
15556 region The entries within the active region, if any
15557 region-start-level
15558 The entries within the active region, but only those at
15559 the same level than the first one.
15560 file The current buffer, without restriction
15561 file-with-archives
15562 The current buffer, and any archives associated with it
15563 agenda All agenda files
15564 agenda-with-archives
15565 All agenda files with any archive files associated with them
15566 \(file1 file2 ...)
15567 If this is a list, all files in the list will be scanned
15569 The remaining args are treated as settings for the skipping facilities of
15570 the scanner. The following items can be given here:
15572 archive skip trees with the archive tag
15573 comment skip trees with the COMMENT keyword
15574 function or Emacs Lisp form:
15575 will be used as value for `org-agenda-skip-function', so
15576 whenever the function returns a position, FUNC will not be
15577 called for that entry and search will continue from the
15578 position returned
15580 If your function needs to retrieve the tags including inherited tags
15581 at the *current* entry, you can use the value of the variable
15582 `org-scanner-tags' which will be much faster than getting the value
15583 with `org-get-tags-at'. If your function gets properties with
15584 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15585 to t around the call to `org-entry-properties' to get the same speedup.
15586 Note that if your function moves around to retrieve tags and properties at
15587 a *different* entry, you cannot use these techniques."
15588 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15589 (not (org-region-active-p)))
15590 (let* ((org-agenda-archives-mode nil) ; just to make sure
15591 (org-agenda-skip-archived-trees (memq 'archive skip))
15592 (org-agenda-skip-comment-trees (memq 'comment skip))
15593 (org-agenda-skip-function
15594 (car (org-delete-all '(comment archive) skip)))
15595 (org-tags-match-list-sublevels t)
15596 (start-level (eq scope 'region-start-level))
15597 matcher res
15598 org-todo-keywords-for-agenda
15599 org-done-keywords-for-agenda
15600 org-todo-keyword-alist-for-agenda
15601 org-tag-alist-for-agenda
15602 org--matcher-tags-todo-only)
15604 (cond
15605 ((eq match t) (setq matcher t))
15606 ((eq match nil) (setq matcher t))
15607 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15609 (save-excursion
15610 (save-restriction
15611 (cond ((eq scope 'tree)
15612 (org-back-to-heading t)
15613 (org-narrow-to-subtree)
15614 (setq scope nil))
15615 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15616 (org-region-active-p))
15617 ;; If needed, set start-level to a string like "2"
15618 (when start-level
15619 (save-excursion
15620 (goto-char (region-beginning))
15621 (unless (org-at-heading-p) (outline-next-heading))
15622 (setq start-level (org-current-level))))
15623 (narrow-to-region (region-beginning)
15624 (save-excursion
15625 (goto-char (region-end))
15626 (unless (and (bolp) (org-at-heading-p))
15627 (outline-next-heading))
15628 (point)))
15629 (setq scope nil)))
15631 (if (not scope)
15632 (progn
15633 (org-agenda-prepare-buffers
15634 (and buffer-file-name (list buffer-file-name)))
15635 (setq res
15636 (org-scan-tags
15637 func matcher org--matcher-tags-todo-only start-level)))
15638 ;; Get the right scope
15639 (cond
15640 ((and scope (listp scope) (symbolp (car scope)))
15641 (setq scope (eval scope)))
15642 ((eq scope 'agenda)
15643 (setq scope (org-agenda-files t)))
15644 ((eq scope 'agenda-with-archives)
15645 (setq scope (org-agenda-files t))
15646 (setq scope (org-add-archive-files scope)))
15647 ((eq scope 'file)
15648 (setq scope (and buffer-file-name (list buffer-file-name))))
15649 ((eq scope 'file-with-archives)
15650 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15651 (org-agenda-prepare-buffers scope)
15652 (dolist (file scope)
15653 (with-current-buffer (org-find-base-buffer-visiting file)
15654 (save-excursion
15655 (save-restriction
15656 (widen)
15657 (goto-char (point-min))
15658 (setq res
15659 (append
15661 (org-scan-tags
15662 func matcher org--matcher-tags-todo-only))))))))))
15663 res)))
15665 ;;; Properties API
15667 (defconst org-special-properties
15668 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15669 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15670 "The special properties valid in Org mode.
15671 These are properties that are not defined in the property drawer,
15672 but in some other way.")
15674 (defconst org-default-properties
15675 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15676 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15677 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15678 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15679 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15680 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15681 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15682 "Some properties that are used by Org mode for various purposes.
15683 Being in this list makes sure that they are offered for completion.")
15685 (defun org--valid-property-p (property)
15686 "Non nil when string PROPERTY is a valid property name."
15687 (not
15688 (or (equal property "")
15689 (string-match-p "\\s-" property))))
15691 (defun org--update-property-plist (key val props)
15692 "Associate KEY to VAL in alist PROPS.
15693 Modifications are made by side-effect. Return new alist."
15694 (let* ((appending (string= (substring key -1) "+"))
15695 (key (if appending (substring key 0 -1) key))
15696 (old (assoc-string key props t)))
15697 (if (not old) (cons (cons key val) props)
15698 (setcdr old (if appending (concat (cdr old) " " val) val))
15699 props)))
15701 (defun org-get-property-block (&optional beg force)
15702 "Return the (beg . end) range of the body of the property drawer.
15703 BEG is the beginning of the current subtree, or of the part
15704 before the first headline. If it is not given, it will be found.
15705 If the drawer does not exist, create it if FORCE is non-nil, or
15706 return nil."
15707 (org-with-wide-buffer
15708 (when beg (goto-char beg))
15709 (unless (org-before-first-heading-p)
15710 (let ((beg (cond (beg)
15711 ((or (not (featurep 'org-inlinetask))
15712 (org-inlinetask-in-task-p))
15713 (org-back-to-heading t))
15714 (t (org-with-limited-levels (org-back-to-heading t))))))
15715 (forward-line)
15716 (when (looking-at-p org-planning-line-re) (forward-line))
15717 (cond ((looking-at org-property-drawer-re)
15718 (forward-line)
15719 (cons (point) (progn (goto-char (match-end 0))
15720 (line-beginning-position))))
15721 (force
15722 (goto-char beg)
15723 (org-insert-property-drawer)
15724 (let ((pos (save-excursion (search-forward ":END:")
15725 (line-beginning-position))))
15726 (cons pos pos))))))))
15728 (defun org-at-property-p ()
15729 "Non-nil when point is inside a property drawer.
15730 See `org-property-re' for match data, if applicable."
15731 (save-excursion
15732 (beginning-of-line)
15733 (and (looking-at org-property-re)
15734 (let ((property-drawer (save-match-data (org-get-property-block))))
15735 (and property-drawer
15736 (>= (point) (car property-drawer))
15737 (< (point) (cdr property-drawer)))))))
15739 (defun org-property-action ()
15740 "Do an action on properties."
15741 (interactive)
15742 (unless (org-at-property-p) (user-error "Not at a property"))
15743 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15744 (let ((c (read-char-exclusive)))
15745 (cl-case c
15746 (?s (call-interactively #'org-set-property))
15747 (?d (call-interactively #'org-delete-property))
15748 (?D (call-interactively #'org-delete-property-globally))
15749 (?c (call-interactively #'org-compute-property-at-point))
15750 (otherwise (user-error "No such property action %c" c)))))
15752 (defun org-inc-effort ()
15753 "Increment the value of the effort property in the current entry."
15754 (interactive)
15755 (org-set-effort nil t))
15757 (defvar org-clock-effort) ; Defined in org-clock.el.
15758 (defvar org-clock-current-task) ; Defined in org-clock.el.
15759 (defun org-set-effort (&optional value increment)
15760 "Set the effort property of the current entry.
15761 With numerical prefix arg, use the nth allowed value, 0 stands for the
15762 10th allowed value.
15764 When INCREMENT is non-nil, set the property to the next allowed value."
15765 (interactive "P")
15766 (when (equal value 0) (setq value 10))
15767 (let* ((completion-ignore-case t)
15768 (prop org-effort-property)
15769 (cur (org-entry-get nil prop))
15770 (allowed (org-property-get-allowed-values nil prop 'table))
15771 (existing (mapcar 'list (org-property-values prop)))
15772 (heading (nth 4 (org-heading-components)))
15774 (val (cond
15775 ((stringp value) value)
15776 ((and allowed (integerp value))
15777 (or (car (nth (1- value) allowed))
15778 (car (org-last allowed))))
15779 ((and allowed increment)
15780 (or (cl-caadr (member (list cur) allowed))
15781 (user-error "Allowed effort values are not set")))
15782 (allowed
15783 (message "Select 1-9,0, [RET%s]: %s"
15784 (if cur (concat "=" cur) "")
15785 (mapconcat 'car allowed " "))
15786 (setq rpl (read-char-exclusive))
15787 (if (equal rpl ?\r)
15789 (setq rpl (- rpl ?0))
15790 (when (equal rpl 0) (setq rpl 10))
15791 (if (and (> rpl 0) (<= rpl (length allowed)))
15792 (car (nth (1- rpl) allowed))
15793 (org-completing-read "Effort: " allowed nil))))
15795 (org-completing-read
15796 (concat "Effort" (and cur (string-match "\\S-" cur)
15797 (concat " [" cur "]"))
15798 ": ")
15799 existing nil nil "" nil cur)))))
15800 (unless (equal (org-entry-get nil prop) val)
15801 (org-entry-put nil prop val))
15802 (org-refresh-property
15803 '((effort . identity)
15804 (effort-minutes . org-duration-string-to-minutes))
15805 val)
15806 (when (equal heading (bound-and-true-p org-clock-current-task))
15807 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15808 (org-clock-update-mode-line))
15809 (message "%s is now %s" prop val)))
15811 (defun org-entry-properties (&optional pom which)
15812 "Get all properties of the current entry.
15814 When POM is a buffer position, get all properties from the entry
15815 there instead.
15817 This includes the TODO keyword, the tags, time strings for
15818 deadline, scheduled, and clocking, and any additional properties
15819 defined in the entry.
15821 If WHICH is nil or `all', get all properties. If WHICH is
15822 `special' or `standard', only get that subclass. If WHICH is
15823 a string, only get that property.
15825 Return value is an alist. Keys are properties, as upcased
15826 strings."
15827 (org-with-point-at pom
15828 (when (and (derived-mode-p 'org-mode)
15829 (ignore-errors (org-back-to-heading t)))
15830 (catch 'exit
15831 (let* ((beg (point))
15832 (specific (and (stringp which) (upcase which)))
15833 (which (cond ((not specific) which)
15834 ((member specific org-special-properties) 'special)
15835 (t 'standard)))
15836 props)
15837 ;; Get the special properties, like TODO and TAGS.
15838 (when (memq which '(nil all special))
15839 (when (or (not specific) (string= specific "CLOCKSUM"))
15840 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15841 (when clocksum
15842 (push (cons "CLOCKSUM"
15843 (org-minutes-to-clocksum-string clocksum))
15844 props)))
15845 (when specific (throw 'exit props)))
15846 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15847 (let ((clocksumt (get-text-property (point)
15848 :org-clock-minutes-today)))
15849 (when clocksumt
15850 (push (cons "CLOCKSUM_T"
15851 (org-minutes-to-clocksum-string clocksumt))
15852 props)))
15853 (when specific (throw 'exit props)))
15854 (when (or (not specific) (string= specific "ITEM"))
15855 (when (looking-at org-complex-heading-regexp)
15856 (push (cons "ITEM"
15857 (let ((title (match-string-no-properties 4)))
15858 (if (org-string-nw-p title)
15859 (org-remove-tabs title)
15860 "")))
15861 props))
15862 (when specific (throw 'exit props)))
15863 (when (or (not specific) (string= specific "TODO"))
15864 (let ((case-fold-search nil))
15865 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15866 (push (cons "TODO" (match-string-no-properties 2)) props)))
15867 (when specific (throw 'exit props)))
15868 (when (or (not specific) (string= specific "PRIORITY"))
15869 (push (cons "PRIORITY"
15870 (if (looking-at org-priority-regexp)
15871 (match-string-no-properties 2)
15872 (char-to-string org-default-priority)))
15873 props)
15874 (when specific (throw 'exit props)))
15875 (when (or (not specific) (string= specific "FILE"))
15876 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15877 props)
15878 (when specific (throw 'exit props)))
15879 (when (or (not specific) (string= specific "TAGS"))
15880 (let ((value (org-string-nw-p (org-get-tags-string))))
15881 (when value (push (cons "TAGS" value) props)))
15882 (when specific (throw 'exit props)))
15883 (when (or (not specific) (string= specific "ALLTAGS"))
15884 (let ((value (org-get-tags-at)))
15885 (when value
15886 (push (cons "ALLTAGS"
15887 (format ":%s:" (mapconcat #'identity value ":")))
15888 props)))
15889 (when specific (throw 'exit props)))
15890 (when (or (not specific) (string= specific "BLOCKED"))
15891 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15892 (when specific (throw 'exit props)))
15893 (when (or (not specific)
15894 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15895 (forward-line)
15896 (when (looking-at-p org-planning-line-re)
15897 (end-of-line)
15898 (let ((bol (line-beginning-position))
15899 ;; Backward compatibility: time keywords used to
15900 ;; be configurable (before 8.3). Make sure we
15901 ;; get the correct keyword.
15902 (key-assoc `(("CLOSED" . ,org-closed-string)
15903 ("DEADLINE" . ,org-deadline-string)
15904 ("SCHEDULED" . ,org-scheduled-string))))
15905 (dolist (pair (if specific (list (assoc specific key-assoc))
15906 key-assoc))
15907 (save-excursion
15908 (when (search-backward (cdr pair) bol t)
15909 (goto-char (match-end 0))
15910 (skip-chars-forward " \t")
15911 (and (looking-at org-ts-regexp-both)
15912 (push (cons (car pair)
15913 (match-string-no-properties 0))
15914 props)))))))
15915 (when specific (throw 'exit props)))
15916 (when (or (not specific)
15917 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15918 (let ((find-ts
15919 (lambda (end ts)
15920 ;; Fix next time-stamp before END. TS is the
15921 ;; list of time-stamps found so far.
15922 (let ((ts ts)
15923 (regexp (cond
15924 ((string= specific "TIMESTAMP")
15925 org-ts-regexp)
15926 ((string= specific "TIMESTAMP_IA")
15927 org-ts-regexp-inactive)
15928 ((assoc "TIMESTAMP_IA" ts)
15929 org-ts-regexp)
15930 ((assoc "TIMESTAMP" ts)
15931 org-ts-regexp-inactive)
15932 (t org-ts-regexp-both))))
15933 (catch 'next
15934 (while (re-search-forward regexp end t)
15935 (backward-char)
15936 (let ((object (org-element-context)))
15937 ;; Accept to match timestamps in node
15938 ;; properties, too.
15939 (when (memq (org-element-type object)
15940 '(node-property timestamp))
15941 (let ((type
15942 (org-element-property :type object)))
15943 (cond
15944 ((and (memq type '(active active-range))
15945 (not (equal specific "TIMESTAMP_IA")))
15946 (unless (assoc "TIMESTAMP" ts)
15947 (push (cons "TIMESTAMP"
15948 (org-element-property
15949 :raw-value object))
15951 (when specific (throw 'exit ts))))
15952 ((and (memq type '(inactive inactive-range))
15953 (not (string= specific "TIMESTAMP")))
15954 (unless (assoc "TIMESTAMP_IA" ts)
15955 (push (cons "TIMESTAMP_IA"
15956 (org-element-property
15957 :raw-value object))
15959 (when specific (throw 'exit ts))))))
15960 ;; Both timestamp types are found,
15961 ;; move to next part.
15962 (when (= (length ts) 2) (throw 'next ts)))))
15963 ts)))))
15964 (goto-char beg)
15965 ;; First look for timestamps within headline.
15966 (let ((ts (funcall find-ts (line-end-position) nil)))
15967 (if (= (length ts) 2) (setq props (nconc ts props))
15968 (forward-line)
15969 ;; Then find timestamps in the section, skipping
15970 ;; planning line.
15971 (when (looking-at-p org-planning-line-re)
15972 (forward-line))
15973 (let ((end (save-excursion (outline-next-heading))))
15974 (setq props (nconc (funcall find-ts end ts) props))))))))
15975 ;; Get the standard properties, like :PROP:.
15976 (when (memq which '(nil all standard))
15977 ;; If we are looking after a specific property, delegate
15978 ;; to `org-entry-get', which is faster. However, make an
15979 ;; exception for "CATEGORY", since it can be also set
15980 ;; through keywords (i.e. #+CATEGORY).
15981 (if (and specific (not (equal specific "CATEGORY")))
15982 (let ((value (org-entry-get beg specific nil t)))
15983 (throw 'exit (and value (list (cons specific value)))))
15984 (let ((range (org-get-property-block beg)))
15985 (when range
15986 (let ((end (cdr range)) seen-base)
15987 (goto-char (car range))
15988 ;; Unlike to `org--update-property-plist', we
15989 ;; handle the case where base values is found
15990 ;; after its extension. We also forbid standard
15991 ;; properties to be named as special properties.
15992 (while (re-search-forward org-property-re end t)
15993 (let* ((key (upcase (match-string-no-properties 2)))
15994 (extendp (string-match-p "\\+\\'" key))
15995 (key-base (if extendp (substring key 0 -1) key))
15996 (value (match-string-no-properties 3)))
15997 (cond
15998 ((member-ignore-case key-base org-special-properties))
15999 (extendp
16000 (setq props
16001 (org--update-property-plist key value props)))
16002 ((member key seen-base))
16003 (t (push key seen-base)
16004 (let ((p (assoc-string key props t)))
16005 (if p (setcdr p (concat value " " (cdr p)))
16006 (push (cons key value) props))))))))))))
16007 (unless (assoc "CATEGORY" props)
16008 (push (cons "CATEGORY" (org-get-category beg)) props)
16009 (when (string= specific "CATEGORY") (throw 'exit props)))
16010 ;; Return value.
16011 props)))))
16013 (defun org-property--local-values (property literal-nil)
16014 "Return value for PROPERTY in current entry.
16015 Value is a list whose car is the base value for PROPERTY and cdr
16016 a list of accumulated values. Return nil if neither is found in
16017 the entry. Also return nil when PROPERTY is set to \"nil\",
16018 unless LITERAL-NIL is non-nil."
16019 (let ((range (org-get-property-block)))
16020 (when range
16021 (goto-char (car range))
16022 (let* ((case-fold-search t)
16023 (end (cdr range))
16024 (value
16025 ;; Base value.
16026 (save-excursion
16027 (let ((v (and (re-search-forward
16028 (org-re-property property nil t) end t)
16029 (match-string-no-properties 3))))
16030 (list (if literal-nil v (org-not-nil v)))))))
16031 ;; Find additional values.
16032 (let* ((property+ (org-re-property (concat property "+") nil t)))
16033 (while (re-search-forward property+ end t)
16034 (push (match-string-no-properties 3) value)))
16035 ;; Return final values.
16036 (and (not (equal value '(nil))) (nreverse value))))))
16038 (defun org-entry-get (pom property &optional inherit literal-nil)
16039 "Get value of PROPERTY for entry or content at point-or-marker POM.
16041 If INHERIT is non-nil and the entry does not have the property,
16042 then also check higher levels of the hierarchy. If INHERIT is
16043 the symbol `selective', use inheritance only if the setting in
16044 `org-use-property-inheritance' selects PROPERTY for inheritance.
16046 If the property is present but empty, the return value is the
16047 empty string. If the property is not present at all, nil is
16048 returned. In any other case, return the value as a string.
16049 Search is case-insensitive.
16051 If LITERAL-NIL is set, return the string value \"nil\" as
16052 a string, do not interpret it as the list atom nil. This is used
16053 for inheritance when a \"nil\" value can supersede a non-nil
16054 value higher up the hierarchy."
16055 (org-with-point-at pom
16056 (cond
16057 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16058 ;; We need a special property. Use `org-entry-properties' to
16059 ;; retrieve it, but specify the wanted property.
16060 (cdr (assoc-string property (org-entry-properties nil property))))
16061 ((and inherit
16062 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16063 (org-entry-get-with-inheritance property literal-nil))
16065 (let* ((local (org-property--local-values property literal-nil))
16066 (value (and local (mapconcat #'identity (delq nil local) " "))))
16067 (if literal-nil value (org-not-nil value)))))))
16069 (defun org-property-or-variable-value (var &optional inherit)
16070 "Check if there is a property fixing the value of VAR.
16071 If yes, return this value. If not, return the current value of the variable."
16072 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16073 (if (and prop (stringp prop) (string-match "\\S-" prop))
16074 (read prop)
16075 (symbol-value var))))
16077 (defun org-entry-delete (pom property)
16078 "Delete PROPERTY from entry at point-or-marker POM.
16079 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16080 non-nil when a property was removed."
16081 (unless (member property org-special-properties)
16082 (org-with-point-at pom
16083 (let ((range (org-get-property-block)))
16084 (when range
16085 (let* ((begin (car range))
16086 (origin (cdr range))
16087 (end (copy-marker origin))
16088 (re (org-re-property
16089 (concat (regexp-quote property) "\\+?") t t)))
16090 (goto-char begin)
16091 (while (re-search-forward re end t)
16092 (delete-region (match-beginning 0) (line-beginning-position 2)))
16093 ;; If drawer is empty, remove it altogether.
16094 (when (= begin end)
16095 (delete-region (line-beginning-position 0)
16096 (line-beginning-position 2)))
16097 ;; Return non-nil if some property was removed.
16098 (prog1 (/= end origin) (set-marker end nil))))))))
16100 ;; Multi-values properties are properties that contain multiple values
16101 ;; These values are assumed to be single words, separated by whitespace.
16102 (defun org-entry-add-to-multivalued-property (pom property value)
16103 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16104 (let* ((old (org-entry-get pom property))
16105 (values (and old (org-split-string old "[ \t]"))))
16106 (setq value (org-entry-protect-space value))
16107 (unless (member value values)
16108 (setq values (append values (list value)))
16109 (org-entry-put pom property
16110 (mapconcat 'identity values " ")))))
16112 (defun org-entry-remove-from-multivalued-property (pom property value)
16113 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16114 (let* ((old (org-entry-get pom property))
16115 (values (and old (org-split-string old "[ \t]"))))
16116 (setq value (org-entry-protect-space value))
16117 (when (member value values)
16118 (setq values (delete value values))
16119 (org-entry-put pom property
16120 (mapconcat 'identity values " ")))))
16122 (defun org-entry-member-in-multivalued-property (pom property value)
16123 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16124 (let* ((old (org-entry-get pom property))
16125 (values (and old (org-split-string old "[ \t]"))))
16126 (setq value (org-entry-protect-space value))
16127 (member value values)))
16129 (defun org-entry-get-multivalued-property (pom property)
16130 "Return a list of values in a multivalued property."
16131 (let* ((value (org-entry-get pom property))
16132 (values (and value (org-split-string value "[ \t]"))))
16133 (mapcar 'org-entry-restore-space values)))
16135 (defun org-entry-put-multivalued-property (pom property &rest values)
16136 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16137 VALUES should be a list of strings. Spaces will be protected."
16138 (org-entry-put pom property
16139 (mapconcat 'org-entry-protect-space values " "))
16140 (let* ((value (org-entry-get pom property))
16141 (values (and value (org-split-string value "[ \t]"))))
16142 (mapcar 'org-entry-restore-space values)))
16144 (defun org-entry-protect-space (s)
16145 "Protect spaces and newline in string S."
16146 (while (string-match " " s)
16147 (setq s (replace-match "%20" t t s)))
16148 (while (string-match "\n" s)
16149 (setq s (replace-match "%0A" t t s)))
16152 (defun org-entry-restore-space (s)
16153 "Restore spaces and newline in string S."
16154 (while (string-match "%20" s)
16155 (setq s (replace-match " " t t s)))
16156 (while (string-match "%0A" s)
16157 (setq s (replace-match "\n" t t s)))
16160 (defvar org-entry-property-inherited-from (make-marker)
16161 "Marker pointing to the entry from where a property was inherited.
16162 Each call to `org-entry-get-with-inheritance' will set this marker to the
16163 location of the entry where the inheritance search matched. If there was
16164 no match, the marker will point nowhere.
16165 Note that also `org-entry-get' calls this function, if the INHERIT flag
16166 is set.")
16168 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16169 "Get PROPERTY of entry or content at point, search higher levels if needed.
16170 The search will stop at the first ancestor which has the property defined.
16171 If the value found is \"nil\", return nil to show that the property
16172 should be considered as undefined (this is the meaning of nil here).
16173 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16174 (move-marker org-entry-property-inherited-from nil)
16175 (org-with-wide-buffer
16176 (let (value)
16177 (catch 'exit
16178 (while t
16179 (let ((v (org-property--local-values property literal-nil)))
16180 (when v
16181 (setq value
16182 (concat (mapconcat #'identity (delq nil v) " ")
16183 (and value " ")
16184 value)))
16185 (cond
16186 ((car v)
16187 (org-back-to-heading t)
16188 (move-marker org-entry-property-inherited-from (point))
16189 (throw 'exit nil))
16190 ((org-up-heading-safe))
16192 (let ((global
16193 (cdr (or (assoc-string property org-file-properties t)
16194 (assoc-string property org-global-properties t)
16195 (assoc-string property org-global-properties-fixed t)))))
16196 (cond ((not global))
16197 (value (setq value (concat global " " value)))
16198 (t (setq value global))))
16199 (throw 'exit nil))))))
16200 (if literal-nil value (org-not-nil value)))))
16202 (defvar org-property-changed-functions nil
16203 "Hook called when the value of a property has changed.
16204 Each hook function should accept two arguments, the name of the property
16205 and the new value.")
16207 (defun org-entry-put (pom property value)
16208 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16210 If the value is nil, it is converted to the empty string. If it
16211 is not a string, an error is raised. Also raise an error on
16212 invalid property names.
16214 PROPERTY can be any regular property (see
16215 `org-special-properties'). It can also be \"TODO\",
16216 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16218 For the last two properties, VALUE may have any of the special
16219 values \"earlier\" and \"later\". The function then increases or
16220 decreases scheduled or deadline date by one day."
16221 (cond ((null value) (setq value ""))
16222 ((not (stringp value)) (error "Properties values should be strings"))
16223 ((not (org--valid-property-p property))
16224 (user-error "Invalid property name: \"%s\"" property)))
16225 (org-with-point-at pom
16226 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16227 (org-back-to-heading t)
16228 (org-with-limited-levels (org-back-to-heading t)))
16229 (let ((beg (point)))
16230 (cond
16231 ((equal property "TODO")
16232 (cond ((not (org-string-nw-p value)) (setq value 'none))
16233 ((not (member value org-todo-keywords-1))
16234 (user-error "\"%s\" is not a valid TODO state" value)))
16235 (org-todo value)
16236 (org-set-tags nil 'align))
16237 ((equal property "PRIORITY")
16238 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16239 (org-set-tags nil 'align))
16240 ((equal property "SCHEDULED")
16241 (forward-line)
16242 (if (and (looking-at-p org-planning-line-re)
16243 (re-search-forward
16244 org-scheduled-time-regexp (line-end-position) t))
16245 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16246 ((string= value "later") (org-timestamp-change 1 'day))
16247 ((string= value "") (org-schedule '(4)))
16248 (t (org-schedule nil value)))
16249 (if (member value '("earlier" "later" ""))
16250 (call-interactively #'org-schedule)
16251 (org-schedule nil value))))
16252 ((equal property "DEADLINE")
16253 (forward-line)
16254 (if (and (looking-at-p org-planning-line-re)
16255 (re-search-forward
16256 org-deadline-time-regexp (line-end-position) t))
16257 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16258 ((string= value "later") (org-timestamp-change 1 'day))
16259 ((string= value "") (org-deadline '(4)))
16260 (t (org-deadline nil value)))
16261 (if (member value '("earlier" "later" ""))
16262 (call-interactively #'org-deadline)
16263 (org-deadline nil value))))
16264 ((member property org-special-properties)
16265 (error "The %s property cannot be set with `org-entry-put'" property))
16267 (let* ((range (org-get-property-block beg 'force))
16268 (end (cdr range))
16269 (case-fold-search t))
16270 (goto-char (car range))
16271 (if (re-search-forward (org-re-property property nil t) end t)
16272 (progn (delete-region (match-beginning 0) (match-end 0))
16273 (goto-char (match-beginning 0)))
16274 (goto-char end)
16275 (insert "\n")
16276 (backward-char))
16277 (insert ":" property ":")
16278 (when value (insert " " value))
16279 (org-indent-line)))))
16280 (run-hook-with-args 'org-property-changed-functions property value)))
16282 (defun org-buffer-property-keys
16283 (&optional specials defaults columns ignore-malformed)
16284 "Get all property keys in the current buffer.
16286 When SPECIALS is non-nil, also list the special properties that
16287 reflect things like tags and TODO state.
16289 When DEFAULTS is non-nil, also include properties that has
16290 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16291 DESCRIPTION, LOCATION, and LOGGING and others.
16293 When COLUMNS in non-nil, also include property names given in
16294 COLUMN formats in the current buffer.
16296 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16297 automatically performed, such drawers will be silently ignored."
16298 (let ((case-fold-search t)
16299 (props (append
16300 (and specials org-special-properties)
16301 (and defaults (cons org-effort-property org-default-properties))
16302 nil)))
16303 (org-with-wide-buffer
16304 (goto-char (point-min))
16305 (while (re-search-forward org-property-start-re nil t)
16306 (let ((range (org-get-property-block)))
16307 (catch 'skip
16308 (unless range
16309 (when (and (not ignore-malformed)
16310 (not (org-before-first-heading-p))
16311 (y-or-n-p (format "Malformed drawer at %d, repair?"
16312 (line-beginning-position))))
16313 (org-get-property-block nil t))
16314 (throw 'skip nil))
16315 (goto-char (car range))
16316 (let ((begin (car range))
16317 (end (cdr range)))
16318 ;; Make sure that found property block is not located
16319 ;; before current point, as it would generate an infloop.
16320 ;; It can happen, for example, in the following
16321 ;; situation:
16323 ;; * Headline
16324 ;; :PROPERTIES:
16325 ;; ...
16326 ;; :END:
16327 ;; *************** Inlinetask
16328 ;; #+BEGIN_EXAMPLE
16329 ;; :PROPERTIES:
16330 ;; #+END_EXAMPLE
16332 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16333 (while (< (point) end)
16334 (let ((p (progn (looking-at org-property-re)
16335 (match-string-no-properties 2))))
16336 ;; Only add true property name, not extension symbol.
16337 (push (if (not (string-match-p "\\+\\'" p)) p
16338 (substring p 0 -1))
16339 props))
16340 (forward-line))))
16341 (outline-next-heading)))
16342 (when columns
16343 (goto-char (point-min))
16344 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16345 (let ((element (org-element-at-point)))
16346 (when (memq (org-element-type element) '(keyword node-property))
16347 (let ((value (org-element-property :value element))
16348 (start 0))
16349 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16350 (setq start (match-end 0))
16351 (let ((p (match-string-no-properties 1 value)))
16352 (unless (member-ignore-case p org-special-properties)
16353 (push p props))))))))))
16354 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16356 (defun org-property-values (key)
16357 "List all non-nil values of property KEY in current buffer."
16358 (org-with-wide-buffer
16359 (goto-char (point-min))
16360 (let ((case-fold-search t)
16361 (re (org-re-property key))
16362 values)
16363 (while (re-search-forward re nil t)
16364 (push (org-entry-get (point) key) values))
16365 (delete-dups values))))
16367 (defun org-insert-property-drawer ()
16368 "Insert a property drawer into the current entry."
16369 (org-with-wide-buffer
16370 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16371 (org-back-to-heading t)
16372 (org-with-limited-levels (org-back-to-heading t)))
16373 (forward-line)
16374 (when (looking-at-p org-planning-line-re) (forward-line))
16375 (unless (looking-at-p org-property-drawer-re)
16376 ;; Make sure we start editing a line from current entry, not from
16377 ;; next one. It prevents extending text properties or overlays
16378 ;; belonging to the latter.
16379 (when (bolp) (backward-char))
16380 (let ((begin (1+ (point)))
16381 (inhibit-read-only t))
16382 (insert "\n:PROPERTIES:\n:END:")
16383 (when (eobp) (insert "\n"))
16384 (org-indent-region begin (point))))))
16386 (defun org-insert-drawer (&optional arg drawer)
16387 "Insert a drawer at point.
16389 When optional argument ARG is non-nil, insert a property drawer.
16391 Optional argument DRAWER, when non-nil, is a string representing
16392 drawer's name. Otherwise, the user is prompted for a name.
16394 If a region is active, insert the drawer around that region
16395 instead.
16397 Point is left between drawer's boundaries."
16398 (interactive "P")
16399 (let* ((drawer (if arg "PROPERTIES"
16400 (or drawer (read-from-minibuffer "Drawer: ")))))
16401 (cond
16402 ;; With C-u, fall back on `org-insert-property-drawer'
16403 (arg (org-insert-property-drawer))
16404 ;; Check validity of suggested drawer's name.
16405 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16406 (user-error "Invalid drawer name"))
16407 ;; With an active region, insert a drawer at point.
16408 ((not (org-region-active-p))
16409 (progn
16410 (unless (bolp) (insert "\n"))
16411 (insert (format ":%s:\n\n:END:\n" drawer))
16412 (forward-line -2)))
16413 ;; Otherwise, insert the drawer at point
16415 (let ((rbeg (region-beginning))
16416 (rend (copy-marker (region-end))))
16417 (unwind-protect
16418 (progn
16419 (goto-char rbeg)
16420 (beginning-of-line)
16421 (when (save-excursion
16422 (re-search-forward org-outline-regexp-bol rend t))
16423 (user-error "Drawers cannot contain headlines"))
16424 ;; Position point at the beginning of the first
16425 ;; non-blank line in region. Insert drawer's opening
16426 ;; there, then indent it.
16427 (org-skip-whitespace)
16428 (beginning-of-line)
16429 (insert ":" drawer ":\n")
16430 (forward-line -1)
16431 (indent-for-tab-command)
16432 ;; Move point to the beginning of the first blank line
16433 ;; after the last non-blank line in region. Insert
16434 ;; drawer's closing, then indent it.
16435 (goto-char rend)
16436 (skip-chars-backward " \r\t\n")
16437 (insert "\n:END:")
16438 (deactivate-mark t)
16439 (indent-for-tab-command)
16440 (unless (eolp) (insert "\n")))
16441 ;; Clear marker, whatever the outcome of insertion is.
16442 (set-marker rend nil)))))))
16444 (defvar org-property-set-functions-alist nil
16445 "Property set function alist.
16446 Each entry should have the following format:
16448 (PROPERTY . READ-FUNCTION)
16450 The read function will be called with the same argument as
16451 `org-completing-read'.")
16453 (defun org-set-property-function (property)
16454 "Get the function that should be used to set PROPERTY.
16455 This is computed according to `org-property-set-functions-alist'."
16456 (or (cdr (assoc property org-property-set-functions-alist))
16457 'org-completing-read))
16459 (defun org-read-property-value (property)
16460 "Read PROPERTY value from user."
16461 (let* ((completion-ignore-case t)
16462 (allowed (org-property-get-allowed-values nil property 'table))
16463 (cur (org-entry-get nil property))
16464 (prompt (concat property " value"
16465 (if (and cur (string-match "\\S-" cur))
16466 (concat " [" cur "]") "") ": "))
16467 (set-function (org-set-property-function property))
16468 (val (if allowed
16469 (funcall set-function prompt allowed nil
16470 (not (get-text-property 0 'org-unrestricted
16471 (caar allowed))))
16472 (funcall set-function prompt
16473 (mapcar 'list (org-property-values property))
16474 nil nil "" nil cur))))
16475 (org-trim val)))
16477 (defvar org-last-set-property nil)
16478 (defvar org-last-set-property-value nil)
16479 (defun org-read-property-name ()
16480 "Read a property name."
16481 (let ((completion-ignore-case t)
16482 (default-prop (or (and (org-at-property-p)
16483 (match-string-no-properties 2))
16484 org-last-set-property)))
16485 (org-completing-read
16486 (concat "Property"
16487 (if default-prop (concat " [" default-prop "]") "")
16488 ": ")
16489 (mapcar #'list (org-buffer-property-keys nil t t))
16490 nil nil nil nil default-prop)))
16492 (defun org-set-property-and-value (use-last)
16493 "Allow to set [PROPERTY]: [value] direction from prompt.
16494 When use-default, don't even ask, just use the last
16495 \"[PROPERTY]: [value]\" string from the history."
16496 (interactive "P")
16497 (let* ((completion-ignore-case t)
16498 (pv (or (and use-last org-last-set-property-value)
16499 (org-completing-read
16500 "Enter a \"[Property]: [value]\" pair: "
16501 nil nil nil nil nil
16502 org-last-set-property-value)))
16503 prop val)
16504 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16505 (setq prop (match-string 1 pv)
16506 val (match-string 2 pv))
16507 (org-set-property prop val))))
16509 (defun org-set-property (property value)
16510 "In the current entry, set PROPERTY to VALUE.
16512 When called interactively, this will prompt for a property name, offering
16513 completion on existing and default properties. And then it will prompt
16514 for a value, offering completion either on allowed values (via an inherited
16515 xxx_ALL property) or on existing values in other instances of this property
16516 in the current file.
16518 Throw an error when trying to set a property with an invalid name."
16519 (interactive (list nil nil))
16520 (let ((property (or property (org-read-property-name))))
16521 ;; `org-entry-put' also makes the following check, but this one
16522 ;; avoids polluting `org-last-set-property' and
16523 ;; `org-last-set-property-value' needlessly.
16524 (unless (org--valid-property-p property)
16525 (user-error "Invalid property name: \"%s\"" property))
16526 (let ((value (or value (org-read-property-value property)))
16527 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16528 (setq org-last-set-property property)
16529 (setq org-last-set-property-value (concat property ": " value))
16530 ;; Possibly postprocess the inserted value:
16531 (when fn (setq value (funcall fn value)))
16532 (unless (equal (org-entry-get nil property) value)
16533 (org-entry-put nil property value)))))
16535 (defun org-find-property (property &optional value)
16536 "Find first entry in buffer that sets PROPERTY.
16538 When optional argument VALUE is non-nil, only consider an entry
16539 if it contains PROPERTY set to this value. If PROPERTY should be
16540 explicitly set to nil, use string \"nil\" for VALUE.
16542 Return position where the entry begins, or nil if there is no
16543 such entry. If narrowing is in effect, only search the visible
16544 part of the buffer."
16545 (save-excursion
16546 (goto-char (point-min))
16547 (let ((case-fold-search t)
16548 (re (org-re-property property nil (not value) value)))
16549 (catch 'exit
16550 (while (re-search-forward re nil t)
16551 (when (if value (org-at-property-p)
16552 (org-entry-get (point) property nil t))
16553 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16555 (defun org-delete-property (property)
16556 "In the current entry, delete PROPERTY."
16557 (interactive
16558 (let* ((completion-ignore-case t)
16559 (cat (org-entry-get (point) "CATEGORY"))
16560 (props0 (org-entry-properties nil 'standard))
16561 (props (if cat props0
16562 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16563 (prop (if (< 1 (length props))
16564 (completing-read "Property: " props nil t)
16565 (caar props))))
16566 (list prop)))
16567 (if (not property)
16568 (message "No property to delete in this entry")
16569 (org-entry-delete nil property)
16570 (message "Property \"%s\" deleted" property)))
16572 (defun org-delete-property-globally (property)
16573 "Remove PROPERTY globally, from all entries.
16574 This function ignores narrowing, if any."
16575 (interactive
16576 (let* ((completion-ignore-case t)
16577 (prop (completing-read
16578 "Globally remove property: "
16579 (mapcar #'list (org-buffer-property-keys)))))
16580 (list prop)))
16581 (org-with-wide-buffer
16582 (goto-char (point-min))
16583 (let ((count 0)
16584 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16585 (while (re-search-forward re nil t)
16586 (when (org-entry-delete (point) property) (cl-incf count)))
16587 (message "Property \"%s\" removed from %d entries" property count))))
16589 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16591 (defun org-compute-property-at-point ()
16592 "Compute the property at point.
16593 This looks for an enclosing column format, extracts the operator and
16594 then applies it to the property in the column format's scope."
16595 (interactive)
16596 (unless (org-at-property-p)
16597 (user-error "Not at a property"))
16598 (let ((prop (match-string-no-properties 2)))
16599 (org-columns-get-format-and-top-level)
16600 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16601 (user-error "No operator defined for property %s" prop))
16602 (org-columns-compute prop)))
16604 (defvar org-property-allowed-value-functions nil
16605 "Hook for functions supplying allowed values for a specific property.
16606 The functions must take a single argument, the name of the property, and
16607 return a flat list of allowed values. If \":ETC\" is one of
16608 the values, this means that these values are intended as defaults for
16609 completion, but that other values should be allowed too.
16610 The functions must return nil if they are not responsible for this
16611 property.")
16613 (defun org-property-get-allowed-values (pom property &optional table)
16614 "Get allowed values for the property PROPERTY.
16615 When TABLE is non-nil, return an alist that can directly be used for
16616 completion."
16617 (let (vals)
16618 (cond
16619 ((equal property "TODO")
16620 (setq vals (org-with-point-at pom
16621 (append org-todo-keywords-1 '("")))))
16622 ((equal property "PRIORITY")
16623 (let ((n org-lowest-priority))
16624 (while (>= n org-highest-priority)
16625 (push (char-to-string n) vals)
16626 (setq n (1- n)))))
16627 ((equal property "CATEGORY"))
16628 ((member property org-special-properties))
16629 ((setq vals (run-hook-with-args-until-success
16630 'org-property-allowed-value-functions property)))
16632 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16633 (when (and vals (string-match "\\S-" vals))
16634 (setq vals (car (read-from-string (concat "(" vals ")"))))
16635 (setq vals (mapcar (lambda (x)
16636 (cond ((stringp x) x)
16637 ((numberp x) (number-to-string x))
16638 ((symbolp x) (symbol-name x))
16639 (t "???")))
16640 vals)))))
16641 (when (member ":ETC" vals)
16642 (setq vals (remove ":ETC" vals))
16643 (org-add-props (car vals) '(org-unrestricted t)))
16644 (if table (mapcar 'list vals) vals)))
16646 (defun org-property-previous-allowed-value (&optional _previous)
16647 "Switch to the next allowed value for this property."
16648 (interactive)
16649 (org-property-next-allowed-value t))
16651 (defun org-property-next-allowed-value (&optional previous)
16652 "Switch to the next allowed value for this property."
16653 (interactive)
16654 (unless (org-at-property-p)
16655 (user-error "Not at a property"))
16656 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16657 (key (match-string 2))
16658 (value (match-string 3))
16659 (allowed (or (org-property-get-allowed-values (point) key)
16660 (and (member value '("[ ]" "[-]" "[X]"))
16661 '("[ ]" "[X]"))))
16662 (heading (save-match-data (nth 4 (org-heading-components))))
16663 nval)
16664 (unless allowed
16665 (user-error "Allowed values for this property have not been defined"))
16666 (when previous (setq allowed (reverse allowed)))
16667 (when (member value allowed)
16668 (setq nval (car (cdr (member value allowed)))))
16669 (setq nval (or nval (car allowed)))
16670 (when (equal nval value)
16671 (user-error "Only one allowed value for this property"))
16672 (org-at-property-p)
16673 (replace-match (concat " :" key ": " nval) t t)
16674 (org-indent-line)
16675 (beginning-of-line 1)
16676 (skip-chars-forward " \t")
16677 (when (equal prop org-effort-property)
16678 (org-refresh-property
16679 '((effort . identity)
16680 (effort-minutes . org-duration-string-to-minutes))
16681 nval)
16682 (when (string= org-clock-current-task heading)
16683 (setq org-clock-effort nval)
16684 (org-clock-update-mode-line)))
16685 (run-hook-with-args 'org-property-changed-functions key nval)))
16687 (defun org-find-olp (path &optional this-buffer)
16688 "Return a marker pointing to the entry at outline path OLP.
16689 If anything goes wrong, throw an error.
16690 You can wrap this call to catch the error like this:
16692 \(condition-case msg
16693 \(org-mobile-locate-entry (match-string 4))
16694 \(error (nth 1 msg)))
16696 The return value will then be either a string with the error message,
16697 or a marker if everything is OK.
16699 If THIS-BUFFER is set, the outline path does not contain a file,
16700 only headings."
16701 (let* ((file (if this-buffer buffer-file-name (pop path)))
16702 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16703 (level 1)
16704 (lmin 1)
16705 (lmax 1)
16706 end found flevel)
16707 (unless buffer (error "File not found :%s" file))
16708 (with-current-buffer buffer
16709 (org-with-wide-buffer
16710 (goto-char (point-min))
16711 (dolist (heading path)
16712 (let ((re (format org-complex-heading-regexp-format
16713 (regexp-quote heading)))
16714 (cnt 0))
16715 (while (re-search-forward re end t)
16716 (setq level (- (match-end 1) (match-beginning 1)))
16717 (when (and (>= level lmin) (<= level lmax))
16718 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16719 (when (= cnt 0)
16720 (error "Heading not found on level %d: %s" lmax heading))
16721 (when (> cnt 1)
16722 (error "Heading not unique on level %d: %s" lmax heading))
16723 (goto-char found)
16724 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16725 (setq end (save-excursion (org-end-of-subtree t t)))))
16726 (when (org-at-heading-p)
16727 (point-marker))))))
16729 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16730 "Find node HEADING in BUFFER.
16731 Return a marker to the heading if it was found, or nil if not.
16732 If POS-ONLY is set, return just the position instead of a marker.
16734 The heading text must match exact, but it may have a TODO keyword,
16735 a priority cookie and tags in the standard locations."
16736 (with-current-buffer (or buffer (current-buffer))
16737 (save-excursion
16738 (save-restriction
16739 (widen)
16740 (goto-char (point-min))
16741 (let (case-fold-search)
16742 (when (re-search-forward
16743 (format org-complex-heading-regexp-format
16744 (regexp-quote heading)) nil t)
16745 (if pos-only
16746 (match-beginning 0)
16747 (move-marker (make-marker) (match-beginning 0)))))))))
16749 (defun org-find-exact-heading-in-directory (heading &optional dir)
16750 "Find Org node headline HEADING in all .org files in directory DIR.
16751 When the target headline is found, return a marker to this location."
16752 (let ((files (directory-files (or dir default-directory)
16753 t "\\`[^.#].*\\.org\\'"))
16754 visiting m buffer)
16755 (catch 'found
16756 (dolist (file files)
16757 (message "trying %s" file)
16758 (setq visiting (org-find-base-buffer-visiting file))
16759 (setq buffer (or visiting (find-file-noselect file)))
16760 (setq m (org-find-exact-headline-in-buffer
16761 heading buffer))
16762 (when (and (not m) (not visiting)) (kill-buffer buffer))
16763 (and m (throw 'found m))))))
16765 (defun org-find-entry-with-id (ident)
16766 "Locate the entry that contains the ID property with exact value IDENT.
16767 IDENT can be a string, a symbol or a number, this function will search for
16768 the string representation of it.
16769 Return the position where this entry starts, or nil if there is no such entry."
16770 (interactive "sID: ")
16771 (let ((id (cond
16772 ((stringp ident) ident)
16773 ((symbolp ident) (symbol-name ident))
16774 ((numberp ident) (number-to-string ident))
16775 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16776 (org-with-wide-buffer (org-find-property "ID" id))))
16778 ;;;; Timestamps
16780 (defvar org-last-changed-timestamp nil)
16781 (defvar org-last-inserted-timestamp nil
16782 "The last time stamp inserted with `org-insert-time-stamp'.")
16783 (defvar org-ts-what) ; dynamically scoped parameter
16785 (defun org-time-stamp (arg &optional inactive)
16786 "Prompt for a date/time and insert a time stamp.
16788 If the user specifies a time like HH:MM or if this command is
16789 called with at least one prefix argument, the time stamp contains
16790 the date and the time. Otherwise, only the date is included.
16792 All parts of a date not specified by the user are filled in from
16793 the timestamp at point, if any, or the current date/time
16794 otherwise.
16796 If there is already a timestamp at the cursor, it is replaced.
16798 With two universal prefix arguments, insert an active timestamp
16799 with the current time without prompting the user.
16801 When called from lisp, the timestamp is inactive if INACTIVE is
16802 non-nil."
16803 (interactive "P")
16804 (let* ((ts (cond
16805 ((org-at-date-range-p t)
16806 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16807 ((org-at-timestamp-p t) (match-string 0))))
16808 ;; Default time is either the timestamp at point or today.
16809 ;; When entering a range, only the range start is considered.
16810 (default-time (if (not ts) (current-time)
16811 (apply #'encode-time (org-parse-time-string ts))))
16812 (default-input (and ts (org-get-compact-tod ts)))
16813 (repeater (and ts
16814 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16815 (match-string 0 ts)))
16816 org-time-was-given
16817 org-end-time-was-given
16818 (time
16819 (and (if (equal arg '(16)) (current-time)
16820 ;; Preserve `this-command' and `last-command'.
16821 (let ((this-command this-command)
16822 (last-command last-command))
16823 (org-read-date
16824 arg 'totime nil nil default-time default-input
16825 inactive))))))
16826 (cond
16827 ((and ts
16828 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16829 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16830 (insert "--")
16831 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16833 ;; Make sure we're on a timestamp. When in the middle of a date
16834 ;; range, move arbitrarily to range end.
16835 (unless (org-at-timestamp-p t)
16836 (skip-chars-forward "-")
16837 (org-at-timestamp-p t))
16838 (replace-match "")
16839 (setq org-last-changed-timestamp
16840 (org-insert-time-stamp
16841 time (or org-time-was-given arg)
16842 inactive nil nil (list org-end-time-was-given)))
16843 (when repeater
16844 (backward-char)
16845 (insert " " repeater)
16846 (setq org-last-changed-timestamp
16847 (concat (substring org-last-inserted-timestamp 0 -1)
16848 " " repeater ">")))
16849 (message "Timestamp updated"))
16850 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16851 (t (org-insert-time-stamp
16852 time (or org-time-was-given arg) inactive nil nil
16853 (list org-end-time-was-given))))))
16855 ;; FIXME: can we use this for something else, like computing time differences?
16856 (defun org-get-compact-tod (s)
16857 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16858 (let* ((t1 (match-string 1 s))
16859 (h1 (string-to-number (match-string 2 s)))
16860 (m1 (string-to-number (match-string 3 s)))
16861 (t2 (and (match-end 4) (match-string 5 s)))
16862 (h2 (and t2 (string-to-number (match-string 6 s))))
16863 (m2 (and t2 (string-to-number (match-string 7 s))))
16864 dh dm)
16865 (if (not t2)
16867 (setq dh (- h2 h1) dm (- m2 m1))
16868 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16869 (concat t1 "+" (number-to-string dh)
16870 (and (/= 0 dm) (format ":%02d" dm)))))))
16872 (defun org-time-stamp-inactive (&optional arg)
16873 "Insert an inactive time stamp.
16874 An inactive time stamp is enclosed in square brackets instead of angle
16875 brackets. It is inactive in the sense that it does not trigger agenda entries,
16876 does not link to the calendar and cannot be changed with the S-cursor keys.
16877 So these are more for recording a certain time/date."
16878 (interactive "P")
16879 (org-time-stamp arg 'inactive))
16881 (defvar org-date-ovl (make-overlay 1 1))
16882 (overlay-put org-date-ovl 'face 'org-date-selected)
16883 (delete-overlay org-date-ovl)
16885 (defvar org-ans1) ; dynamically scoped parameter
16886 (defvar org-ans2) ; dynamically scoped parameter
16888 (defvar org-plain-time-of-day-regexp) ; defined below
16890 (defvar org-overriding-default-time nil) ; dynamically scoped
16891 (defvar org-read-date-overlay nil)
16892 (defvar org-dcst nil) ; dynamically scoped
16893 (defvar org-read-date-history nil)
16894 (defvar org-read-date-final-answer nil)
16895 (defvar org-read-date-analyze-futurep nil)
16896 (defvar org-read-date-analyze-forced-year nil)
16897 (defvar org-read-date-inactive)
16899 (defvar org-read-date-minibuffer-local-map
16900 (let* ((map (make-sparse-keymap)))
16901 (set-keymap-parent map minibuffer-local-map)
16902 (org-defkey map (kbd ".")
16903 (lambda () (interactive)
16904 ;; Are we at the beginning of the prompt?
16905 (if (looking-back "^[^:]+: "
16906 (let ((inhibit-field-text-motion t))
16907 (line-beginning-position)))
16908 (org-eval-in-calendar '(calendar-goto-today))
16909 (insert "."))))
16910 (org-defkey map (kbd "C-.")
16911 (lambda () (interactive)
16912 (org-eval-in-calendar '(calendar-goto-today))))
16913 (org-defkey map [(meta shift left)]
16914 (lambda () (interactive)
16915 (org-eval-in-calendar '(calendar-backward-month 1))))
16916 (org-defkey map [(meta shift right)]
16917 (lambda () (interactive)
16918 (org-eval-in-calendar '(calendar-forward-month 1))))
16919 (org-defkey map [(meta shift up)]
16920 (lambda () (interactive)
16921 (org-eval-in-calendar '(calendar-backward-year 1))))
16922 (org-defkey map [(meta shift down)]
16923 (lambda () (interactive)
16924 (org-eval-in-calendar '(calendar-forward-year 1))))
16925 (org-defkey map [?\e (shift left)]
16926 (lambda () (interactive)
16927 (org-eval-in-calendar '(calendar-backward-month 1))))
16928 (org-defkey map [?\e (shift right)]
16929 (lambda () (interactive)
16930 (org-eval-in-calendar '(calendar-forward-month 1))))
16931 (org-defkey map [?\e (shift up)]
16932 (lambda () (interactive)
16933 (org-eval-in-calendar '(calendar-backward-year 1))))
16934 (org-defkey map [?\e (shift down)]
16935 (lambda () (interactive)
16936 (org-eval-in-calendar '(calendar-forward-year 1))))
16937 (org-defkey map [(shift up)]
16938 (lambda () (interactive)
16939 (org-eval-in-calendar '(calendar-backward-week 1))))
16940 (org-defkey map [(shift down)]
16941 (lambda () (interactive)
16942 (org-eval-in-calendar '(calendar-forward-week 1))))
16943 (org-defkey map [(shift left)]
16944 (lambda () (interactive)
16945 (org-eval-in-calendar '(calendar-backward-day 1))))
16946 (org-defkey map [(shift right)]
16947 (lambda () (interactive)
16948 (org-eval-in-calendar '(calendar-forward-day 1))))
16949 (org-defkey map "!"
16950 (lambda () (interactive)
16951 (org-eval-in-calendar '(diary-view-entries))
16952 (message "")))
16953 (org-defkey map ">"
16954 (lambda () (interactive)
16955 (org-eval-in-calendar '(calendar-scroll-left 1))))
16956 (org-defkey map "<"
16957 (lambda () (interactive)
16958 (org-eval-in-calendar '(calendar-scroll-right 1))))
16959 (org-defkey map "\C-v"
16960 (lambda () (interactive)
16961 (org-eval-in-calendar
16962 '(calendar-scroll-left-three-months 1))))
16963 (org-defkey map "\M-v"
16964 (lambda () (interactive)
16965 (org-eval-in-calendar
16966 '(calendar-scroll-right-three-months 1))))
16967 map)
16968 "Keymap for minibuffer commands when using `org-read-date'.")
16970 (defvar org-def)
16971 (defvar org-defdecode)
16972 (defvar org-with-time)
16974 (defvar calendar-setup) ; Dynamically scoped.
16975 (defun org-read-date (&optional with-time to-time from-string prompt
16976 default-time default-input inactive)
16977 "Read a date, possibly a time, and make things smooth for the user.
16978 The prompt will suggest to enter an ISO date, but you can also enter anything
16979 which will at least partially be understood by `parse-time-string'.
16980 Unrecognized parts of the date will default to the current day, month, year,
16981 hour and minute. If this command is called to replace a timestamp at point,
16982 or to enter the second timestamp of a range, the default time is taken
16983 from the existing stamp. Furthermore, the command prefers the future,
16984 so if you are giving a date where the year is not given, and the day-month
16985 combination is already past in the current year, it will assume you
16986 mean next year. For details, see the manual. A few examples:
16988 3-2-5 --> 2003-02-05
16989 feb 15 --> currentyear-02-15
16990 2/15 --> currentyear-02-15
16991 sep 12 9 --> 2009-09-12
16992 12:45 --> today 12:45
16993 22 sept 0:34 --> currentyear-09-22 0:34
16994 12 --> currentyear-currentmonth-12
16995 Fri --> nearest Friday after today
16996 -Tue --> last Tuesday
16997 etc.
16999 Furthermore you can specify a relative date by giving, as the *first* thing
17000 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
17001 change in days weeks, months, years.
17002 With a single plus or minus, the date is relative to today. With a double
17003 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17004 +4d --> four days from today
17005 +4 --> same as above
17006 +2w --> two weeks from today
17007 ++5 --> five days from default date
17009 The function understands only English month and weekday abbreviations.
17011 While prompting, a calendar is popped up - you can also select the
17012 date with the mouse (button 1). The calendar shows a period of three
17013 months. To scroll it to other months, use the keys `>' and `<'.
17014 If you don't like the calendar, turn it off with
17015 (setq org-read-date-popup-calendar nil)
17017 With optional argument TO-TIME, the date will immediately be converted
17018 to an internal time.
17019 With an optional argument WITH-TIME, the prompt will suggest to
17020 also insert a time. Note that when WITH-TIME is not set, you can
17021 still enter a time, and this function will inform the calling routine
17022 about this change. The calling routine may then choose to change the
17023 format used to insert the time stamp into the buffer to include the time.
17024 With optional argument FROM-STRING, read from this string instead from
17025 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17026 the time/date that is used for everything that is not specified by the
17027 user."
17028 (require 'parse-time)
17029 (let* ((org-with-time with-time)
17030 (org-time-stamp-rounding-minutes
17031 (if (equal org-with-time '(16))
17032 '(0 0)
17033 org-time-stamp-rounding-minutes))
17034 (org-dcst org-display-custom-times)
17035 (ct (org-current-time))
17036 (org-def (or org-overriding-default-time default-time ct))
17037 (org-defdecode (decode-time org-def))
17038 (cur-frame (selected-frame))
17039 (mouse-autoselect-window nil) ; Don't let the mouse jump
17040 (calendar-setup
17041 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17042 (calendar-move-hook nil)
17043 (calendar-view-diary-initially-flag nil)
17044 (calendar-view-holidays-initially-flag nil)
17045 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17046 ;; Rationalize `org-def' and `org-defdecode', if required.
17047 (when (< (nth 2 org-defdecode) org-extend-today-until)
17048 (setf (nth 2 org-defdecode) -1)
17049 (setf (nth 1 org-defdecode) 59)
17050 (setq org-def (apply #'encode-time org-defdecode))
17051 (setq org-defdecode (decode-time org-def)))
17052 (let* ((timestr (format-time-string
17053 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17054 org-def))
17055 (prompt (concat (if prompt (concat prompt " ") "")
17056 (format "Date+time [%s]: " timestr))))
17057 (cond
17058 (from-string (setq ans from-string))
17059 (org-read-date-popup-calendar
17060 (save-excursion
17061 (save-window-excursion
17062 (calendar)
17063 (when (eq calendar-setup 'calendar-only)
17064 (setq cal-frame
17065 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17066 (select-frame cal-frame))
17067 (org-eval-in-calendar '(setq cursor-type nil) t)
17068 (unwind-protect
17069 (progn
17070 (calendar-forward-day (- (time-to-days org-def)
17071 (calendar-absolute-from-gregorian
17072 (calendar-current-date))))
17073 (org-eval-in-calendar nil t)
17074 (let* ((old-map (current-local-map))
17075 (map (copy-keymap calendar-mode-map))
17076 (minibuffer-local-map
17077 (copy-keymap org-read-date-minibuffer-local-map)))
17078 (org-defkey map (kbd "RET") 'org-calendar-select)
17079 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17080 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17081 (unwind-protect
17082 (progn
17083 (use-local-map map)
17084 (setq org-read-date-inactive inactive)
17085 (add-hook 'post-command-hook 'org-read-date-display)
17086 (setq org-ans0
17087 (read-string prompt
17088 default-input
17089 'org-read-date-history
17090 nil))
17091 ;; org-ans0: from prompt
17092 ;; org-ans1: from mouse click
17093 ;; org-ans2: from calendar motion
17094 (setq ans
17095 (concat org-ans0 " " (or org-ans1 org-ans2))))
17096 (remove-hook 'post-command-hook 'org-read-date-display)
17097 (use-local-map old-map)
17098 (when org-read-date-overlay
17099 (delete-overlay org-read-date-overlay)
17100 (setq org-read-date-overlay nil)))))
17101 (bury-buffer "*Calendar*")
17102 (when cal-frame
17103 (delete-frame cal-frame)
17104 (select-frame-set-input-focus cur-frame))))))
17106 (t ; Naked prompt only
17107 (unwind-protect
17108 (setq ans (read-string prompt default-input
17109 'org-read-date-history timestr))
17110 (when org-read-date-overlay
17111 (delete-overlay org-read-date-overlay)
17112 (setq org-read-date-overlay nil))))))
17114 (setq final (org-read-date-analyze ans org-def org-defdecode))
17116 (when org-read-date-analyze-forced-year
17117 (message "Year was forced into %s"
17118 (if org-read-date-force-compatible-dates
17119 "compatible range (1970-2037)"
17120 "range representable on this machine"))
17121 (ding))
17123 ;; One round trip to get rid of 34th of August and stuff like that....
17124 (setq final (decode-time (apply 'encode-time final)))
17126 (setq org-read-date-final-answer ans)
17128 (if to-time
17129 (apply 'encode-time final)
17130 (if (and (boundp 'org-time-was-given) org-time-was-given)
17131 (format "%04d-%02d-%02d %02d:%02d"
17132 (nth 5 final) (nth 4 final) (nth 3 final)
17133 (nth 2 final) (nth 1 final))
17134 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17136 (defun org-read-date-display ()
17137 "Display the current date prompt interpretation in the minibuffer."
17138 (when org-read-date-display-live
17139 (when org-read-date-overlay
17140 (delete-overlay org-read-date-overlay))
17141 (when (minibufferp (current-buffer))
17142 (save-excursion
17143 (end-of-line 1)
17144 (while (not (equal (buffer-substring
17145 (max (point-min) (- (point) 4)) (point))
17146 " "))
17147 (insert " ")))
17148 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17149 " " (or org-ans1 org-ans2)))
17150 (org-end-time-was-given nil)
17151 (f (org-read-date-analyze ans org-def org-defdecode))
17152 (fmts (if org-dcst
17153 org-time-stamp-custom-formats
17154 org-time-stamp-formats))
17155 (fmt (if (or org-with-time
17156 (and (boundp 'org-time-was-given) org-time-was-given))
17157 (cdr fmts)
17158 (car fmts)))
17159 (txt (format-time-string fmt (apply 'encode-time f)))
17160 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17161 (txt (concat "=> " txt)))
17162 (when (and org-end-time-was-given
17163 (string-match org-plain-time-of-day-regexp txt))
17164 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17165 org-end-time-was-given
17166 (substring txt (match-end 0)))))
17167 (when org-read-date-analyze-futurep
17168 (setq txt (concat txt " (=>F)")))
17169 (setq org-read-date-overlay
17170 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17171 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17173 (defun org-read-date-analyze (ans def defdecode)
17174 "Analyze the combined answer of the date prompt."
17175 ;; FIXME: cleanup and comment
17176 ;; Pass `current-time' result to `decode-time' (instead of calling
17177 ;; without arguments) so that only `current-time' has to be
17178 ;; overriden in tests.
17179 (let ((org-def def)
17180 (org-defdecode defdecode)
17181 (nowdecode (decode-time (current-time)))
17182 delta deltan deltaw deltadef year month day
17183 hour minute second wday pm h2 m2 tl wday1
17184 iso-year iso-weekday iso-week iso-date futurep kill-year)
17185 (setq org-read-date-analyze-futurep nil
17186 org-read-date-analyze-forced-year nil)
17187 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17188 (setq ans "+0"))
17190 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17191 (setq ans (replace-match "" t t ans)
17192 deltan (car delta)
17193 deltaw (nth 1 delta)
17194 deltadef (nth 2 delta)))
17196 ;; Check if there is an iso week date in there. If yes, store the
17197 ;; info and postpone interpreting it until the rest of the parsing
17198 ;; is done.
17199 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17200 (setq iso-year (when (match-end 1)
17201 (org-small-year-to-year
17202 (string-to-number (match-string 1 ans))))
17203 iso-weekday (when (match-end 3)
17204 (string-to-number (match-string 3 ans)))
17205 iso-week (string-to-number (match-string 2 ans)))
17206 (setq ans (replace-match "" t t ans)))
17208 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17209 (when (string-match
17210 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17211 (setq year (if (match-end 2)
17212 (string-to-number (match-string 2 ans))
17213 (progn (setq kill-year t)
17214 (string-to-number (format-time-string "%Y"))))
17215 month (string-to-number (match-string 3 ans))
17216 day (string-to-number (match-string 4 ans)))
17217 (setq year (org-small-year-to-year year))
17218 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17219 t nil ans)))
17221 ;; Help matching dotted european dates
17222 (when (string-match
17223 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17224 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17225 (setq kill-year t)
17226 (string-to-number (format-time-string "%Y")))
17227 day (string-to-number (match-string 1 ans))
17228 month (string-to-number (match-string 2 ans))
17229 ans (replace-match (format "%04d-%02d-%02d" year month day)
17230 t nil ans)))
17232 ;; Help matching american dates, like 5/30 or 5/30/7
17233 (when (string-match
17234 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17235 (setq year (if (match-end 4)
17236 (string-to-number (match-string 4 ans))
17237 (progn (setq kill-year t)
17238 (string-to-number (format-time-string "%Y"))))
17239 month (string-to-number (match-string 1 ans))
17240 day (string-to-number (match-string 2 ans)))
17241 (setq year (org-small-year-to-year year))
17242 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17243 t nil ans)))
17244 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17245 ;; If there is a time with am/pm, and *no* time without it, we convert
17246 ;; so that matching will be successful.
17247 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17248 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17249 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17250 (setq hour (string-to-number (match-string 1 ans))
17251 minute (if (match-end 3)
17252 (string-to-number (match-string 3 ans))
17254 pm (equal ?p
17255 (string-to-char (downcase (match-string 4 ans)))))
17256 (if (and (= hour 12) (not pm))
17257 (setq hour 0)
17258 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17259 (setq ans (replace-match (format "%02d:%02d" hour minute)
17260 t t ans))))
17262 ;; Check if a time range is given as a duration
17263 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17264 (setq hour (string-to-number (match-string 1 ans))
17265 h2 (+ hour (string-to-number (match-string 3 ans)))
17266 minute (string-to-number (match-string 2 ans))
17267 m2 (+ minute (if (match-end 5) (string-to-number
17268 (match-string 5 ans))0)))
17269 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17270 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17271 t t ans)))
17273 ;; Check if there is a time range
17274 (when (boundp 'org-end-time-was-given)
17275 (setq org-time-was-given nil)
17276 (when (and (string-match org-plain-time-of-day-regexp ans)
17277 (match-end 8))
17278 (setq org-end-time-was-given (match-string 8 ans))
17279 (setq ans (concat (substring ans 0 (match-beginning 7))
17280 (substring ans (match-end 7))))))
17282 (setq tl (parse-time-string ans)
17283 day (or (nth 3 tl) (nth 3 org-defdecode))
17284 month
17285 (cond ((nth 4 tl))
17286 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17287 ;; Day was specified. Make sure DAY+MONTH
17288 ;; combination happens in the future.
17289 ((nth 3 tl)
17290 (setq futurep t)
17291 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17292 (nth 4 nowdecode)))
17293 (t (nth 4 org-defdecode)))
17294 year
17295 (cond ((and (not kill-year) (nth 5 tl)))
17296 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17297 ;; Month was guessed in the future and is at least
17298 ;; equal to NOWDECODE's. Fix year accordingly.
17299 (futurep
17300 (if (or (> month (nth 4 nowdecode))
17301 (>= day (nth 3 nowdecode)))
17302 (nth 5 nowdecode)
17303 (1+ (nth 5 nowdecode))))
17304 ;; Month was specified. Make sure MONTH+YEAR
17305 ;; combination happens in the future.
17306 ((nth 4 tl)
17307 (setq futurep t)
17308 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17309 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17310 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17311 (t (nth 5 nowdecode))))
17312 (t (nth 5 org-defdecode)))
17313 hour (or (nth 2 tl) (nth 2 org-defdecode))
17314 minute (or (nth 1 tl) (nth 1 org-defdecode))
17315 second (or (nth 0 tl) 0)
17316 wday (nth 6 tl))
17318 (when (and (eq org-read-date-prefer-future 'time)
17319 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17320 (equal day (nth 3 nowdecode))
17321 (equal month (nth 4 nowdecode))
17322 (equal year (nth 5 nowdecode))
17323 (nth 2 tl)
17324 (or (< (nth 2 tl) (nth 2 nowdecode))
17325 (and (= (nth 2 tl) (nth 2 nowdecode))
17326 (nth 1 tl)
17327 (< (nth 1 tl) (nth 1 nowdecode)))))
17328 (setq day (1+ day)
17329 futurep t))
17331 ;; Special date definitions below
17332 (cond
17333 (iso-week
17334 ;; There was an iso week
17335 (require 'cal-iso)
17336 (setq futurep nil)
17337 (setq year (or iso-year year)
17338 day (or iso-weekday wday 1)
17339 wday nil ; to make sure that the trigger below does not match
17340 iso-date (calendar-gregorian-from-absolute
17341 (calendar-iso-to-absolute
17342 (list iso-week day year))))
17343 ; FIXME: Should we also push ISO weeks into the future?
17344 ; (when (and org-read-date-prefer-future
17345 ; (not iso-year)
17346 ; (< (calendar-absolute-from-gregorian iso-date)
17347 ; (time-to-days (current-time))))
17348 ; (setq year (1+ year)
17349 ; iso-date (calendar-gregorian-from-absolute
17350 ; (calendar-iso-to-absolute
17351 ; (list iso-week day year)))))
17352 (setq month (car iso-date)
17353 year (nth 2 iso-date)
17354 day (nth 1 iso-date)))
17355 (deltan
17356 (setq futurep nil)
17357 (unless deltadef
17358 ;; Pass `current-time' result to `decode-time' (instead of
17359 ;; calling without arguments) so that only `current-time' has
17360 ;; to be overriden in tests.
17361 (let ((now (decode-time (current-time))))
17362 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17363 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17364 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17365 ((equal deltaw "m") (setq month (+ month deltan)))
17366 ((equal deltaw "y") (setq year (+ year deltan)))))
17367 ((and wday (not (nth 3 tl)))
17368 ;; Weekday was given, but no day, so pick that day in the week
17369 ;; on or after the derived date.
17370 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17371 (unless (equal wday wday1)
17372 (setq day (+ day (% (- wday wday1 -7) 7))))))
17373 (when (and (boundp 'org-time-was-given)
17374 (nth 2 tl))
17375 (setq org-time-was-given t))
17376 (when (< year 100) (setq year (+ 2000 year)))
17377 ;; Check of the date is representable
17378 (if org-read-date-force-compatible-dates
17379 (progn
17380 (when (< year 1970)
17381 (setq year 1970 org-read-date-analyze-forced-year t))
17382 (when (> year 2037)
17383 (setq year 2037 org-read-date-analyze-forced-year t)))
17384 (condition-case nil
17385 (ignore (encode-time second minute hour day month year))
17386 (error
17387 (setq year (nth 5 org-defdecode))
17388 (setq org-read-date-analyze-forced-year t))))
17389 (setq org-read-date-analyze-futurep futurep)
17390 (list second minute hour day month year)))
17392 (defvar parse-time-weekdays)
17393 (defun org-read-date-get-relative (s today default)
17394 "Check string S for special relative date string.
17395 TODAY and DEFAULT are internal times, for today and for a default.
17396 Return shift list (N what def-flag)
17397 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17398 N is the number of WHATs to shift.
17399 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17400 the DEFAULT date rather than TODAY."
17401 (require 'parse-time)
17402 (when (and
17403 (string-match
17404 (concat
17405 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17406 "\\([0-9]+\\)?"
17407 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17408 "\\([ \t]\\|$\\)") s)
17409 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17410 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17411 (string-to-char (substring (match-string 1 s) -1))
17412 ?+))
17413 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17414 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17415 (what (if (match-end 3) (match-string 3 s) "d"))
17416 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17417 (date (if rel default today))
17418 (wday (nth 6 (decode-time date)))
17419 delta)
17420 (if wday1
17421 (progn
17422 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17423 (when (= delta 0) (setq delta 7))
17424 (when (= dir ?-)
17425 (setq delta (- delta 7))
17426 (when (= delta 0) (setq delta -7)))
17427 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17428 (list delta "d" rel))
17429 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17431 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17432 "Turn a user-specified date into the internal representation.
17433 The internal representation needed by the calendar is (month day year).
17434 This is a wrapper to handle the brain-dead convention in calendar that
17435 user function argument order change dependent on argument order."
17436 (pcase calendar-date-style
17437 (`american (list arg1 arg2 arg3))
17438 (`european (list arg2 arg1 arg3))
17439 (`iso (list arg2 arg3 arg1))))
17441 (defun org-eval-in-calendar (form &optional keepdate)
17442 "Eval FORM in the calendar window and return to current window.
17443 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17444 (let ((sf (selected-frame))
17445 (sw (selected-window)))
17446 (select-window (get-buffer-window "*Calendar*" t))
17447 (eval form)
17448 (when (and (not keepdate) (calendar-cursor-to-date))
17449 (let* ((date (calendar-cursor-to-date))
17450 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17451 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17452 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17453 (select-window sw)
17454 (select-frame-set-input-focus sf)))
17456 (defun org-calendar-select ()
17457 "Return to `org-read-date' with the date currently selected.
17458 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17459 (interactive)
17460 (when (calendar-cursor-to-date)
17461 (let* ((date (calendar-cursor-to-date))
17462 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17463 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17464 (when (active-minibuffer-window) (exit-minibuffer))))
17466 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17467 "Insert a date stamp for the date given by the internal TIME.
17468 See `format-time-string' for the format of TIME.
17469 WITH-HM means use the stamp format that includes the time of the day.
17470 INACTIVE means use square brackets instead of angular ones, so that the
17471 stamp will not contribute to the agenda.
17472 PRE and POST are optional strings to be inserted before and after the
17473 stamp.
17474 The command returns the inserted time stamp."
17475 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17476 stamp)
17477 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17478 (insert-before-markers (or pre ""))
17479 (when (listp extra)
17480 (setq extra (car extra))
17481 (if (and (stringp extra)
17482 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17483 (setq extra (format "-%02d:%02d"
17484 (string-to-number (match-string 1 extra))
17485 (string-to-number (match-string 2 extra))))
17486 (setq extra nil)))
17487 (when extra
17488 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17489 (insert-before-markers (setq stamp (format-time-string fmt time)))
17490 (insert-before-markers (or post ""))
17491 (setq org-last-inserted-timestamp stamp)))
17493 (defun org-toggle-time-stamp-overlays ()
17494 "Toggle the use of custom time stamp formats."
17495 (interactive)
17496 (setq org-display-custom-times (not org-display-custom-times))
17497 (unless org-display-custom-times
17498 (let ((p (point-min)) (bmp (buffer-modified-p)))
17499 (while (setq p (next-single-property-change p 'display))
17500 (when (and (get-text-property p 'display)
17501 (eq (get-text-property p 'face) 'org-date))
17502 (remove-text-properties
17503 p (setq p (next-single-property-change p 'display))
17504 '(display t))))
17505 (set-buffer-modified-p bmp)))
17506 (org-restart-font-lock)
17507 (setq org-table-may-need-update t)
17508 (if org-display-custom-times
17509 (message "Time stamps are overlaid with custom format")
17510 (message "Time stamp overlays removed")))
17512 (defun org-display-custom-time (beg end)
17513 "Overlay modified time stamp format over timestamp between BEG and END."
17514 (let* ((ts (buffer-substring beg end))
17515 t1 w1 with-hm tf time str w2 (off 0))
17516 (save-match-data
17517 (setq t1 (org-parse-time-string ts t))
17518 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17519 (setq off (- (match-end 0) (match-beginning 0)))))
17520 (setq end (- end off))
17521 (setq w1 (- end beg)
17522 with-hm (and (nth 1 t1) (nth 2 t1))
17523 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17524 time (org-fix-decoded-time t1)
17525 str (org-add-props
17526 (format-time-string
17527 (substring tf 1 -1) (apply 'encode-time time))
17528 nil 'mouse-face 'highlight)
17529 w2 (length str))
17530 (unless (= w2 w1)
17531 (add-text-properties (1+ beg) (+ 2 beg)
17532 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17533 (put-text-property beg end 'display str)))
17535 (defun org-fix-decoded-time (time)
17536 "Set 0 instead of nil for the first 6 elements of time.
17537 Don't touch the rest."
17538 (let ((n 0))
17539 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17541 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17542 "Difference between TIMESTAMP-STRING and now in days.
17543 If SECONDS is non-nil, return the difference in seconds."
17544 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17545 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17546 (funcall fdiff (current-time)))))
17548 (defun org-deadline-close-p (timestamp-string &optional ndays)
17549 "Is the time in TIMESTAMP-STRING close to the current date?"
17550 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17551 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17552 (not (org-entry-is-done-p))))
17554 (defun org-get-wdays (ts &optional delay zero-delay)
17555 "Get the deadline lead time appropriate for timestring TS.
17556 When DELAY is non-nil, get the delay time for scheduled items
17557 instead of the deadline lead time. When ZERO-DELAY is non-nil
17558 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17559 don't try to find the delay cookie in the scheduled timestamp."
17560 (let ((tv (if delay org-scheduled-delay-days
17561 org-deadline-warning-days)))
17562 (cond
17563 ((or (and delay (< tv 0))
17564 (and delay zero-delay (<= tv 0))
17565 (and (not delay) (<= tv 0)))
17566 ;; Enforce this value no matter what
17567 (- tv))
17568 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17569 ;; lead time is specified.
17570 (floor (* (string-to-number (match-string 1 ts))
17571 (cdr (assoc (match-string 2 ts)
17572 '(("d" . 1) ("w" . 7)
17573 ("m" . 30.4) ("y" . 365.25)
17574 ("h" . 0.041667)))))))
17575 ;; go for the default.
17576 (t tv))))
17578 (defun org-calendar-select-mouse (ev)
17579 "Return to `org-read-date' with the date currently selected.
17580 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17581 (interactive "e")
17582 (mouse-set-point ev)
17583 (when (calendar-cursor-to-date)
17584 (let* ((date (calendar-cursor-to-date))
17585 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17586 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17587 (when (active-minibuffer-window) (exit-minibuffer))))
17589 (defun org-check-deadlines (ndays)
17590 "Check if there are any deadlines due or past due.
17591 A deadline is considered due if it happens within `org-deadline-warning-days'
17592 days from today's date. If the deadline appears in an entry marked DONE,
17593 it is not shown. The prefix arg NDAYS can be used to test that many
17594 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17595 (interactive "P")
17596 (let* ((org-warn-days
17597 (cond
17598 ((equal ndays '(4)) 100000)
17599 (ndays (prefix-numeric-value ndays))
17600 (t (abs org-deadline-warning-days))))
17601 (case-fold-search nil)
17602 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17603 (callback
17604 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17605 (message "%d deadlines past-due or due within %d days"
17606 (org-occur regexp nil callback)
17607 org-warn-days)))
17609 (defsubst org-re-timestamp (type)
17610 "Return a regexp for timestamp TYPE.
17611 Allowed values for TYPE are:
17613 all: all timestamps
17614 active: only active timestamps (<...>)
17615 inactive: only inactive timestamps ([...])
17616 scheduled: only scheduled timestamps
17617 deadline: only deadline timestamps
17618 closed: only closed time-stamps
17620 When TYPE is nil, fall back on returning a regexp that matches
17621 both scheduled and deadline timestamps."
17622 (cl-case type
17623 (all org-ts-regexp-both)
17624 (active org-ts-regexp)
17625 (inactive org-ts-regexp-inactive)
17626 (scheduled org-scheduled-time-regexp)
17627 (deadline org-deadline-time-regexp)
17628 (closed org-closed-time-regexp)
17629 (otherwise
17630 (concat "\\<"
17631 (regexp-opt (list org-deadline-string org-scheduled-string))
17632 " *<\\([^>]+\\)>"))))
17634 (defun org-check-before-date (d)
17635 "Check if there are deadlines or scheduled entries before date D."
17636 (interactive (list (org-read-date)))
17637 (let* ((case-fold-search nil)
17638 (regexp (org-re-timestamp org-ts-type))
17639 (ts-type org-ts-type)
17640 (callback
17641 (lambda ()
17642 (let ((match (match-string 1)))
17643 (and (if (memq ts-type '(active inactive all))
17644 (eq (org-element-type (save-excursion
17645 (backward-char)
17646 (org-element-context)))
17647 'timestamp)
17648 (org-at-planning-p))
17649 (time-less-p
17650 (org-time-string-to-time match)
17651 (org-time-string-to-time d)))))))
17652 (message "%d entries before %s"
17653 (org-occur regexp nil callback)
17654 d)))
17656 (defun org-check-after-date (d)
17657 "Check if there are deadlines or scheduled entries after date D."
17658 (interactive (list (org-read-date)))
17659 (let* ((case-fold-search nil)
17660 (regexp (org-re-timestamp org-ts-type))
17661 (ts-type org-ts-type)
17662 (callback
17663 (lambda ()
17664 (let ((match (match-string 1)))
17665 (and (if (memq ts-type '(active inactive all))
17666 (eq (org-element-type (save-excursion
17667 (backward-char)
17668 (org-element-context)))
17669 'timestamp)
17670 (org-at-planning-p))
17671 (not (time-less-p
17672 (org-time-string-to-time match)
17673 (org-time-string-to-time d))))))))
17674 (message "%d entries after %s"
17675 (org-occur regexp nil callback)
17676 d)))
17678 (defun org-check-dates-range (start-date end-date)
17679 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17680 (interactive (list (org-read-date nil nil nil "Range starts")
17681 (org-read-date nil nil nil "Range end")))
17682 (let ((case-fold-search nil)
17683 (regexp (org-re-timestamp org-ts-type))
17684 (callback
17685 (let ((type org-ts-type))
17686 (lambda ()
17687 (let ((match (match-string 1)))
17688 (and
17689 (if (memq type '(active inactive all))
17690 (eq (org-element-type (save-excursion
17691 (backward-char)
17692 (org-element-context)))
17693 'timestamp)
17694 (org-at-planning-p))
17695 (not (time-less-p
17696 (org-time-string-to-time match)
17697 (org-time-string-to-time start-date)))
17698 (time-less-p
17699 (org-time-string-to-time match)
17700 (org-time-string-to-time end-date))))))))
17701 (message "%d entries between %s and %s"
17702 (org-occur regexp nil callback) start-date end-date)))
17704 (defun org-evaluate-time-range (&optional to-buffer)
17705 "Evaluate a time range by computing the difference between start and end.
17706 Normally the result is just printed in the echo area, but with prefix arg
17707 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17708 If the time range is actually in a table, the result is inserted into the
17709 next column.
17710 For time difference computation, a year is assumed to be exactly 365
17711 days in order to avoid rounding problems."
17712 (interactive "P")
17714 (org-clock-update-time-maybe)
17715 (save-excursion
17716 (unless (org-at-date-range-p t)
17717 (goto-char (point-at-bol))
17718 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17719 (unless (org-at-date-range-p t)
17720 (user-error "Not at a time-stamp range, and none found in current line")))
17721 (let* ((ts1 (match-string 1))
17722 (ts2 (match-string 2))
17723 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17724 (match-end (match-end 0))
17725 (time1 (org-time-string-to-time ts1))
17726 (time2 (org-time-string-to-time ts2))
17727 (t1 (float-time time1))
17728 (t2 (float-time time2))
17729 (diff (abs (- t2 t1)))
17730 (negative (< (- t2 t1) 0))
17731 ;; (ys (floor (* 365 24 60 60)))
17732 (ds (* 24 60 60))
17733 (hs (* 60 60))
17734 (fy "%dy %dd %02d:%02d")
17735 (fy1 "%dy %dd")
17736 (fd "%dd %02d:%02d")
17737 (fd1 "%dd")
17738 (fh "%02d:%02d")
17739 y d h m align)
17740 (if havetime
17741 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17743 d (floor (/ diff ds)) diff (mod diff ds)
17744 h (floor (/ diff hs)) diff (mod diff hs)
17745 m (floor (/ diff 60)))
17746 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17748 d (floor (+ (/ diff ds) 0.5))
17749 h 0 m 0))
17750 (if (not to-buffer)
17751 (message "%s" (org-make-tdiff-string y d h m))
17752 (if (org-at-table-p)
17753 (progn
17754 (goto-char match-end)
17755 (setq align t)
17756 (and (looking-at " *|") (goto-char (match-end 0))))
17757 (goto-char match-end))
17758 (when (looking-at
17759 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17760 (replace-match ""))
17761 (when negative (insert " -"))
17762 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17763 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17764 (insert " " (format fh h m))))
17765 (when align (org-table-align))
17766 (message "Time difference inserted")))))
17768 (defun org-make-tdiff-string (y d h m)
17769 (let ((fmt "")
17770 (l nil))
17771 (when (> y 0)
17772 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17773 (push y l))
17774 (when (> d 0)
17775 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17776 (push d l))
17777 (when (> h 0)
17778 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17779 (push h l))
17780 (when (> m 0)
17781 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17782 (push m l))
17783 (apply 'format fmt (nreverse l))))
17785 (defun org-time-string-to-time (s &optional buffer pos)
17786 "Convert a timestamp string into internal time."
17787 (condition-case errdata
17788 (apply 'encode-time (org-parse-time-string s))
17789 (error (error "Bad timestamp `%s'%s\nError was: %s"
17790 s (if (not (and buffer pos))
17792 (format-message " at %d in buffer `%s'" pos buffer))
17793 (cdr errdata)))))
17795 (defun org-time-string-to-seconds (s)
17796 "Convert a timestamp string to a number of seconds."
17797 (float-time (org-time-string-to-time s)))
17799 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17801 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17802 "Convert time stamp S to an absolute day number.
17804 If DAYNR in non-nil, and there is a specifier for a cyclic time
17805 stamp, get the closest date to DAYNR. If PREFER is
17806 `past' (respectively `future') return a date past (respectively
17807 after) or equal to DAYNR.
17809 POS is the location of time stamp S, as a buffer position in
17810 BUFFER.
17812 Diary sexp timestamps are matched against DAYNR, when non-nil.
17813 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17814 signalled."
17815 (cond
17816 ((string-match "\\`%%\\((.*)\\)" s)
17817 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17818 ;; only able to match individual dates. If it fails, raise an
17819 ;; error.
17820 (if (and daynr
17821 (org-diary-sexp-entry
17822 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17823 daynr
17824 (signal 'org-diary-sexp-no-match (list s))))
17825 ((and daynr show-all) (org-closest-date s daynr prefer))
17826 (t (time-to-days
17827 (condition-case errdata
17828 (apply #'encode-time (org-parse-time-string s))
17829 (error (error "Bad timestamp `%s'%s\nError was: %s"
17831 (if (not (and buffer pos)) ""
17832 (format-message " at %d in buffer `%s'" pos buffer))
17833 (cdr errdata))))))))
17835 (defun org-days-to-iso-week (days)
17836 "Return the iso week number."
17837 (require 'cal-iso)
17838 (car (calendar-iso-from-absolute days)))
17840 (defun org-small-year-to-year (year)
17841 "Convert 2-digit years into 4-digit years.
17842 YEAR is expanded into one of the 30 next years, if possible, or
17843 into a past one. Any year larger than 99 is returned unchanged."
17844 (if (>= year 100) year
17845 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17846 (century (/ current 100))
17847 (offset (- year (% current 100))))
17848 (cond ((> offset 30) (+ (* (1- century) 100) year))
17849 ((> offset -70) (+ (* century 100) year))
17850 (t (+ (* (1+ century) 100) year))))))
17852 (defun org-time-from-absolute (d)
17853 "Return the time corresponding to date D.
17854 D may be an absolute day number, or a calendar-type list (month day year)."
17855 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17856 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17858 (defvar org-agenda-current-date)
17859 (defun org-calendar-holiday ()
17860 "List of holidays, for Diary display in Org mode."
17861 (require 'holidays)
17862 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17863 (and hl (mapconcat #'identity hl "; "))))
17865 (defun org-diary-sexp-entry (sexp entry d)
17866 "Process a SEXP diary ENTRY for date D."
17867 (require 'diary-lib)
17868 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17869 ;; dynamically.
17870 (let* ((sexp `(let ((entry ,entry)
17871 (date ',d))
17872 ,(car (read-from-string sexp))))
17873 (result (if calendar-debug-sexp (eval sexp)
17874 (condition-case nil
17875 (eval sexp)
17876 (error
17877 (beep)
17878 (message "Bad sexp at line %d in %s: %s"
17879 (org-current-line)
17880 (buffer-file-name) sexp)
17881 (sleep-for 2))))))
17882 (cond ((stringp result) (split-string result "; "))
17883 ((and (consp result)
17884 (not (consp (cdr result)))
17885 (stringp (cdr result))) (cdr result))
17886 ((and (consp result)
17887 (stringp (car result))) result)
17888 (result entry))))
17890 (defun org-diary-to-ical-string (frombuf)
17891 "Get iCalendar entries from diary entries in buffer FROMBUF.
17892 This uses the icalendar.el library."
17893 (let* ((tmpdir temporary-file-directory)
17894 (tmpfile (make-temp-name
17895 (expand-file-name "orgics" tmpdir)))
17896 buf rtn b e)
17897 (with-current-buffer frombuf
17898 (icalendar-export-region (point-min) (point-max) tmpfile)
17899 (setq buf (find-buffer-visiting tmpfile))
17900 (set-buffer buf)
17901 (goto-char (point-min))
17902 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17903 (setq b (match-beginning 0)))
17904 (goto-char (point-max))
17905 (when (re-search-backward "^END:VEVENT" nil t)
17906 (setq e (match-end 0)))
17907 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17908 (kill-buffer buf)
17909 (delete-file tmpfile)
17910 rtn))
17912 (defun org-closest-date (start current prefer)
17913 "Return closest date to CURRENT starting from START.
17915 CURRENT and START are both time stamps.
17917 When PREFER is `past', return a date that is either CURRENT or
17918 past. When PREFER is `future', return a date that is either
17919 CURRENT or future.
17921 Only time stamps with a repeater are modified. Any other time
17922 stamp stay unchanged. In any case, return value is an absolute
17923 day number."
17924 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17925 ;; No repeater. Do not shift time stamp.
17926 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17927 (let ((value (string-to-number (match-string 1 start)))
17928 (type (match-string 2 start)))
17929 (if (= 0 value)
17930 ;; Repeater with a 0-value is considered as void.
17931 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17932 (let* ((base (org-date-to-gregorian start))
17933 (target (org-date-to-gregorian current))
17934 (sday (calendar-absolute-from-gregorian base))
17935 (cday (calendar-absolute-from-gregorian target))
17936 n1 n2)
17937 ;; If START is already past CURRENT, just return START.
17938 (if (<= cday sday) sday
17939 ;; Compute closest date before (N1) and closest date past
17940 ;; (N2) CURRENT.
17941 (pcase type
17942 ("h"
17943 (let ((missing-hours
17944 (mod (+ (- (* 24 (- cday sday))
17945 (nth 2 (org-parse-time-string start)))
17946 org-extend-today-until)
17947 value)))
17948 (setf n1 (if (= missing-hours 0) cday
17949 (- cday (1+ (/ missing-hours 24)))))
17950 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17951 ((or "d" "w")
17952 (let ((value (if (equal type "w") (* 7 value) value)))
17953 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17954 (setf n2 (+ n1 value))))
17955 ("m"
17956 (let* ((add-months
17957 (lambda (d n)
17958 ;; Add N months to gregorian date D, i.e.,
17959 ;; a list (MONTH DAY YEAR). Return a valid
17960 ;; gregorian date.
17961 (let ((m (+ (nth 0 d) n)))
17962 (list (mod m 12)
17963 (nth 1 d)
17964 (+ (/ m 12) (nth 2 d))))))
17965 (months ; Complete months to TARGET.
17966 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17967 (- (nth 0 target) (nth 0 base))
17968 ;; If START's day is greater than
17969 ;; TARGET's, remove incomplete month.
17970 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17971 value)
17972 value))
17973 (before (funcall add-months base months)))
17974 (setf n1 (calendar-absolute-from-gregorian before))
17975 (setf n2
17976 (calendar-absolute-from-gregorian
17977 (funcall add-months before value)))))
17979 (let* ((d (nth 1 base))
17980 (m (nth 0 base))
17981 (y (nth 2 base))
17982 (years ; Complete years to TARGET.
17983 (* (/ (- (nth 2 target)
17985 ;; If START's month and day are
17986 ;; greater than TARGET's, remove
17987 ;; incomplete year.
17988 (if (or (> (nth 0 target) m)
17989 (and (= (nth 0 target) m)
17990 (> (nth 1 target) d)))
17993 value)
17994 value))
17995 (before (list m d (+ y years))))
17996 (setf n1 (calendar-absolute-from-gregorian before))
17997 (setf n2 (calendar-absolute-from-gregorian
17998 (list m d (+ (nth 2 before) value)))))))
17999 ;; Handle PREFER parameter, if any.
18000 (cond
18001 ((eq prefer 'past) (if (= cday n2) n2 n1))
18002 ((eq prefer 'future) (if (= cday n1) n1 n2))
18003 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18005 (defun org-date-to-gregorian (d)
18006 "Turn any specification of date D into a Gregorian date for the calendar."
18007 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18008 ((and (listp d) (= (length d) 3)) d)
18009 ((stringp d)
18010 (let ((d (org-parse-time-string d)))
18011 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18012 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18014 (defun org-parse-time-string (s &optional nodefault)
18015 "Parse the standard Org-mode time string.
18016 This should be a lot faster than the normal `parse-time-string'.
18017 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18018 hour and minute fields will be nil if not given."
18019 (cond ((string-match org-ts-regexp0 s)
18020 (list 0
18021 (when (or (match-beginning 8) (not nodefault))
18022 (string-to-number (or (match-string 8 s) "0")))
18023 (when (or (match-beginning 7) (not nodefault))
18024 (string-to-number (or (match-string 7 s) "0")))
18025 (string-to-number (match-string 4 s))
18026 (string-to-number (match-string 3 s))
18027 (string-to-number (match-string 2 s))
18028 nil nil nil))
18029 ((string-match "^<[^>]+>$" s)
18030 (decode-time (seconds-to-time (org-matcher-time s))))
18031 (t (error "Not a standard Org-mode time string: %s" s))))
18033 (defun org-timestamp-up (&optional arg)
18034 "Increase the date item at the cursor by one.
18035 If the cursor is on the year, change the year. If it is on the month,
18036 the day or the time, change that.
18037 With prefix ARG, change by that many units."
18038 (interactive "p")
18039 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18041 (defun org-timestamp-down (&optional arg)
18042 "Decrease the date item at the cursor by one.
18043 If the cursor is on the year, change the year. If it is on the month,
18044 the day or the time, change that.
18045 With prefix ARG, change by that many units."
18046 (interactive "p")
18047 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18049 (defun org-timestamp-up-day (&optional arg)
18050 "Increase the date in the time stamp by one day.
18051 With prefix ARG, change that many days."
18052 (interactive "p")
18053 (if (and (not (org-at-timestamp-p t))
18054 (org-at-heading-p))
18055 (org-todo 'up)
18056 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18058 (defun org-timestamp-down-day (&optional arg)
18059 "Decrease the date in the time stamp by one day.
18060 With prefix ARG, change that many days."
18061 (interactive "p")
18062 (if (and (not (org-at-timestamp-p t))
18063 (org-at-heading-p))
18064 (org-todo 'down)
18065 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18067 (defun org-at-timestamp-p (&optional inactive-ok)
18068 "Non-nil if point is inside a timestamp.
18070 When optional argument INACTIVE-OK is non-nil, also consider
18071 inactive timestamps.
18073 When this function returns a non-nil value, match data is set
18074 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18075 INACTIVE-OK."
18076 (interactive)
18077 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18078 (pos (point))
18079 (ans (or (looking-at tsr)
18080 (save-excursion
18081 (skip-chars-backward "^[<\n\r\t")
18082 (when (> (point) (point-min)) (backward-char 1))
18083 (and (looking-at tsr)
18084 (> (- (match-end 0) pos) -1))))))
18085 (and ans
18086 (boundp 'org-ts-what)
18087 (setq org-ts-what
18088 (cond
18089 ((= pos (match-beginning 0)) 'bracket)
18090 ;; Point is considered to be "on the bracket" whether
18091 ;; it's really on it or right after it.
18092 ((= pos (1- (match-end 0))) 'bracket)
18093 ((= pos (match-end 0)) 'after)
18094 ((org-pos-in-match-range pos 2) 'year)
18095 ((org-pos-in-match-range pos 3) 'month)
18096 ((org-pos-in-match-range pos 7) 'hour)
18097 ((org-pos-in-match-range pos 8) 'minute)
18098 ((or (org-pos-in-match-range pos 4)
18099 (org-pos-in-match-range pos 5)) 'day)
18100 ((and (> pos (or (match-end 8) (match-end 5)))
18101 (< pos (match-end 0)))
18102 (- pos (or (match-end 8) (match-end 5))))
18103 (t 'day))))
18104 ans))
18106 (defun org-toggle-timestamp-type ()
18107 "Toggle the type (<active> or [inactive]) of a time stamp."
18108 (interactive)
18109 (when (org-at-timestamp-p t)
18110 (let ((beg (match-beginning 0)) (end (match-end 0))
18111 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18112 (save-excursion
18113 (goto-char beg)
18114 (while (re-search-forward "[][<>]" end t)
18115 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18116 t t)))
18117 (message "Timestamp is now %sactive"
18118 (if (equal (char-after beg) ?<) "" "in")))))
18120 (defun org-at-clock-log-p nil
18121 "Is the cursor on the clock log line?"
18122 (save-excursion
18123 (move-beginning-of-line 1)
18124 (looking-at org-clock-line-re)))
18126 (defvar org-clock-history) ; defined in org-clock.el
18127 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18128 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18129 "Change the date in the time stamp at point.
18130 The date will be changed by N times WHAT. WHAT can be `day', `month',
18131 `year', `minute', `second'. If WHAT is not given, the cursor position
18132 in the timestamp determines what will be changed.
18133 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18134 (let ((origin (point)) origin-cat
18135 with-hm inactive
18136 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18137 org-ts-what
18138 extra rem
18139 ts time time0 fixnext clrgx)
18140 (unless (org-at-timestamp-p t)
18141 (user-error "Not at a timestamp"))
18142 (if (and (not what) (eq org-ts-what 'bracket))
18143 (org-toggle-timestamp-type)
18144 ;; Point isn't on brackets. Remember the part of the time-stamp
18145 ;; the point was in. Indeed, size of time-stamps may change,
18146 ;; but point must be kept in the same category nonetheless.
18147 (setq origin-cat org-ts-what)
18148 (when (and (not what) (not (eq org-ts-what 'day))
18149 org-display-custom-times
18150 (get-text-property (point) 'display)
18151 (not (get-text-property (1- (point)) 'display)))
18152 (setq org-ts-what 'day))
18153 (setq org-ts-what (or what org-ts-what)
18154 inactive (= (char-after (match-beginning 0)) ?\[)
18155 ts (match-string 0))
18156 (replace-match "")
18157 (when (string-match
18158 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18160 (setq extra (match-string 1 ts))
18161 (when suppress-tmp-delay
18162 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18163 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18164 (setq with-hm t))
18165 (setq time0 (org-parse-time-string ts))
18166 (when (and updown
18167 (eq org-ts-what 'minute)
18168 (not current-prefix-arg))
18169 ;; This looks like s-up and s-down. Change by one rounding step.
18170 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18171 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18172 (setcar (cdr time0) (+ (nth 1 time0)
18173 (if (> n 0) (- rem) (- dm rem))))))
18174 (setq time
18175 (apply #'encode-time
18176 (or (car time0) 0)
18177 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18178 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18179 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18180 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18181 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18182 (nthcdr 6 time0)))
18183 (when (and (member org-ts-what '(hour minute))
18184 extra
18185 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18186 (setq extra (org-modify-ts-extra
18187 extra
18188 (if (eq org-ts-what 'hour) 2 5)
18189 n dm)))
18190 (when (integerp org-ts-what)
18191 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18192 (when (eq what 'calendar)
18193 (let ((cal-date (org-get-date-from-calendar)))
18194 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18195 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18196 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18197 (setcar time0 (or (car time0) 0))
18198 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18199 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18200 (setq time (apply 'encode-time time0))))
18201 ;; Insert the new time-stamp, and ensure point stays in the same
18202 ;; category as before (i.e. not after the last position in that
18203 ;; category).
18204 (let ((pos (point)))
18205 ;; Stay before inserted string. `save-excursion' is of no use.
18206 (setq org-last-changed-timestamp
18207 (org-insert-time-stamp time with-hm inactive nil nil extra))
18208 (goto-char pos))
18209 (save-match-data
18210 (looking-at org-ts-regexp3)
18211 (goto-char (cond
18212 ;; `day' category ends before `hour' if any, or at
18213 ;; the end of the day name.
18214 ((eq origin-cat 'day)
18215 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18216 ((eq origin-cat 'hour) (min (match-end 7) origin))
18217 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18218 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18219 ;; `year' and `month' have both fixed size: point
18220 ;; couldn't have moved into another part.
18221 (t origin))))
18222 ;; Update clock if on a CLOCK line.
18223 (org-clock-update-time-maybe)
18224 ;; Maybe adjust the closest clock in `org-clock-history'
18225 (when org-clock-adjust-closest
18226 (if (not (and (org-at-clock-log-p)
18227 (< 1 (length (delq nil (mapcar 'marker-position
18228 org-clock-history))))))
18229 (message "No clock to adjust")
18230 (cond ((save-excursion ; fix previous clock?
18231 (re-search-backward org-ts-regexp0 nil t)
18232 (looking-back (concat org-clock-string " \\[")
18233 (line-beginning-position)))
18234 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18235 ((save-excursion ; fix next clock?
18236 (re-search-backward org-ts-regexp0 nil t)
18237 (looking-at (concat org-ts-regexp0 "\\] =>")))
18238 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18239 (save-window-excursion
18240 ;; Find closest clock to point, adjust the previous/next one in history
18241 (let* ((p (save-excursion (org-back-to-heading t)))
18242 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18243 (clfixnth
18244 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18245 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18246 (if (not clfixpos)
18247 (message "No clock to adjust")
18248 (save-excursion
18249 (org-goto-marker-or-bmk clfixpos)
18250 (org-show-subtree)
18251 (when (re-search-forward clrgx nil t)
18252 (goto-char (match-beginning 1))
18253 (let (org-clock-adjust-closest)
18254 (org-timestamp-change n org-ts-what updown))
18255 (message "Clock adjusted in %s for heading: %s"
18256 (file-name-nondirectory (buffer-file-name))
18257 (org-get-heading t t)))))))))
18258 ;; Try to recenter the calendar window, if any.
18259 (when (and org-calendar-follow-timestamp-change
18260 (get-buffer-window "*Calendar*" t)
18261 (memq org-ts-what '(day month year)))
18262 (org-recenter-calendar (time-to-days time))))))
18264 (defun org-modify-ts-extra (s pos n dm)
18265 "Change the different parts of the lead-time and repeat fields in timestamp."
18266 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18267 ng h m new rem)
18268 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18269 (cond
18270 ((or (org-pos-in-match-range pos 2)
18271 (org-pos-in-match-range pos 3))
18272 (setq m (string-to-number (match-string 3 s))
18273 h (string-to-number (match-string 2 s)))
18274 (if (org-pos-in-match-range pos 2)
18275 (setq h (+ h n))
18276 (setq n (* dm (with-no-warnings (signum n))))
18277 (unless (= 0 (setq rem (% m dm)))
18278 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18279 (setq m (+ m n)))
18280 (when (< m 0) (setq m (+ m 60) h (1- h)))
18281 (when (> m 59) (setq m (- m 60) h (1+ h)))
18282 (setq h (mod h 24))
18283 (setq ng 1 new (format "-%02d:%02d" h m)))
18284 ((org-pos-in-match-range pos 6)
18285 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18286 ((org-pos-in-match-range pos 5)
18287 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18289 ((org-pos-in-match-range pos 9)
18290 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18291 ((org-pos-in-match-range pos 8)
18292 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18294 (when ng
18295 (setq s (concat
18296 (substring s 0 (match-beginning ng))
18298 (substring s (match-end ng))))))
18301 (defun org-recenter-calendar (d)
18302 "If the calendar is visible, recenter it to date D."
18303 (let ((cwin (get-buffer-window "*Calendar*" t)))
18304 (when cwin
18305 (let ((calendar-move-hook nil))
18306 (with-selected-window cwin
18307 (calendar-goto-date
18308 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18310 (defun org-goto-calendar (&optional arg)
18311 "Go to the Emacs calendar at the current date.
18312 If there is a time stamp in the current line, go to that date.
18313 A prefix ARG can be used to force the current date."
18314 (interactive "P")
18315 (let ((tsr org-ts-regexp) diff
18316 (calendar-move-hook nil)
18317 (calendar-view-holidays-initially-flag nil)
18318 (calendar-view-diary-initially-flag nil))
18319 (when (or (org-at-timestamp-p)
18320 (save-excursion
18321 (beginning-of-line 1)
18322 (looking-at (concat ".*" tsr))))
18323 (let ((d1 (time-to-days (current-time)))
18324 (d2 (time-to-days
18325 (org-time-string-to-time (match-string 1)))))
18326 (setq diff (- d2 d1))))
18327 (calendar)
18328 (calendar-goto-today)
18329 (when (and diff (not arg)) (calendar-forward-day diff))))
18331 (defun org-get-date-from-calendar ()
18332 "Return a list (month day year) of date at point in calendar."
18333 (with-current-buffer "*Calendar*"
18334 (save-match-data
18335 (calendar-cursor-to-date))))
18337 (defun org-date-from-calendar ()
18338 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18339 If there is already a time stamp at the cursor position, update it."
18340 (interactive)
18341 (if (org-at-timestamp-p t)
18342 (org-timestamp-change 0 'calendar)
18343 (let ((cal-date (org-get-date-from-calendar)))
18344 (org-insert-time-stamp
18345 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18347 (defcustom org-effort-durations
18348 `(("min" . 1)
18349 ("h" . 60)
18350 ("d" . ,(* 60 8))
18351 ("w" . ,(* 60 8 5))
18352 ("m" . ,(* 60 8 5 4))
18353 ("y" . ,(* 60 8 5 40)))
18354 "Conversion factor to minutes for an effort modifier.
18356 Each entry has the form (MODIFIER . MINUTES).
18358 In an effort string, a number followed by MODIFIER is multiplied
18359 by the specified number of MINUTES to obtain an effort in
18360 minutes.
18362 For example, if the value of this variable is ((\"hours\" . 60)), then an
18363 effort string \"2hours\" is equivalent to 120 minutes."
18364 :group 'org-agenda
18365 :version "25.1"
18366 :package-version '(Org . "8.3")
18367 :type '(alist :key-type (string :tag "Modifier")
18368 :value-type (number :tag "Minutes")))
18370 (defun org-minutes-to-clocksum-string (m)
18371 "Format number of minutes as a clocksum string.
18372 The format is determined by `org-time-clocksum-format',
18373 `org-time-clocksum-use-fractional' and
18374 `org-time-clocksum-fractional-format' and
18375 `org-time-clocksum-use-effort-durations'."
18376 (let ((clocksum "")
18377 (m (round m)) ; Don't allow fractions of minutes
18378 h d w mo y fmt n)
18379 (setq h (if org-time-clocksum-use-effort-durations
18380 (cdr (assoc "h" org-effort-durations)) 60)
18381 d (if org-time-clocksum-use-effort-durations
18382 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18383 w (if org-time-clocksum-use-effort-durations
18384 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18385 mo (if org-time-clocksum-use-effort-durations
18386 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18387 y (if org-time-clocksum-use-effort-durations
18388 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18389 ;; fractional format
18390 (if org-time-clocksum-use-fractional
18391 (cond
18392 ;; single format string
18393 ((stringp org-time-clocksum-fractional-format)
18394 (format org-time-clocksum-fractional-format (/ m (float h))))
18395 ;; choice of fractional formats for different time units
18396 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18397 (> (/ (truncate m) (* y d h)) 0))
18398 (format fmt (/ m (* y d (float h)))))
18399 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18400 (> (/ (truncate m) (* mo d h)) 0))
18401 (format fmt (/ m (* mo d (float h)))))
18402 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18403 (> (/ (truncate m) (* w d h)) 0))
18404 (format fmt (/ m (* w d (float h)))))
18405 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18406 (> (/ (truncate m) (* d h)) 0))
18407 (format fmt (/ m (* d (float h)))))
18408 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18409 (> (/ (truncate m) h) 0))
18410 (format fmt (/ m (float h))))
18411 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18412 (format fmt m))
18413 ;; fall back to smallest time unit with a format
18414 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18415 (format fmt (/ m (float h))))
18416 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18417 (format fmt (/ m (* d (float h)))))
18418 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18419 (format fmt (/ m (* w d (float h)))))
18420 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18421 (format fmt (/ m (* mo d (float h)))))
18422 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18423 (format fmt (/ m (* y d (float h))))))
18424 ;; standard (non-fractional) format, with single format string
18425 (if (stringp org-time-clocksum-format)
18426 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18427 ;; separate formats components
18428 (and (setq fmt (plist-get org-time-clocksum-format :years))
18429 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18430 (plist-get org-time-clocksum-format :require-years))
18431 (setq clocksum (concat clocksum (format fmt n))
18432 m (- m (* n y d h))))
18433 (and (setq fmt (plist-get org-time-clocksum-format :months))
18434 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18435 (plist-get org-time-clocksum-format :require-months))
18436 (setq clocksum (concat clocksum (format fmt n))
18437 m (- m (* n mo d h))))
18438 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18439 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18440 (plist-get org-time-clocksum-format :require-weeks))
18441 (setq clocksum (concat clocksum (format fmt n))
18442 m (- m (* n w d h))))
18443 (and (setq fmt (plist-get org-time-clocksum-format :days))
18444 (or (> (setq n (/ (truncate m) (* d h))) 0)
18445 (plist-get org-time-clocksum-format :require-days))
18446 (setq clocksum (concat clocksum (format fmt n))
18447 m (- m (* n d h))))
18448 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18449 (or (> (setq n (/ (truncate m) h)) 0)
18450 (plist-get org-time-clocksum-format :require-hours))
18451 (setq clocksum (concat clocksum (format fmt n))
18452 m (- m (* n h))))
18453 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18454 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18455 (setq clocksum (concat clocksum (format fmt m))))
18456 ;; return formatted time duration
18457 clocksum))))
18459 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18460 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18461 "Org mode version 8.0")
18463 (defun org-hours-to-clocksum-string (n)
18464 (org-minutes-to-clocksum-string (* n 60)))
18466 (defun org-hh:mm-string-to-minutes (s)
18467 "Convert a string H:MM to a number of minutes.
18468 If the string is just a number, interpret it as minutes.
18469 In fact, the first hh:mm or number in the string will be taken,
18470 there can be extra stuff in the string.
18471 If no number is found, the return value is 0."
18472 (cond
18473 ((integerp s) s)
18474 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18475 (+ (* (string-to-number (match-string 1 s)) 60)
18476 (string-to-number (match-string 2 s))))
18477 ((string-match "\\([0-9]+\\)" s)
18478 (string-to-number (match-string 1 s)))
18479 (t 0)))
18481 (defcustom org-image-actual-width t
18482 "Should we use the actual width of images when inlining them?
18484 When set to t, always use the image width.
18486 When set to a number, use imagemagick (when available) to set
18487 the image's width to this value.
18489 When set to a number in a list, try to get the width from any
18490 #+ATTR.* keyword if it matches a width specification like
18492 #+ATTR_HTML: :width 300px
18494 and fall back on that number if none is found.
18496 When set to nil, try to get the width from an #+ATTR.* keyword
18497 and fall back on the original width if none is found.
18499 This requires Emacs >= 24.1, build with imagemagick support."
18500 :group 'org-appearance
18501 :version "24.4"
18502 :package-version '(Org . "8.0")
18503 :type '(choice
18504 (const :tag "Use the image width" t)
18505 (integer :tag "Use a number of pixels")
18506 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18507 (const :tag "Use #+ATTR* or don't resize" nil)))
18509 (defcustom org-agenda-inhibit-startup nil
18510 "Inhibit startup when preparing agenda buffers.
18511 When this variable is t, the initialization of the Org agenda
18512 buffers is inhibited: e.g. the visibility state is not set, the
18513 tables are not re-aligned, etc."
18514 :type 'boolean
18515 :version "24.3"
18516 :group 'org-agenda)
18518 (defcustom org-agenda-ignore-properties nil
18519 "Avoid updating text properties when building the agenda.
18520 Properties are used to prepare buffers for effort estimates,
18521 appointments, statistics and subtree-local categories.
18522 If you don't use these in the agenda, you can add them to this
18523 list and agenda building will be a bit faster.
18524 The value is a list, with zero or more of the symbols `effort', `appt',
18525 `stats' or `category'."
18526 :type '(set :greedy t
18527 (const effort)
18528 (const appt)
18529 (const stats)
18530 (const category))
18531 :version "25.1"
18532 :package-version '(Org . "8.3")
18533 :group 'org-agenda)
18535 (defun org-duration-string-to-minutes (s &optional output-to-string)
18536 "Convert a duration string S to minutes.
18538 A bare number is interpreted as minutes, modifiers can be set by
18539 customizing `org-effort-durations' (which see).
18541 Entries containing a colon are interpreted as H:MM by
18542 `org-hh:mm-string-to-minutes'."
18543 (let ((result 0)
18544 (re (concat "\\([0-9.]+\\) *\\("
18545 (regexp-opt (mapcar 'car org-effort-durations))
18546 "\\)")))
18547 (while (string-match re s)
18548 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18549 (string-to-number (match-string 1 s))))
18550 (setq s (replace-match "" nil t s)))
18551 (setq result (floor result))
18552 (cl-incf result (org-hh:mm-string-to-minutes s))
18553 (if output-to-string (number-to-string result) result)))
18555 ;;;; Files
18557 (defun org-save-all-org-buffers ()
18558 "Save all Org-mode buffers without user confirmation."
18559 (interactive)
18560 (message "Saving all Org-mode buffers...")
18561 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18562 (when (featurep 'org-id) (org-id-locations-save))
18563 (message "Saving all Org-mode buffers... done"))
18565 (defun org-revert-all-org-buffers ()
18566 "Revert all Org-mode buffers.
18567 Prompt for confirmation when there are unsaved changes.
18568 Be sure you know what you are doing before letting this function
18569 overwrite your changes.
18571 This function is useful in a setup where one tracks org files
18572 with a version control system, to revert on one machine after pulling
18573 changes from another. I believe the procedure must be like this:
18575 1. M-x org-save-all-org-buffers
18576 2. Pull changes from the other machine, resolve conflicts
18577 3. M-x org-revert-all-org-buffers"
18578 (interactive)
18579 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18580 (user-error "Abort"))
18581 (save-excursion
18582 (save-window-excursion
18583 (dolist (b (buffer-list))
18584 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18585 (with-current-buffer b buffer-file-name))
18586 (pop-to-buffer-same-window b)
18587 (revert-buffer t 'no-confirm)))
18588 (when (and (featurep 'org-id) org-id-track-globally)
18589 (org-id-locations-load)))))
18591 ;;;; Agenda files
18593 ;;;###autoload
18594 (defun org-switchb (&optional arg)
18595 "Switch between Org buffers.
18597 With \\[universal-argument] prefix, restrict available buffers to files.
18599 With \\[universal-argument] \\[universal-argument] \
18600 prefix, restrict available buffers to agenda files."
18601 (interactive "P")
18602 (let ((blist (org-buffer-list
18603 (cond ((equal arg '(4)) 'files)
18604 ((equal arg '(16)) 'agenda)))))
18605 (pop-to-buffer-same-window
18606 (completing-read "Org buffer: "
18607 (mapcar #'list (mapcar #'buffer-name blist))
18608 nil t))))
18610 (defun org-buffer-list (&optional predicate exclude-tmp)
18611 "Return a list of Org buffers.
18612 PREDICATE can be `export', `files' or `agenda'.
18614 export restrict the list to Export buffers.
18615 files restrict the list to buffers visiting Org files.
18616 agenda restrict the list to buffers visiting agenda files.
18618 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18619 (let* ((bfn nil)
18620 (agenda-files (and (eq predicate 'agenda)
18621 (mapcar 'file-truename (org-agenda-files t))))
18622 (filter
18623 (cond
18624 ((eq predicate 'files)
18625 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18626 ((eq predicate 'export)
18627 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18628 ((eq predicate 'agenda)
18629 (lambda (b)
18630 (with-current-buffer b
18631 (and (derived-mode-p 'org-mode)
18632 (setq bfn (buffer-file-name b))
18633 (member (file-truename bfn) agenda-files)))))
18634 (t (lambda (b) (with-current-buffer b
18635 (or (derived-mode-p 'org-mode)
18636 (string-match "\\*Org .*Export"
18637 (buffer-name b)))))))))
18638 (delq nil
18639 (mapcar
18640 (lambda(b)
18641 (if (and (funcall filter b)
18642 (or (not exclude-tmp)
18643 (not (string-match "tmp" (buffer-name b)))))
18645 nil))
18646 (buffer-list)))))
18648 (defun org-agenda-files (&optional unrestricted archives)
18649 "Get the list of agenda files.
18650 Optional UNRESTRICTED means return the full list even if a restriction
18651 is currently in place.
18652 When ARCHIVES is t, include all archive files that are really being
18653 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18654 `org-agenda-archives-mode' is t."
18655 (let ((files
18656 (cond
18657 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18658 ((stringp org-agenda-files) (org-read-agenda-file-list))
18659 ((listp org-agenda-files) org-agenda-files)
18660 (t (error "Invalid value of `org-agenda-files'")))))
18661 (setq files (apply 'append
18662 (mapcar (lambda (f)
18663 (if (file-directory-p f)
18664 (directory-files
18665 f t org-agenda-file-regexp)
18666 (list f)))
18667 files)))
18668 (when org-agenda-skip-unavailable-files
18669 (setq files (delq nil
18670 (mapcar (function
18671 (lambda (file)
18672 (and (file-readable-p file) file)))
18673 files))))
18674 (when (or (eq archives t)
18675 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18676 (setq files (org-add-archive-files files)))
18677 files))
18679 (defun org-agenda-file-p (&optional file)
18680 "Return non-nil, if FILE is an agenda file.
18681 If FILE is omitted, use the file associated with the current
18682 buffer."
18683 (let ((fname (or file (buffer-file-name))))
18684 (and fname
18685 (member (file-truename fname)
18686 (mapcar #'file-truename (org-agenda-files t))))))
18688 (defun org-edit-agenda-file-list ()
18689 "Edit the list of agenda files.
18690 Depending on setup, this either uses customize to edit the variable
18691 `org-agenda-files', or it visits the file that is holding the list. In the
18692 latter case, the buffer is set up in a way that saving it automatically kills
18693 the buffer and restores the previous window configuration."
18694 (interactive)
18695 (if (stringp org-agenda-files)
18696 (let ((cw (current-window-configuration)))
18697 (find-file org-agenda-files)
18698 (setq-local org-window-configuration cw)
18699 (add-hook 'after-save-hook
18700 (lambda ()
18701 (set-window-configuration
18702 (prog1 org-window-configuration
18703 (kill-buffer (current-buffer))))
18704 (org-install-agenda-files-menu)
18705 (message "New agenda file list installed"))
18706 nil 'local)
18707 (message "%s" (substitute-command-keys
18708 "Edit list and finish with \\[save-buffer]")))
18709 (customize-variable 'org-agenda-files)))
18711 (defun org-store-new-agenda-file-list (list)
18712 "Set new value for the agenda file list and save it correctly."
18713 (if (stringp org-agenda-files)
18714 (let ((fe (org-read-agenda-file-list t)) b u)
18715 (while (setq b (find-buffer-visiting org-agenda-files))
18716 (kill-buffer b))
18717 (with-temp-file org-agenda-files
18718 (insert
18719 (mapconcat
18720 (lambda (f) ;; Keep un-expanded entries.
18721 (if (setq u (assoc f fe))
18722 (cdr u)
18724 list "\n")
18725 "\n")))
18726 (let ((org-mode-hook nil) (org-inhibit-startup t)
18727 (org-insert-mode-line-in-empty-file nil))
18728 (setq org-agenda-files list)
18729 (customize-save-variable 'org-agenda-files org-agenda-files))))
18731 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18732 "Read the list of agenda files from a file.
18733 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18734 filenames, used by `org-store-new-agenda-file-list' to write back
18735 un-expanded file names."
18736 (when (file-directory-p org-agenda-files)
18737 (error "`org-agenda-files' cannot be a single directory"))
18738 (when (stringp org-agenda-files)
18739 (with-temp-buffer
18740 (insert-file-contents org-agenda-files)
18741 (mapcar
18742 (lambda (f)
18743 (let ((e (expand-file-name (substitute-in-file-name f)
18744 org-directory)))
18745 (if pair-with-expansion
18746 (cons e f)
18747 e)))
18748 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18750 ;;;###autoload
18751 (defun org-cycle-agenda-files ()
18752 "Cycle through the files in `org-agenda-files'.
18753 If the current buffer visits an agenda file, find the next one in the list.
18754 If the current buffer does not, find the first agenda file."
18755 (interactive)
18756 (let* ((fs (or (org-agenda-files t)
18757 (user-error "No agenda files")))
18758 (files (copy-sequence fs))
18759 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18760 file)
18761 (when tcf
18762 (while (and (setq file (pop files))
18763 (not (equal (file-truename file) tcf)))))
18764 (find-file (car (or files fs)))
18765 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18767 (defun org-agenda-file-to-front (&optional to-end)
18768 "Move/add the current file to the top of the agenda file list.
18769 If the file is not present in the list, it is added to the front. If it is
18770 present, it is moved there. With optional argument TO-END, add/move to the
18771 end of the list."
18772 (interactive "P")
18773 (let ((org-agenda-skip-unavailable-files nil)
18774 (file-alist (mapcar (lambda (x)
18775 (cons (file-truename x) x))
18776 (org-agenda-files t)))
18777 (ctf (file-truename
18778 (or buffer-file-name
18779 (user-error "Please save the current buffer to a file"))))
18780 x had)
18781 (setq x (assoc ctf file-alist) had x)
18783 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18784 (if to-end
18785 (setq file-alist (append (delq x file-alist) (list x)))
18786 (setq file-alist (cons x (delq x file-alist))))
18787 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18788 (org-install-agenda-files-menu)
18789 (message "File %s to %s of agenda file list"
18790 (if had "moved" "added") (if to-end "end" "front"))))
18792 (defun org-remove-file (&optional file)
18793 "Remove current file from the list of files in variable `org-agenda-files'.
18794 These are the files which are being checked for agenda entries.
18795 Optional argument FILE means use this file instead of the current."
18796 (interactive)
18797 (let* ((org-agenda-skip-unavailable-files nil)
18798 (file (or file buffer-file-name
18799 (user-error "Current buffer does not visit a file")))
18800 (true-file (file-truename file))
18801 (afile (abbreviate-file-name file))
18802 (files (delq nil (mapcar
18803 (lambda (x)
18804 (unless (equal true-file
18805 (file-truename x))
18807 (org-agenda-files t)))))
18808 (if (not (= (length files) (length (org-agenda-files t))))
18809 (progn
18810 (org-store-new-agenda-file-list files)
18811 (org-install-agenda-files-menu)
18812 (message "Removed from Org Agenda list: %s" afile))
18813 (message "File was not in list: %s (not removed)" afile))))
18815 (defun org-file-menu-entry (file)
18816 (vector file (list 'find-file file) t))
18818 (defun org-check-agenda-file (file)
18819 "Make sure FILE exists. If not, ask user what to do."
18820 (unless (file-exists-p file)
18821 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18822 (abbreviate-file-name file))
18823 (let ((r (downcase (read-char-exclusive))))
18824 (cond
18825 ((equal r ?r)
18826 (org-remove-file file)
18827 (throw 'nextfile t))
18828 (t (user-error "Abort"))))))
18830 (defun org-get-agenda-file-buffer (file)
18831 "Get an agenda buffer visiting FILE.
18832 If the buffer needs to be created, add it to the list of buffers
18833 which might be released later."
18834 (let ((buf (org-find-base-buffer-visiting file)))
18835 (if buf
18836 buf ; just return it
18837 ;; Make a new buffer and remember it
18838 (setq buf (find-file-noselect file))
18839 (when buf (push buf org-agenda-new-buffers))
18840 buf)))
18842 (defun org-release-buffers (blist)
18843 "Release all buffers in list, asking the user for confirmation when needed.
18844 When a buffer is unmodified, it is just killed. When modified, it is saved
18845 \(if the user agrees) and then killed."
18846 (let (file)
18847 (dolist (buf blist)
18848 (setq file (buffer-file-name buf))
18849 (when (and (buffer-modified-p buf)
18850 file
18851 (y-or-n-p (format "Save file %s? " file)))
18852 (with-current-buffer buf (save-buffer)))
18853 (kill-buffer buf))))
18855 (defun org-agenda-prepare-buffers (files)
18856 "Create buffers for all agenda files, protect archived trees and comments."
18857 (interactive)
18858 (let ((pa '(:org-archived t))
18859 (pc '(:org-comment t))
18860 (pall '(:org-archived t :org-comment t))
18861 (inhibit-read-only t)
18862 (org-inhibit-startup org-agenda-inhibit-startup)
18863 (rea (concat ":" org-archive-tag ":"))
18864 re pos)
18865 (setq org-tag-alist-for-agenda nil
18866 org-tag-groups-alist-for-agenda nil)
18867 (save-excursion
18868 (save-restriction
18869 (dolist (file files)
18870 (catch 'nextfile
18871 (if (bufferp file)
18872 (set-buffer file)
18873 (org-check-agenda-file file)
18874 (set-buffer (org-get-agenda-file-buffer file)))
18875 (widen)
18876 (org-set-regexps-and-options 'tags-only)
18877 (setq pos (point))
18878 (or (memq 'category org-agenda-ignore-properties)
18879 (org-refresh-category-properties))
18880 (or (memq 'stats org-agenda-ignore-properties)
18881 (org-refresh-stats-properties))
18882 (or (memq 'effort org-agenda-ignore-properties)
18883 (org-refresh-effort-properties))
18884 (or (memq 'appt org-agenda-ignore-properties)
18885 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18886 (setq org-todo-keywords-for-agenda
18887 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18888 (setq org-done-keywords-for-agenda
18889 (append org-done-keywords-for-agenda org-done-keywords))
18890 (setq org-todo-keyword-alist-for-agenda
18891 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18892 (setq org-tag-alist-for-agenda
18893 (org-uniquify
18894 (append org-tag-alist-for-agenda
18895 org-current-tag-alist)))
18896 ;; Merge current file's tag groups into global
18897 ;; `org-tag-groups-alist-for-agenda'.
18898 (when org-group-tags
18899 (dolist (alist org-tag-groups-alist)
18900 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18901 (if old
18902 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18903 (push alist org-tag-groups-alist-for-agenda)))))
18904 (org-with-silent-modifications
18905 (save-excursion
18906 (remove-text-properties (point-min) (point-max) pall)
18907 (when org-agenda-skip-archived-trees
18908 (goto-char (point-min))
18909 (while (re-search-forward rea nil t)
18910 (when (org-at-heading-p t)
18911 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18912 (goto-char (point-min))
18913 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18914 (while (re-search-forward re nil t)
18915 (when (save-match-data (org-in-commented-heading-p t))
18916 (add-text-properties
18917 (match-beginning 0) (org-end-of-subtree t) pc)))))
18918 (goto-char pos)))))
18919 (setq org-todo-keywords-for-agenda
18920 (org-uniquify org-todo-keywords-for-agenda))
18921 (setq org-todo-keyword-alist-for-agenda
18922 (org-uniquify org-todo-keyword-alist-for-agenda))))
18925 ;;;; CDLaTeX minor mode
18927 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18928 "Keymap for the minor `org-cdlatex-mode'.")
18930 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18931 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18932 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18933 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18934 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18936 (defvar org-cdlatex-texmathp-advice-is-done nil
18937 "Flag remembering if we have applied the advice to texmathp already.")
18939 (define-minor-mode org-cdlatex-mode
18940 "Toggle the minor `org-cdlatex-mode'.
18941 This mode supports entering LaTeX environment and math in LaTeX fragments
18942 in Org-mode.
18943 \\{org-cdlatex-mode-map}"
18944 nil " OCDL" nil
18945 (when org-cdlatex-mode
18946 (require 'cdlatex)
18947 (run-hooks 'cdlatex-mode-hook)
18948 (cdlatex-compute-tables))
18949 (unless org-cdlatex-texmathp-advice-is-done
18950 (setq org-cdlatex-texmathp-advice-is-done t)
18951 (defadvice texmathp (around org-math-always-on activate)
18952 "Always return t in org-mode buffers.
18953 This is because we want to insert math symbols without dollars even outside
18954 the LaTeX math segments. If Orgmode thinks that point is actually inside
18955 an embedded LaTeX fragment, let texmathp do its job.
18956 \\[org-cdlatex-mode-map]"
18957 (interactive)
18958 (let (p)
18959 (cond
18960 ((not (derived-mode-p 'org-mode)) ad-do-it)
18961 ((eq this-command 'cdlatex-math-symbol)
18962 (setq ad-return-value t
18963 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18965 (let ((p (org-inside-LaTeX-fragment-p)))
18966 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18967 (setq ad-return-value t
18968 texmathp-why '("Org-mode embedded math" . 0))
18969 (when p ad-do-it)))))))))
18971 (defun turn-on-org-cdlatex ()
18972 "Unconditionally turn on `org-cdlatex-mode'."
18973 (org-cdlatex-mode 1))
18975 (defun org-try-cdlatex-tab ()
18976 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18977 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18978 - inside a LaTeX fragment, or
18979 - after the first word in a line, where an abbreviation expansion could
18980 insert a LaTeX environment."
18981 (when org-cdlatex-mode
18982 (cond
18983 ;; Before any word on the line: No expansion possible.
18984 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18985 ;; Just after first word on the line: Expand it. Make sure it
18986 ;; cannot happen on headlines, though.
18987 ((save-excursion
18988 (skip-chars-backward "a-zA-Z0-9*")
18989 (skip-chars-backward " \t")
18990 (and (bolp) (not (org-at-heading-p))))
18991 (cdlatex-tab) t)
18992 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18994 (defun org-cdlatex-underscore-caret (&optional _arg)
18995 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18996 Revert to the normal definition outside of these fragments."
18997 (interactive "P")
18998 (if (org-inside-LaTeX-fragment-p)
18999 (call-interactively 'cdlatex-sub-superscript)
19000 (let (org-cdlatex-mode)
19001 (call-interactively (key-binding (vector last-input-event))))))
19003 (defun org-cdlatex-math-modify (&optional _arg)
19004 "Execute `cdlatex-math-modify' in LaTeX fragments.
19005 Revert to the normal definition outside of these fragments."
19006 (interactive "P")
19007 (if (org-inside-LaTeX-fragment-p)
19008 (call-interactively 'cdlatex-math-modify)
19009 (let (org-cdlatex-mode)
19010 (call-interactively (key-binding (vector last-input-event))))))
19012 (defun org-cdlatex-environment-indent (&optional environment item)
19013 "Execute `cdlatex-environment' and indent the inserted environment.
19015 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19017 The inserted environment is indented to current indentation
19018 unless point is at the beginning of the line, in which the
19019 environment remains unintended."
19020 (interactive)
19021 ;; cdlatex-environment always return nil. Therefore, capture output
19022 ;; first and determine if an environment was selected.
19023 (let* ((beg (point-marker))
19024 (end (copy-marker (point) t))
19025 (inserted (progn
19026 (ignore-errors (cdlatex-environment environment item))
19027 (< beg end)))
19028 ;; Figure out how many lines to move forward after the
19029 ;; environment has been inserted.
19030 (lines (when inserted
19031 (save-excursion
19032 (- (cl-loop while (< beg (point))
19033 with x = 0
19034 do (forward-line -1)
19035 (cl-incf x)
19036 finally return x)
19037 (if (progn (goto-char beg)
19038 (and (progn (skip-chars-forward " \t") (eolp))
19039 (progn (skip-chars-backward " \t") (bolp))))
19040 1 0)))))
19041 (env (org-trim (delete-and-extract-region beg end))))
19042 (when inserted
19043 ;; Get indentation of next line unless at column 0.
19044 (let ((ind (if (bolp) 0
19045 (save-excursion
19046 (org-return-indent)
19047 (prog1 (org-get-indentation)
19048 (when (progn (skip-chars-forward " \t") (eolp))
19049 (delete-region beg (point)))))))
19050 (bol (progn (skip-chars-backward " \t") (bolp))))
19051 ;; Insert a newline before environment unless at column zero
19052 ;; to "escape" the current line. Insert a newline if
19053 ;; something is one the same line as \end{ENVIRONMENT}.
19054 (insert
19055 (concat (unless bol "\n") env
19056 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19057 (unless (zerop ind)
19058 (save-excursion
19059 (goto-char beg)
19060 (while (< (point) end)
19061 (unless (eolp) (indent-line-to ind))
19062 (forward-line))))
19063 (goto-char beg)
19064 (forward-line lines)
19065 (indent-line-to ind)))
19066 (set-marker beg nil)
19067 (set-marker end nil)))
19070 ;;;; LaTeX fragments
19072 (defun org-inside-LaTeX-fragment-p ()
19073 "Test if point is inside a LaTeX fragment.
19074 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19075 sequence appearing also before point.
19076 Even though the matchers for math are configurable, this function assumes
19077 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19078 delimiters are skipped when they have been removed by customization.
19079 The return value is nil, or a cons cell with the delimiter and the
19080 position of this delimiter.
19082 This function does a reasonably good job, but can locally be fooled by
19083 for example currency specifications. For example it will assume being in
19084 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19085 fragments that are properly closed, but during editing, we have to live
19086 with the uncertainty caused by missing closing delimiters. This function
19087 looks only before point, not after."
19088 (catch 'exit
19089 (let ((pos (point))
19090 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19091 (lim (progn
19092 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19093 (point)))
19094 dd-on str (start 0) m re)
19095 (goto-char pos)
19096 (when dodollar
19097 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19098 re (nth 1 (assoc "$" org-latex-regexps)))
19099 (while (string-match re str start)
19100 (cond
19101 ((= (match-end 0) (length str))
19102 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19103 ((= (match-end 0) (- (length str) 5))
19104 (throw 'exit nil))
19105 (t (setq start (match-end 0))))))
19106 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19107 (goto-char pos)
19108 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19109 (and (match-beginning 2) (throw 'exit nil))
19110 ;; count $$
19111 (while (re-search-backward "\\$\\$" lim t)
19112 (setq dd-on (not dd-on)))
19113 (goto-char pos)
19114 (when dd-on (cons "$$" m))))))
19116 (defun org-inside-latex-macro-p ()
19117 "Is point inside a LaTeX macro or its arguments?"
19118 (save-match-data
19119 (org-in-regexp
19120 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19122 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19123 "Build an overlay between BEG and END using IMAGE file.
19124 Argument IMAGETYPE is the extension of the displayed image,
19125 as a string. It defaults to \"png\"."
19126 (let ((ov (make-overlay beg end))
19127 (imagetype (or (intern imagetype) 'png)))
19128 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19129 (overlay-put ov 'evaporate t)
19130 (overlay-put ov
19131 'modification-hooks
19132 (list (lambda (o _flag _beg _end &optional _l)
19133 (delete-overlay o))))
19134 (overlay-put ov
19135 'display
19136 (list 'image :type imagetype :file image :ascent 'center))))
19138 (defun org--list-latex-overlays (&optional beg end)
19139 "List all Org LaTeX overlays in current buffer.
19140 Limit to overlays between BEG and END when those are provided."
19141 (cl-remove-if-not
19142 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19143 (overlays-in (or beg (point-min)) (or end (point-max)))))
19145 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19146 "Remove all overlays with LaTeX fragment images in current buffer.
19147 When optional arguments BEG and END are non-nil, remove all
19148 overlays between them instead. Return a non-nil value when some
19149 overlays were removed, nil otherwise."
19150 (let ((overlays (org--list-latex-overlays beg end)))
19151 (mapc #'delete-overlay overlays)
19152 overlays))
19154 (defun org-toggle-latex-fragment (&optional arg)
19155 "Preview the LaTeX fragment at point, or all locally or globally.
19157 If the cursor is on a LaTeX fragment, create the image and overlay
19158 it over the source code, if there is none. Remove it otherwise.
19159 If there is no fragment at point, display all fragments in the
19160 current section.
19162 With prefix ARG, preview or clear image for all fragments in the
19163 current subtree or in the whole buffer when used before the first
19164 headline. With a double prefix ARG \\[universal-argument] \
19165 \\[universal-argument] preview or clear images
19166 for all fragments in the buffer."
19167 (interactive "P")
19168 (when (display-graphic-p)
19169 (catch 'exit
19170 (save-excursion
19171 (let (beg end msg)
19172 (cond
19173 ((or (equal arg '(16))
19174 (and (equal arg '(4))
19175 (org-with-limited-levels (org-before-first-heading-p))))
19176 (if (org-remove-latex-fragment-image-overlays)
19177 (progn (message "LaTeX fragments images removed from buffer")
19178 (throw 'exit nil))
19179 (setq msg "Creating images for buffer...")))
19180 ((equal arg '(4))
19181 (org-with-limited-levels (org-back-to-heading t))
19182 (setq beg (point))
19183 (setq end (progn (org-end-of-subtree t) (point)))
19184 (if (org-remove-latex-fragment-image-overlays beg end)
19185 (progn
19186 (message "LaTeX fragment images removed from subtree")
19187 (throw 'exit nil))
19188 (setq msg "Creating images for subtree...")))
19189 ((let ((datum (org-element-context)))
19190 (when (memq (org-element-type datum)
19191 '(latex-environment latex-fragment))
19192 (setq beg (org-element-property :begin datum))
19193 (setq end (org-element-property :end datum))
19194 (if (org-remove-latex-fragment-image-overlays beg end)
19195 (progn (message "LaTeX fragment image removed")
19196 (throw 'exit nil))
19197 (setq msg "Creating image...")))))
19199 (org-with-limited-levels
19200 (setq beg (if (org-at-heading-p) (line-beginning-position)
19201 (outline-previous-heading)
19202 (point)))
19203 (setq end (progn (outline-next-heading) (point)))
19204 (if (org-remove-latex-fragment-image-overlays beg end)
19205 (progn
19206 (message "LaTeX fragment images removed from section")
19207 (throw 'exit nil))
19208 (setq msg "Creating images for section...")))))
19209 (let ((file (buffer-file-name (buffer-base-buffer))))
19210 (org-format-latex
19211 (concat org-preview-latex-image-directory "org-ltximg")
19212 beg end
19213 ;; Emacs cannot overlay images from remote hosts. Create
19214 ;; it in `temporary-file-directory' instead.
19215 (if (or (not file) (file-remote-p file))
19216 temporary-file-directory
19217 default-directory)
19218 'overlays msg 'forbuffer org-preview-latex-default-process))
19219 (message (concat msg "done")))))))
19221 (defun org-format-latex
19222 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19223 "Replace LaTeX fragments with links to an image.
19225 The function takes care of creating the replacement image.
19227 Only consider fragments between BEG and END when those are
19228 provided.
19230 When optional argument OVERLAYS is non-nil, display the image on
19231 top of the fragment instead of replacing it.
19233 PROCESSING-TYPE is the conversion method to use, as a symbol.
19235 Some of the options can be changed using the variable
19236 `org-format-latex-options', which see."
19237 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19238 (unless (eq processing-type 'verbatim)
19239 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19240 (cnt 0)
19241 checkdir-flag)
19242 (goto-char (or beg (point-min)))
19243 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19244 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19245 (overlay-recenter (or end (point-max))))
19246 (while (re-search-forward math-regexp end t)
19247 (unless (and overlays
19248 (eq (get-char-property (point) 'org-overlay-type)
19249 'org-latex-overlay))
19250 (let* ((context (org-element-context))
19251 (type (org-element-type context)))
19252 (when (memq type '(latex-environment latex-fragment))
19253 (let ((block-type (eq type 'latex-environment))
19254 (value (org-element-property :value context))
19255 (beg (org-element-property :begin context))
19256 (end (save-excursion
19257 (goto-char (org-element-property :end context))
19258 (skip-chars-backward " \r\t\n")
19259 (point))))
19260 (cond
19261 ((eq processing-type 'mathjax)
19262 ;; Prepare for MathJax processing.
19263 (if (not (string-match "\\`\\$\\$?" value))
19264 (goto-char end)
19265 (delete-region beg end)
19266 (if (string= (match-string 0 value) "$$")
19267 (insert "\\[" (substring value 2 -2) "\\]")
19268 (insert "\\(" (substring value 1 -1) "\\)"))))
19269 ((assq processing-type org-preview-latex-process-alist)
19270 ;; Process to an image.
19271 (cl-incf cnt)
19272 (goto-char beg)
19273 (let* ((processing-info
19274 (cdr (assq processing-type org-preview-latex-process-alist)))
19275 (face (face-at-point))
19276 ;; Get the colors from the face at point.
19278 (let ((color (plist-get org-format-latex-options
19279 :foreground)))
19280 (if (and forbuffer (eq color 'auto))
19281 (face-attribute face :foreground nil 'default)
19282 color)))
19284 (let ((color (plist-get org-format-latex-options
19285 :background)))
19286 (if (and forbuffer (eq color 'auto))
19287 (face-attribute face :background nil 'default)
19288 color)))
19289 (hash (sha1 (prin1-to-string
19290 (list org-format-latex-header
19291 org-latex-default-packages-alist
19292 org-latex-packages-alist
19293 org-format-latex-options
19294 forbuffer value fg bg))))
19295 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19296 (absprefix (expand-file-name prefix dir))
19297 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19298 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19299 (sep (and block-type "\n\n"))
19300 (link (concat sep "[[file:" linkfile "]]" sep))
19301 (options
19302 (org-combine-plists
19303 org-format-latex-options
19304 `(:foreground ,fg :background ,bg))))
19305 (when msg (message msg cnt))
19306 (unless checkdir-flag ; Ensure the directory exists.
19307 (setq checkdir-flag t)
19308 (let ((todir (file-name-directory absprefix)))
19309 (unless (file-directory-p todir)
19310 (make-directory todir t))))
19311 (unless (file-exists-p movefile)
19312 (org-create-formula-image
19313 value movefile options forbuffer processing-type))
19314 (if overlays
19315 (progn
19316 (dolist (o (overlays-in beg end))
19317 (when (eq (overlay-get o 'org-overlay-type)
19318 'org-latex-overlay)
19319 (delete-overlay o)))
19320 (org--format-latex-make-overlay beg end movefile imagetype)
19321 (goto-char end))
19322 (delete-region beg end)
19323 (insert
19324 (org-add-props link
19325 (list 'org-latex-src
19326 (replace-regexp-in-string "\"" "" value)
19327 'org-latex-src-embed-type
19328 (if block-type 'paragraph 'character)))))))
19329 ((eq processing-type 'mathml)
19330 ;; Process to MathML.
19331 (unless (org-format-latex-mathml-available-p)
19332 (user-error "LaTeX to MathML converter not configured"))
19333 (cl-incf cnt)
19334 (when msg (message msg cnt))
19335 (goto-char beg)
19336 (delete-region beg end)
19337 (insert (org-format-latex-as-mathml
19338 value block-type prefix dir)))
19340 (error "Unknown conversion process %s for LaTeX fragments"
19341 processing-type)))))))))))
19343 (defun org-create-math-formula (latex-frag &optional mathml-file)
19344 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19345 Use `org-latex-to-mathml-convert-command'. If the conversion is
19346 sucessful, return the portion between \"<math...> </math>\"
19347 elements otherwise return nil. When MATHML-FILE is specified,
19348 write the results in to that file. When invoked as an
19349 interactive command, prompt for LATEX-FRAG, with initial value
19350 set to the current active region and echo the results for user
19351 inspection."
19352 (interactive (list (let ((frag (when (org-region-active-p)
19353 (buffer-substring-no-properties
19354 (region-beginning) (region-end)))))
19355 (read-string "LaTeX Fragment: " frag nil frag))))
19356 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19357 (let* ((tmp-in-file
19358 (let ((file (file-relative-name
19359 (make-temp-name (expand-file-name "ltxmathml-in")))))
19360 (write-region latex-frag nil file)
19361 file))
19362 (tmp-out-file (file-relative-name
19363 (make-temp-name (expand-file-name "ltxmathml-out"))))
19364 (cmd (format-spec
19365 org-latex-to-mathml-convert-command
19366 `((?j . ,(and org-latex-to-mathml-jar-file
19367 (shell-quote-argument
19368 (expand-file-name
19369 org-latex-to-mathml-jar-file))))
19370 (?I . ,(shell-quote-argument tmp-in-file))
19371 (?i . ,latex-frag)
19372 (?o . ,(shell-quote-argument tmp-out-file)))))
19373 mathml shell-command-output)
19374 (when (called-interactively-p 'any)
19375 (unless (org-format-latex-mathml-available-p)
19376 (user-error "LaTeX to MathML converter not configured")))
19377 (message "Running %s" cmd)
19378 (setq shell-command-output (shell-command-to-string cmd))
19379 (setq mathml
19380 (when (file-readable-p tmp-out-file)
19381 (with-current-buffer (find-file-noselect tmp-out-file t)
19382 (goto-char (point-min))
19383 (when (re-search-forward
19384 (concat
19385 (regexp-quote
19386 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19387 "[^>]*?>"
19388 "\\(.\\|\n\\)*"
19389 "</math>")
19390 nil t)
19391 (prog1 (match-string 0) (kill-buffer))))))
19392 (cond
19393 (mathml
19394 (setq mathml
19395 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19396 (when mathml-file
19397 (write-region mathml nil mathml-file))
19398 (when (called-interactively-p 'any)
19399 (message mathml)))
19400 ((message "LaTeX to MathML conversion failed")
19401 (message shell-command-output)))
19402 (delete-file tmp-in-file)
19403 (when (file-exists-p tmp-out-file)
19404 (delete-file tmp-out-file))
19405 mathml))
19407 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19408 prefix &optional dir)
19409 "Use `org-create-math-formula' but check local cache first."
19410 (let* ((absprefix (expand-file-name prefix dir))
19411 (print-length nil) (print-level nil)
19412 (formula-id (concat
19413 "formula-"
19414 (sha1
19415 (prin1-to-string
19416 (list latex-frag
19417 org-latex-to-mathml-convert-command)))))
19418 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19419 (formula-cache-dir (file-name-directory formula-cache)))
19421 (unless (file-directory-p formula-cache-dir)
19422 (make-directory formula-cache-dir t))
19424 (unless (file-exists-p formula-cache)
19425 (org-create-math-formula latex-frag formula-cache))
19427 (if (file-exists-p formula-cache)
19428 ;; Successful conversion. Return the link to MathML file.
19429 (org-add-props
19430 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19431 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19432 'org-latex-src-embed-type (if latex-frag-type
19433 'paragraph 'character)))
19434 ;; Failed conversion. Return the LaTeX fragment verbatim
19435 latex-frag)))
19437 (declare-function org-export-get-backend "ox" (name))
19438 (declare-function org-export--get-global-options "ox" (&optional backend))
19439 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19440 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19441 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19442 (defun org-create-formula--latex-header ()
19443 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19444 (let ((info (org-combine-plists (org-export--get-global-options
19445 (org-export-get-backend 'latex))
19446 (org-export--get-inbuffer-options
19447 (org-export-get-backend 'latex)))))
19448 (org-latex-guess-babel-language
19449 (org-latex-guess-inputenc
19450 (org-splice-latex-header
19451 org-format-latex-header
19452 org-latex-default-packages-alist
19453 org-latex-packages-alist t
19454 (plist-get info :latex-header)))
19455 info)))
19457 (defun org--get-display-dpi ()
19458 "Get the DPI of the display.
19460 Assumes that the display has the same pixel width in the
19461 horizontal and vertical directions."
19462 (if (display-graphic-p)
19463 (round (/ (display-pixel-height)
19464 (/ (display-mm-height) 25.4)))
19465 (error "Attempt to calculate the dpi of a non-graphic display")))
19467 (defun org-create-formula-image
19468 (string tofile options buffer &optional processing-type)
19469 "Create an image from LaTeX source using external processes.
19471 The LaTeX STRING is saved to a temporary LaTeX file, then
19472 converted to an image file by process PROCESSING-TYPE defined in
19473 `org-preview-latex-process-alist'. A nil value defaults to
19474 `org-preview-latex-default-process'.
19476 The generated image file is eventually moved to TOFILE.
19478 The OPTIONS argument controls the size, foreground color and
19479 background color of the generated image.
19481 When BUFFER non-nil, this function is used for LaTeX previewing.
19482 Otherwise, it is used to deal with LaTeX snippets showed in
19483 a HTML file."
19484 (let* ((processing-type (or processing-type
19485 org-preview-latex-default-process))
19486 (processing-info
19487 (cdr (assq processing-type org-preview-latex-process-alist)))
19488 (programs (plist-get processing-info :programs))
19489 (error-message (or (plist-get processing-info :message) ""))
19490 (use-xcolor (plist-get processing-info :use-xcolor))
19491 (image-input-type (plist-get processing-info :image-input-type))
19492 (image-output-type (plist-get processing-info :image-output-type))
19493 (post-clean (or (plist-get processing-info :post-clean)
19494 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19495 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19496 (latex-header (or (plist-get processing-info :latex-header)
19497 (org-create-formula--latex-header)))
19498 (latex-compiler (plist-get processing-info :latex-compiler))
19499 (image-converter (plist-get processing-info :image-converter))
19500 (tmpdir temporary-file-directory)
19501 (texfilebase (make-temp-name
19502 (expand-file-name "orgtex" tmpdir)))
19503 (texfile (concat texfilebase ".tex"))
19504 (font-height (face-attribute 'default :height nil))
19505 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19506 '(1.0 . 1.0)))
19507 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19508 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19509 (dpi (* scale (floor (if buffer font-height 140.0))))
19510 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19511 "Black"))
19512 (bg (or (plist-get options (if buffer :background :html-background))
19513 "Transparent"))
19514 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19515 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19516 (dolist (program programs)
19517 (org-check-external-command program error-message))
19518 (if use-xcolor
19519 (progn (if (eq fg 'default)
19520 (setq fg (org-latex-color :foreground))
19521 (setq fg (org-latex-color-format fg)))
19522 (if (eq bg 'default)
19523 (setq bg (org-latex-color :background))
19524 (setq bg (org-latex-color-format
19525 (if (string= bg "Transparent") "white" bg))))
19526 (with-temp-file texfile
19527 (insert latex-header)
19528 (insert "\n\\begin{document}\n"
19529 "\\definecolor{fg}{rgb}{" fg "}\n"
19530 "\\definecolor{bg}{rgb}{" bg "}\n"
19531 "\n\\pagecolor{bg}\n"
19532 "\n{\\color{fg}\n"
19533 string
19534 "\n}\n"
19535 "\n\\end{document}\n")))
19536 (if (eq fg 'default)
19537 (setq fg (org-dvipng-color :foreground))
19538 (unless (string= fg "Transparent")
19539 (setq fg (org-dvipng-color-format fg))))
19540 (if (eq bg 'default)
19541 (setq bg (org-dvipng-color :background))
19542 (unless (string= bg "Transparent")
19543 (setq bg (org-dvipng-color-format bg))))
19544 (with-temp-file texfile
19545 (insert latex-header)
19546 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19548 (let* ((err-msg (format "Please adjust '%s' part of \
19549 `org-preview-latex-process-alist'."
19550 processing-type))
19551 (image-input-file
19552 (org-compile-file
19553 texfile latex-compiler image-input-type err-msg log-buf))
19554 (image-output-file
19555 (org-compile-file
19556 image-input-file image-converter image-output-type err-msg log-buf
19557 `((?F . ,(shell-quote-argument fg))
19558 (?B . ,(shell-quote-argument bg))
19559 (?D . ,(shell-quote-argument (format "%s" dpi)))
19560 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19561 (copy-file image-output-file tofile 'replace)
19562 (dolist (e post-clean)
19563 (when (file-exists-p (concat texfilebase e))
19564 (delete-file (concat texfilebase e))))
19565 image-output-file)))
19567 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19568 "Fill a LaTeX header template TPL.
19569 In the template, the following place holders will be recognized:
19571 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19572 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19573 [PACKAGES] \\usepackage statements for PKG
19574 [NO-PACKAGES] do not include PKG
19575 [EXTRA] the string EXTRA
19576 [NO-EXTRA] do not include EXTRA
19578 For backward compatibility, if both the positive and the negative place
19579 holder is missing, the positive one (without the \"NO-\") will be
19580 assumed to be present at the end of the template.
19581 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19582 EXTRA is a string.
19583 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19584 (let (rpl (end ""))
19585 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19586 (setq rpl (if (or (match-end 1) (not def-pkg))
19587 "" (org-latex-packages-to-string def-pkg snippets-p t))
19588 tpl (replace-match rpl t t tpl))
19589 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19591 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19592 (setq rpl (if (or (match-end 1) (not pkg))
19593 "" (org-latex-packages-to-string pkg snippets-p t))
19594 tpl (replace-match rpl t t tpl))
19595 (when pkg (setq end
19596 (concat end "\n"
19597 (org-latex-packages-to-string pkg snippets-p)))))
19599 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19600 (setq rpl (if (or (match-end 1) (not extra))
19601 "" (concat extra "\n"))
19602 tpl (replace-match rpl t t tpl))
19603 (when (and extra (string-match "\\S-" extra))
19604 (setq end (concat end "\n" extra))))
19606 (if (string-match "\\S-" end)
19607 (concat tpl "\n" end)
19608 tpl)))
19610 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19611 "Turn an alist of packages into a string with the \\usepackage macros."
19612 (setq pkg (mapconcat (lambda(p)
19613 (cond
19614 ((stringp p) p)
19615 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19616 (format "%% Package %s omitted" (cadr p)))
19617 ((equal "" (car p))
19618 (format "\\usepackage{%s}" (cadr p)))
19620 (format "\\usepackage[%s]{%s}"
19621 (car p) (cadr p)))))
19623 "\n"))
19624 (if newline (concat pkg "\n") pkg))
19626 (defun org-dvipng-color (attr)
19627 "Return a RGB color specification for dvipng."
19628 (apply #'format "rgb %s %s %s"
19629 (mapcar #'org-normalize-color
19630 (color-values (face-attribute 'default attr nil)))))
19632 (defun org-dvipng-color-format (color-name)
19633 "Convert COLOR-NAME to a RGB color value for dvipng."
19634 (apply 'format "rgb %s %s %s"
19635 (mapcar 'org-normalize-color
19636 (color-values color-name))))
19638 (defun org-latex-color (attr)
19639 "Return a RGB color for the LaTeX color package."
19640 (apply #'format "%s,%s,%s"
19641 (mapcar #'org-normalize-color
19642 (color-values (face-attribute 'default attr nil)))))
19644 (defun org-latex-color-format (color-name)
19645 "Convert COLOR-NAME to a RGB color value."
19646 (apply 'format "%s,%s,%s"
19647 (mapcar 'org-normalize-color
19648 (color-values color-name))))
19650 (defun org-normalize-color (value)
19651 "Return string to be used as color value for an RGB component."
19652 (format "%g" (/ value 65535.0)))
19656 ;; Image display
19658 (defvar-local org-inline-image-overlays nil)
19660 (defun org-toggle-inline-images (&optional include-linked)
19661 "Toggle the display of inline images.
19662 INCLUDE-LINKED is passed to `org-display-inline-images'."
19663 (interactive "P")
19664 (if org-inline-image-overlays
19665 (progn
19666 (org-remove-inline-images)
19667 (when (called-interactively-p 'interactive)
19668 (message "Inline image display turned off")))
19669 (org-display-inline-images include-linked)
19670 (when (called-interactively-p 'interactive)
19671 (message (if org-inline-image-overlays
19672 (format "%d images displayed inline"
19673 (length org-inline-image-overlays))
19674 "No images to display inline")))))
19676 (defun org-redisplay-inline-images ()
19677 "Refresh the display of inline images."
19678 (interactive)
19679 (if (not org-inline-image-overlays)
19680 (org-toggle-inline-images)
19681 (org-toggle-inline-images)
19682 (org-toggle-inline-images)))
19684 (defun org-display-inline-images (&optional include-linked refresh beg end)
19685 "Display inline images.
19687 An inline image is a link which follows either of these
19688 conventions:
19690 1. Its path is a file with an extension matching return value
19691 from `image-file-name-regexp' and it has no contents.
19693 2. Its description consists in a single link of the previous
19694 type.
19696 When optional argument INCLUDE-LINKED is non-nil, also links with
19697 a text description part will be inlined. This can be nice for
19698 a quick look at those images, but it does not reflect what
19699 exported files will look like.
19701 When optional argument REFRESH is non-nil, refresh existing
19702 images between BEG and END. This will create new image displays
19703 only if necessary. BEG and END default to the buffer
19704 boundaries."
19705 (interactive "P")
19706 (when (display-graphic-p)
19707 (unless refresh
19708 (org-remove-inline-images)
19709 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19710 (org-with-wide-buffer
19711 (goto-char (or beg (point-min)))
19712 (let ((case-fold-search t)
19713 (file-extension-re (image-file-name-regexp)))
19714 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19715 (let ((link (save-match-data (org-element-context))))
19716 ;; Check if we're at an inline image.
19717 (when (and (equal (org-element-property :type link) "file")
19718 (or include-linked
19719 (not (org-element-property :contents-begin link)))
19720 (let ((parent (org-element-property :parent link)))
19721 (or (not (eq (org-element-type parent) 'link))
19722 (not (cdr (org-element-contents parent)))))
19723 (string-match-p file-extension-re
19724 (org-element-property :path link)))
19725 (let ((file (expand-file-name
19726 (org-link-unescape
19727 (org-element-property :path link)))))
19728 (when (file-exists-p file)
19729 (let ((width
19730 ;; Apply `org-image-actual-width' specifications.
19731 (cond
19732 ((not (image-type-available-p 'imagemagick)) nil)
19733 ((eq org-image-actual-width t) nil)
19734 ((listp org-image-actual-width)
19736 ;; First try to find a width among
19737 ;; attributes associated to the paragraph
19738 ;; containing link.
19739 (let ((paragraph
19740 (let ((e link))
19741 (while (and (setq e (org-element-property
19742 :parent e))
19743 (not (eq (org-element-type e)
19744 'paragraph))))
19745 e)))
19746 (when paragraph
19747 (save-excursion
19748 (goto-char (org-element-property :begin paragraph))
19749 (when
19750 (re-search-forward
19751 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19752 (org-element-property
19753 :post-affiliated paragraph)
19755 (string-to-number (match-string 1))))))
19756 ;; Otherwise, fall-back to provided number.
19757 (car org-image-actual-width)))
19758 ((numberp org-image-actual-width)
19759 org-image-actual-width)))
19760 (old (get-char-property-and-overlay
19761 (org-element-property :begin link)
19762 'org-image-overlay)))
19763 (if (and (car-safe old) refresh)
19764 (image-refresh (overlay-get (cdr old) 'display))
19765 (let ((image (create-image file
19766 (and width 'imagemagick)
19768 :width width)))
19769 (when image
19770 (let* ((link
19771 ;; If inline image is the description
19772 ;; of another link, be sure to
19773 ;; consider the latter as the one to
19774 ;; apply the overlay on.
19775 (let ((parent
19776 (org-element-property :parent link)))
19777 (if (eq (org-element-type parent) 'link)
19778 parent
19779 link)))
19780 (ov (make-overlay
19781 (org-element-property :begin link)
19782 (progn
19783 (goto-char
19784 (org-element-property :end link))
19785 (skip-chars-backward " \t")
19786 (point)))))
19787 (overlay-put ov 'display image)
19788 (overlay-put ov 'face 'default)
19789 (overlay-put ov 'org-image-overlay t)
19790 (overlay-put
19791 ov 'modification-hooks
19792 (list 'org-display-inline-remove-overlay))
19793 (push ov org-inline-image-overlays)))))))))))))))
19795 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19796 "Remove inline-display overlay if a corresponding region is modified."
19797 (let ((inhibit-modification-hooks t))
19798 (when (and ov after)
19799 (delete ov org-inline-image-overlays)
19800 (delete-overlay ov))))
19802 (defun org-remove-inline-images ()
19803 "Remove inline display of images."
19804 (interactive)
19805 (mapc #'delete-overlay org-inline-image-overlays)
19806 (setq org-inline-image-overlays nil))
19808 ;;;; Key bindings
19810 ;; Outline functions from `outline-mode-prefix-map'
19811 ;; that can be remapped in Org:
19812 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19813 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19814 (define-key org-mode-map [remap outline-forward-same-level]
19815 'org-forward-heading-same-level)
19816 (define-key org-mode-map [remap outline-backward-same-level]
19817 'org-backward-heading-same-level)
19818 (define-key org-mode-map [remap outline-show-branches]
19819 'org-kill-note-or-show-branches)
19820 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19821 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19822 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19823 (define-key org-mode-map [remap outline-next-visible-heading]
19824 'org-next-visible-heading)
19825 (define-key org-mode-map [remap outline-previous-visible-heading]
19826 'org-previous-visible-heading)
19827 (define-key org-mode-map [remap show-children] 'org-show-children)
19829 ;; Outline functions from `outline-mode-prefix-map' that can not
19830 ;; be remapped in Org:
19832 ;; - the column "key binding" shows whether the Outline function is still
19833 ;; available in Org mode on the same key that it has been bound to in
19834 ;; Outline mode:
19835 ;; - "overridden": key used for a different functionality in Org mode
19836 ;; - else: key still bound to the same Outline function in Org mode
19838 ;; | Outline function | key binding | Org replacement |
19839 ;; |------------------------------------+-------------+--------------------------|
19840 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19841 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19842 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19843 ;; | `show-entry' | overridden | no replacement |
19844 ;; | `show-branches' | `C-c C-k' | still same function |
19845 ;; | `show-subtree' | overridden | visibility cycling |
19846 ;; | `show-all' | overridden | no replacement |
19847 ;; | `hide-subtree' | overridden | visibility cycling |
19848 ;; | `hide-body' | overridden | no replacement |
19849 ;; | `hide-entry' | overridden | visibility cycling |
19850 ;; | `hide-leaves' | overridden | no replacement |
19851 ;; | `hide-sublevels' | overridden | no replacement |
19852 ;; | `hide-other' | overridden | no replacement |
19854 ;; Make `C-c C-x' a prefix key
19855 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19857 ;; TAB key with modifiers
19858 (org-defkey org-mode-map "\C-i" 'org-cycle)
19859 (org-defkey org-mode-map [(tab)] 'org-cycle)
19860 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19861 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19862 ;; The following line is necessary under Suse GNU/Linux
19863 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19864 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19865 (define-key org-mode-map [backtab] 'org-shifttab)
19867 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19868 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19869 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19871 ;; Cursor keys with modifiers
19872 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19873 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19874 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19875 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19877 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19878 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19879 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19880 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19881 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19882 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19884 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19885 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19886 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19887 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19889 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19890 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19891 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19892 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19894 ;; Babel keys
19895 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19896 (dolist (pair org-babel-key-bindings)
19897 (define-key org-babel-map (car pair) (cdr pair)))
19899 ;;; Extra keys for tty access.
19900 ;; We only set them when really needed because otherwise the
19901 ;; menus don't show the simple keys
19903 (when (or org-use-extra-keys (not window-system))
19904 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19905 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19906 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19907 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19908 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19909 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19910 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19911 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19912 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19913 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19914 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19915 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19916 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19917 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19918 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19919 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19920 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19921 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19922 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19923 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19924 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19925 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19926 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19927 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19928 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19929 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19930 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19931 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19933 ;; All the other keys
19935 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19936 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19937 (if (boundp 'narrow-map)
19938 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19939 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19940 (if (boundp 'narrow-map)
19941 (org-defkey narrow-map "b" 'org-narrow-to-block)
19942 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19943 (if (boundp 'narrow-map)
19944 (org-defkey narrow-map "e" 'org-narrow-to-element)
19945 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19946 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19947 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19948 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19949 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19950 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19951 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19952 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19953 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19954 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19955 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19956 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19957 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19958 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19959 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19960 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19961 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19962 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19963 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19964 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19965 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19966 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19967 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19968 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19969 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19970 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19971 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19972 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19973 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19974 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19975 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19976 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19977 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19978 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19979 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19980 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19981 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19982 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19983 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19984 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19985 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19986 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19987 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19988 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19989 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19990 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19991 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19992 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19993 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19994 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19995 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19996 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19997 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19998 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19999 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20000 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
20001 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
20002 (org-defkey org-mode-map "\C-c^" 'org-sort)
20003 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20004 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20005 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20006 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20007 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20008 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20009 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20010 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20011 (org-defkey org-mode-map "\C-m" 'org-return)
20012 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20013 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20014 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20015 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20016 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20017 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20018 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20019 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20020 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20021 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20022 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20023 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20024 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20025 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20026 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20027 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20028 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20029 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20030 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20031 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20032 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20033 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20034 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20035 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20036 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20038 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20039 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20040 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20042 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20043 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20044 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20045 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20046 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20047 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20048 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20049 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20050 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20051 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20052 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20053 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20054 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20055 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20056 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20057 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20058 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20059 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20060 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20061 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20062 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20063 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20065 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20066 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20067 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20068 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20069 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20071 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20073 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20075 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20076 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20078 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20081 (defconst org-speed-commands-default
20083 ("Outline Navigation")
20084 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20085 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20086 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20087 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20088 ("F" . org-next-block)
20089 ("B" . org-previous-block)
20090 ("u" . (org-speed-move-safe 'outline-up-heading))
20091 ("j" . org-goto)
20092 ("g" . (org-refile t))
20093 ("Outline Visibility")
20094 ("c" . org-cycle)
20095 ("C" . org-shifttab)
20096 (" " . org-display-outline-path)
20097 ("s" . org-narrow-to-subtree)
20098 ("=" . org-columns)
20099 ("Outline Structure Editing")
20100 ("U" . org-metaup)
20101 ("D" . org-metadown)
20102 ("r" . org-metaright)
20103 ("l" . org-metaleft)
20104 ("R" . org-shiftmetaright)
20105 ("L" . org-shiftmetaleft)
20106 ("i" . (progn (forward-char 1) (call-interactively
20107 'org-insert-heading-respect-content)))
20108 ("^" . org-sort)
20109 ("w" . org-refile)
20110 ("a" . org-archive-subtree-default-with-confirmation)
20111 ("@" . org-mark-subtree)
20112 ("#" . org-toggle-comment)
20113 ("Clock Commands")
20114 ("I" . org-clock-in)
20115 ("O" . org-clock-out)
20116 ("Meta Data Editing")
20117 ("t" . org-todo)
20118 ("," . (org-priority))
20119 ("0" . (org-priority ?\ ))
20120 ("1" . (org-priority ?A))
20121 ("2" . (org-priority ?B))
20122 ("3" . (org-priority ?C))
20123 (":" . org-set-tags-command)
20124 ("e" . org-set-effort)
20125 ("E" . org-inc-effort)
20126 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20127 (org-entry-put (point) "APPT_WARNTIME" m)))
20128 ("Agenda Views etc")
20129 ("v" . org-agenda)
20130 ("/" . org-sparse-tree)
20131 ("Misc")
20132 ("o" . org-open-at-point)
20133 ("?" . org-speed-command-help)
20134 ("<" . (org-agenda-set-restriction-lock 'subtree))
20135 (">" . (org-agenda-remove-restriction-lock))
20137 "The default speed commands.")
20139 (defun org-print-speed-command (e)
20140 (if (> (length (car e)) 1)
20141 (progn
20142 (princ "\n")
20143 (princ (car e))
20144 (princ "\n")
20145 (princ (make-string (length (car e)) ?-))
20146 (princ "\n"))
20147 (princ (car e))
20148 (princ " ")
20149 (if (symbolp (cdr e))
20150 (princ (symbol-name (cdr e)))
20151 (prin1 (cdr e)))
20152 (princ "\n")))
20154 (defun org-speed-command-help ()
20155 "Show the available speed commands."
20156 (interactive)
20157 (if (not org-use-speed-commands)
20158 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20159 (with-output-to-temp-buffer "*Help*"
20160 (princ "User-defined Speed commands\n===========================\n")
20161 (mapc #'org-print-speed-command org-speed-commands-user)
20162 (princ "\n")
20163 (princ "Built-in Speed commands\n=======================\n")
20164 (mapc #'org-print-speed-command org-speed-commands-default))
20165 (with-current-buffer "*Help*"
20166 (setq truncate-lines t))))
20168 (defun org-speed-move-safe (cmd)
20169 "Execute CMD, but make sure that the cursor always ends up in a headline.
20170 If not, return to the original position and throw an error."
20171 (interactive)
20172 (let ((pos (point)))
20173 (call-interactively cmd)
20174 (unless (and (bolp) (org-at-heading-p))
20175 (goto-char pos)
20176 (error "Boundary reached while executing %s" cmd))))
20178 (defvar org-self-insert-command-undo-counter 0)
20180 (defvar org-table-auto-blank-field) ; defined in org-table.el
20181 (defvar org-speed-command nil)
20183 (defun org-speed-command-activate (keys)
20184 "Hook for activating single-letter speed commands.
20185 `org-speed-commands-default' specifies a minimal command set.
20186 Use `org-speed-commands-user' for further customization."
20187 (when (or (and (bolp) (looking-at org-outline-regexp))
20188 (and (functionp org-use-speed-commands)
20189 (funcall org-use-speed-commands)))
20190 (cdr (assoc keys (append org-speed-commands-user
20191 org-speed-commands-default)))))
20193 (defun org-babel-speed-command-activate (keys)
20194 "Hook for activating single-letter code block commands."
20195 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20196 (cdr (assoc keys org-babel-key-bindings))))
20198 (defcustom org-speed-command-hook
20199 '(org-speed-command-default-hook org-babel-speed-command-hook)
20200 "Hook for activating speed commands at strategic locations.
20201 Hook functions are called in sequence until a valid handler is
20202 found.
20204 Each hook takes a single argument, a user-pressed command key
20205 which is also a `self-insert-command' from the global map.
20207 Within the hook, examine the cursor position and the command key
20208 and return nil or a valid handler as appropriate. Handler could
20209 be one of an interactive command, a function, or a form.
20211 Set `org-use-speed-commands' to non-nil value to enable this
20212 hook. The default setting is `org-speed-command-activate'."
20213 :group 'org-structure
20214 :version "24.1"
20215 :type 'hook)
20217 (defun org-self-insert-command (N)
20218 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20219 If the cursor is in a table looking at whitespace, the whitespace is
20220 overwritten, and the table is not marked as requiring realignment."
20221 (interactive "p")
20222 (org-check-before-invisible-edit 'insert)
20223 (cond
20224 ((and org-use-speed-commands
20225 (let ((kv (this-command-keys-vector)))
20226 (setq org-speed-command
20227 (run-hook-with-args-until-success
20228 'org-speed-command-hook
20229 (make-string 1 (aref kv (1- (length kv))))))))
20230 (cond
20231 ((commandp org-speed-command)
20232 (setq this-command org-speed-command)
20233 (call-interactively org-speed-command))
20234 ((functionp org-speed-command)
20235 (funcall org-speed-command))
20236 ((and org-speed-command (listp org-speed-command))
20237 (eval org-speed-command))
20238 (t (let (org-use-speed-commands)
20239 (call-interactively 'org-self-insert-command)))))
20240 ((and
20241 (org-at-table-p)
20242 (progn
20243 ;; Check if we blank the field, and if that triggers align.
20244 (and (featurep 'org-table) org-table-auto-blank-field
20245 (memq last-command
20246 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20247 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20248 ;; Got extra space, this field does not determine
20249 ;; column width.
20250 (let (org-table-may-need-update) (org-table-blank-field))
20251 ;; No extra space, this field may determine column
20252 ;; width.
20253 (org-table-blank-field)))
20255 (eq N 1)
20256 (looking-at "[^|\n]* \\( \\)|"))
20257 ;; There is room for insertion without re-aligning the table.
20258 (delete-region (match-beginning 1) (match-end 1))
20259 (self-insert-command N))
20261 (setq org-table-may-need-update t)
20262 (self-insert-command N)
20263 (org-fix-tags-on-the-fly)
20264 (when org-self-insert-cluster-for-undo
20265 (if (not (eq last-command 'org-self-insert-command))
20266 (setq org-self-insert-command-undo-counter 1)
20267 (if (>= org-self-insert-command-undo-counter 20)
20268 (setq org-self-insert-command-undo-counter 1)
20269 (and (> org-self-insert-command-undo-counter 0)
20270 buffer-undo-list (listp buffer-undo-list)
20271 (not (cadr buffer-undo-list)) ; remove nil entry
20272 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20273 (setq org-self-insert-command-undo-counter
20274 (1+ org-self-insert-command-undo-counter))))))))
20276 (defun org-check-before-invisible-edit (kind)
20277 "Check is editing if kind KIND would be dangerous with invisible text around.
20278 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20279 ;; First, try to get out of here as quickly as possible, to reduce overhead
20280 (when (and org-catch-invisible-edits
20281 (or (not (boundp 'visible-mode)) (not visible-mode))
20282 (or (get-char-property (point) 'invisible)
20283 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20284 ;; OK, we need to take a closer look
20285 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20286 (invisible-before-point (unless (bobp) (get-char-property
20287 (1- (point)) 'invisible)))
20288 (border-and-ok-direction
20290 ;; Check if we are acting predictably before invisible text
20291 (and invisible-at-point (not invisible-before-point)
20292 (memq kind '(insert delete-backward)))
20293 ;; Check if we are acting predictably after invisible text
20294 ;; This works not well, and I have turned it off. It seems
20295 ;; better to always show and stop after invisible text.
20296 ;; (and (not invisible-at-point) invisible-before-point
20297 ;; (memq kind '(insert delete)))
20299 (when (or (memq invisible-at-point '(outline org-hide-block t))
20300 (memq invisible-before-point '(outline org-hide-block t)))
20301 (when (eq org-catch-invisible-edits 'error)
20302 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20303 (if (and org-custom-properties-overlays
20304 (y-or-n-p "Display invisible properties in this buffer? "))
20305 (org-toggle-custom-properties-visibility)
20306 ;; Make the area visible
20307 (save-excursion
20308 (when invisible-before-point
20309 (goto-char (previous-single-char-property-change
20310 (point) 'invisible)))
20311 (outline-show-subtree))
20312 (cond
20313 ((eq org-catch-invisible-edits 'show)
20314 ;; That's it, we do the edit after showing
20315 (message
20316 "Unfolding invisible region around point before editing")
20317 (sit-for 1))
20318 ((and (eq org-catch-invisible-edits 'smart)
20319 border-and-ok-direction)
20320 (message "Unfolding invisible region around point before editing"))
20322 ;; Don't do the edit, make the user repeat it in full visibility
20323 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20325 (defun org-fix-tags-on-the-fly ()
20326 (when (and (equal (char-after (point-at-bol)) ?*)
20327 (org-at-heading-p))
20328 (org-align-tags-here org-tags-column)))
20330 (defun org-delete-backward-char (N)
20331 "Like `delete-backward-char', insert whitespace at field end in tables.
20332 When deleting backwards, in tables this function will insert whitespace in
20333 front of the next \"|\" separator, to keep the table aligned. The table will
20334 still be marked for re-alignment if the field did fill the entire column,
20335 because, in this case the deletion might narrow the column."
20336 (interactive "p")
20337 (save-match-data
20338 (org-check-before-invisible-edit 'delete-backward)
20339 (if (and (org-at-table-p)
20340 (eq N 1)
20341 (string-match "|" (buffer-substring (point-at-bol) (point)))
20342 (looking-at ".*?|"))
20343 (let ((pos (point))
20344 (noalign (looking-at "[^|\n\r]* |"))
20345 (c org-table-may-need-update))
20346 (backward-delete-char N)
20347 (unless overwrite-mode
20348 (skip-chars-forward "^|")
20349 (insert " ")
20350 (goto-char (1- pos)))
20351 ;; noalign: if there were two spaces at the end, this field
20352 ;; does not determine the width of the column.
20353 (when noalign (setq org-table-may-need-update c)))
20354 (backward-delete-char N)
20355 (org-fix-tags-on-the-fly))))
20357 (defun org-delete-char (N)
20358 "Like `delete-char', but insert whitespace at field end in tables.
20359 When deleting characters, in tables this function will insert whitespace in
20360 front of the next \"|\" separator, to keep the table aligned. The table will
20361 still be marked for re-alignment if the field did fill the entire column,
20362 because, in this case the deletion might narrow the column."
20363 (interactive "p")
20364 (save-match-data
20365 (org-check-before-invisible-edit 'delete)
20366 (if (and (org-at-table-p)
20367 (not (bolp))
20368 (not (= (char-after) ?|))
20369 (eq N 1))
20370 (if (looking-at ".*?|")
20371 (let ((pos (point))
20372 (noalign (looking-at "[^|\n\r]* |"))
20373 (c org-table-may-need-update))
20374 (replace-match
20375 (concat (substring (match-string 0) 1 -1) " |") nil t)
20376 (goto-char pos)
20377 ;; noalign: if there were two spaces at the end, this field
20378 ;; does not determine the width of the column.
20379 (when noalign (setq org-table-may-need-update c)))
20380 (delete-char N))
20381 (delete-char N)
20382 (org-fix-tags-on-the-fly))))
20384 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20385 (put 'org-self-insert-command 'delete-selection
20386 (lambda ()
20387 (not (run-hook-with-args-until-success
20388 'self-insert-uses-region-functions))))
20389 (put 'orgtbl-self-insert-command 'delete-selection
20390 (lambda ()
20391 (not (run-hook-with-args-until-success
20392 'self-insert-uses-region-functions))))
20393 (put 'org-delete-char 'delete-selection 'supersede)
20394 (put 'org-delete-backward-char 'delete-selection 'supersede)
20395 (put 'org-yank 'delete-selection 'yank)
20397 ;; Make `flyspell-mode' delay after some commands
20398 (put 'org-self-insert-command 'flyspell-delayed t)
20399 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20400 (put 'org-delete-char 'flyspell-delayed t)
20401 (put 'org-delete-backward-char 'flyspell-delayed t)
20403 ;; Make pabbrev-mode expand after org-mode commands
20404 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20405 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20407 (defun org-remap (map &rest commands)
20408 "In MAP, remap the functions given in COMMANDS.
20409 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20410 (let (new old)
20411 (while commands
20412 (setq old (pop commands) new (pop commands))
20413 (if (fboundp 'command-remapping)
20414 (org-defkey map (vector 'remap old) new)
20415 (substitute-key-definition old new map global-map)))))
20417 (defun org-transpose-words ()
20418 "Transpose words for Org.
20419 This uses the `org-mode-transpose-word-syntax-table' syntax
20420 table, which interprets characters in `org-emphasis-alist' as
20421 word constituents."
20422 (interactive)
20423 (with-syntax-table org-mode-transpose-word-syntax-table
20424 (call-interactively 'transpose-words)))
20425 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20427 (when (eq org-enable-table-editor 'optimized)
20428 ;; If the user wants maximum table support, we need to hijack
20429 ;; some standard editing functions
20430 (org-remap org-mode-map
20431 'self-insert-command 'org-self-insert-command
20432 'delete-char 'org-delete-char
20433 'delete-backward-char 'org-delete-backward-char)
20434 (org-defkey org-mode-map "|" 'org-force-self-insert))
20436 (defvar org-ctrl-c-ctrl-c-hook nil
20437 "Hook for functions attaching themselves to `C-c C-c'.
20439 This can be used to add additional functionality to the C-c C-c
20440 key which executes context-dependent commands. This hook is run
20441 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20442 run after the last test.
20444 Each function will be called with no arguments. The function
20445 must check if the context is appropriate for it to act. If yes,
20446 it should do its thing and then return a non-nil value. If the
20447 context is wrong, just do nothing and return nil.")
20449 (defvar org-ctrl-c-ctrl-c-final-hook nil
20450 "Hook for functions attaching themselves to `C-c C-c'.
20452 This can be used to add additional functionality to the C-c C-c
20453 key which executes context-dependent commands. This hook is run
20454 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20455 before the first test.
20457 Each function will be called with no arguments. The function
20458 must check if the context is appropriate for it to act. If yes,
20459 it should do its thing and then return a non-nil value. If the
20460 context is wrong, just do nothing and return nil.")
20462 (defvar org-tab-first-hook nil
20463 "Hook for functions to attach themselves to TAB.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.
20465 This hook runs as the first action when TAB is pressed, even before
20466 `org-cycle' messes around with the `outline-regexp' to cater for
20467 inline tasks and plain list item folding.
20468 If any function in this hook returns t, any other actions that
20469 would have been caused by TAB (such as table field motion or visibility
20470 cycling) will not occur.")
20472 (defvar org-tab-after-check-for-table-hook nil
20473 "Hook for functions to attach themselves to TAB.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.
20475 This hook runs after it has been established that the cursor is not in a
20476 table, but before checking if the cursor is in a headline or if global cycling
20477 should be done.
20478 If any function in this hook returns t, not other actions like visibility
20479 cycling will be done.")
20481 (defvar org-tab-after-check-for-cycling-hook nil
20482 "Hook for functions to attach themselves to TAB.
20483 See `org-ctrl-c-ctrl-c-hook' for more information.
20484 This hook runs after it has been established that not table field motion and
20485 not visibility should be done because of current context. This is probably
20486 the place where a package like yasnippets can hook in.")
20488 (defvar org-tab-before-tab-emulation-hook nil
20489 "Hook for functions to attach themselves to TAB.
20490 See `org-ctrl-c-ctrl-c-hook' for more information.
20491 This hook runs after every other options for TAB have been exhausted, but
20492 before indentation and \t insertion takes place.")
20494 (defvar org-metaleft-hook nil
20495 "Hook for functions attaching themselves to `M-left'.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defvar org-metaright-hook nil
20498 "Hook for functions attaching themselves to `M-right'.
20499 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defvar org-metaup-hook nil
20501 "Hook for functions attaching themselves to `M-up'.
20502 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defvar org-metadown-hook nil
20504 "Hook for functions attaching themselves to `M-down'.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20506 (defvar org-shiftmetaleft-hook nil
20507 "Hook for functions attaching themselves to `M-S-left'.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-shiftmetaright-hook nil
20510 "Hook for functions attaching themselves to `M-S-right'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftmetaup-hook nil
20513 "Hook for functions attaching themselves to `M-S-up'.
20514 See `org-ctrl-c-ctrl-c-hook' for more information.")
20515 (defvar org-shiftmetadown-hook nil
20516 "Hook for functions attaching themselves to `M-S-down'.
20517 See `org-ctrl-c-ctrl-c-hook' for more information.")
20518 (defvar org-metareturn-hook nil
20519 "Hook for functions attaching themselves to `M-RET'.
20520 See `org-ctrl-c-ctrl-c-hook' for more information.")
20521 (defvar org-shiftup-hook nil
20522 "Hook for functions attaching themselves to `S-up'.
20523 See `org-ctrl-c-ctrl-c-hook' for more information.")
20524 (defvar org-shiftup-final-hook nil
20525 "Hook for functions attaching themselves to `S-up'.
20526 This one runs after all other options except shift-select have been excluded.
20527 See `org-ctrl-c-ctrl-c-hook' for more information.")
20528 (defvar org-shiftdown-hook nil
20529 "Hook for functions attaching themselves to `S-down'.
20530 See `org-ctrl-c-ctrl-c-hook' for more information.")
20531 (defvar org-shiftdown-final-hook nil
20532 "Hook for functions attaching themselves to `S-down'.
20533 This one runs after all other options except shift-select have been excluded.
20534 See `org-ctrl-c-ctrl-c-hook' for more information.")
20535 (defvar org-shiftleft-hook nil
20536 "Hook for functions attaching themselves to `S-left'.
20537 See `org-ctrl-c-ctrl-c-hook' for more information.")
20538 (defvar org-shiftleft-final-hook nil
20539 "Hook for functions attaching themselves to `S-left'.
20540 This one runs after all other options except shift-select have been excluded.
20541 See `org-ctrl-c-ctrl-c-hook' for more information.")
20542 (defvar org-shiftright-hook nil
20543 "Hook for functions attaching themselves to `S-right'.
20544 See `org-ctrl-c-ctrl-c-hook' for more information.")
20545 (defvar org-shiftright-final-hook nil
20546 "Hook for functions attaching themselves to `S-right'.
20547 This one runs after all other options except shift-select have been excluded.
20548 See `org-ctrl-c-ctrl-c-hook' for more information.")
20550 (defun org-modifier-cursor-error ()
20551 "Throw an error, a modified cursor command was applied in wrong context."
20552 (user-error "This command is active in special context like tables, headlines or items"))
20554 (defun org-shiftselect-error ()
20555 "Throw an error because Shift-Cursor command was applied in wrong context."
20556 (if (and (boundp 'shift-select-mode) shift-select-mode)
20557 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20558 (user-error "This command works only in special context like headlines or timestamps")))
20560 (defun org-call-for-shift-select (cmd)
20561 (let ((this-command-keys-shift-translated t))
20562 (call-interactively cmd)))
20564 (defun org-shifttab (&optional arg)
20565 "Global visibility cycling or move to previous table field.
20566 Call `org-table-previous-field' within a table.
20567 When ARG is nil, cycle globally through visibility states.
20568 When ARG is a numeric prefix, show contents of this level."
20569 (interactive "P")
20570 (cond
20571 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20572 ((integerp arg)
20573 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20574 (message "Content view to level: %d" arg)
20575 (org-content (prefix-numeric-value arg2))
20576 (org-cycle-show-empty-lines t)
20577 (setq org-cycle-global-status 'overview)))
20578 (t (call-interactively 'org-global-cycle))))
20580 (defun org-shiftmetaleft ()
20581 "Promote subtree or delete table column.
20582 Calls `org-promote-subtree', `org-outdent-item-tree', or
20583 `org-table-delete-column', depending on context. See the
20584 individual commands for more information."
20585 (interactive)
20586 (cond
20587 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20588 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20589 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20590 ((if (not (org-region-active-p)) (org-at-item-p)
20591 (save-excursion (goto-char (region-beginning))
20592 (org-at-item-p)))
20593 (call-interactively 'org-outdent-item-tree))
20594 (t (org-modifier-cursor-error))))
20596 (defun org-shiftmetaright ()
20597 "Demote subtree or insert table column.
20598 Calls `org-demote-subtree', `org-indent-item-tree', or
20599 `org-table-insert-column', depending on context. See the
20600 individual commands for more information."
20601 (interactive)
20602 (cond
20603 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20604 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20605 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20606 ((if (not (org-region-active-p)) (org-at-item-p)
20607 (save-excursion (goto-char (region-beginning))
20608 (org-at-item-p)))
20609 (call-interactively 'org-indent-item-tree))
20610 (t (org-modifier-cursor-error))))
20612 (defun org-shiftmetaup (&optional _arg)
20613 "Drag the line at point up.
20614 In a table, kill the current row.
20615 On a clock timestamp, update the value of the timestamp like `S-<up>'
20616 but also adjust the previous clocked item in the clock history.
20617 Everywhere else, drag the line at point up."
20618 (interactive "P")
20619 (cond
20620 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20621 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20622 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20623 (call-interactively 'org-timestamp-up)))
20624 (t (call-interactively 'org-drag-line-backward))))
20626 (defun org-shiftmetadown (&optional _arg)
20627 "Drag the line at point down.
20628 In a table, insert an empty row at the current line.
20629 On a clock timestamp, update the value of the timestamp like `S-<down>'
20630 but also adjust the previous clocked item in the clock history.
20631 Everywhere else, drag the line at point down."
20632 (interactive "P")
20633 (cond
20634 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20635 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20636 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20637 (call-interactively 'org-timestamp-down)))
20638 (t (call-interactively 'org-drag-line-forward))))
20640 (defsubst org-hidden-tree-error ()
20641 (user-error
20642 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20644 (defun org-metaleft (&optional _arg)
20645 "Promote heading, list item at point or move table column left.
20647 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20648 depending on context. With no specific context, calls the Emacs
20649 default `backward-word'. See the individual commands for more
20650 information.
20652 This function runs the hook `org-metaleft-hook' as a first step,
20653 and returns at first non-nil value."
20654 (interactive "P")
20655 (cond
20656 ((run-hook-with-args-until-success 'org-metaleft-hook))
20657 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20658 ((org-with-limited-levels
20659 (or (org-at-heading-p)
20660 (and (org-region-active-p)
20661 (save-excursion
20662 (goto-char (region-beginning))
20663 (org-at-heading-p)))))
20664 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20665 (call-interactively 'org-do-promote))
20666 ;; At an inline task.
20667 ((org-at-heading-p)
20668 (call-interactively 'org-inlinetask-promote))
20669 ((or (org-at-item-p)
20670 (and (org-region-active-p)
20671 (save-excursion
20672 (goto-char (region-beginning))
20673 (org-at-item-p))))
20674 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20675 (call-interactively 'org-outdent-item))
20676 (t (call-interactively 'backward-word))))
20678 (defun org-metaright (&optional _arg)
20679 "Demote heading, list item at point or move table column right.
20681 In front of a drawer or a block keyword, indent it correctly.
20683 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20684 `org-indnet-drawer' or `org-indent-block' depending on context.
20685 With no specific context, calls the Emacs default `forward-word'.
20686 See the individual commands for more information.
20688 This function runs the hook `org-metaright-hook' as a first step,
20689 and returns at first non-nil value."
20690 (interactive "P")
20691 (cond
20692 ((run-hook-with-args-until-success 'org-metaright-hook))
20693 ((org-at-table-p) (call-interactively 'org-table-move-column))
20694 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20695 ((org-at-block-p) (call-interactively 'org-indent-block))
20696 ((org-with-limited-levels
20697 (or (org-at-heading-p)
20698 (and (org-region-active-p)
20699 (save-excursion
20700 (goto-char (region-beginning))
20701 (org-at-heading-p)))))
20702 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20703 (call-interactively 'org-do-demote))
20704 ;; At an inline task.
20705 ((org-at-heading-p)
20706 (call-interactively 'org-inlinetask-demote))
20707 ((or (org-at-item-p)
20708 (and (org-region-active-p)
20709 (save-excursion
20710 (goto-char (region-beginning))
20711 (org-at-item-p))))
20712 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20713 (call-interactively 'org-indent-item))
20714 (t (call-interactively 'forward-word))))
20716 (defun org-check-for-hidden (what)
20717 "Check if there are hidden headlines/items in the current visual line.
20718 WHAT can be either `headlines' or `items'. If the current line is
20719 an outline or item heading and it has a folded subtree below it,
20720 this function returns t, nil otherwise."
20721 (let ((re (cond
20722 ((eq what 'headlines) org-outline-regexp-bol)
20723 ((eq what 'items) (org-item-beginning-re))
20724 (t (error "This should not happen"))))
20725 beg end)
20726 (save-excursion
20727 (catch 'exit
20728 (unless (org-region-active-p)
20729 (setq beg (point-at-bol))
20730 (beginning-of-line 2)
20731 (while (and (not (eobp)) ;; this is like `next-line'
20732 (get-char-property (1- (point)) 'invisible))
20733 (beginning-of-line 2))
20734 (setq end (point))
20735 (goto-char beg)
20736 (goto-char (point-at-eol))
20737 (setq end (max end (point)))
20738 (while (re-search-forward re end t)
20739 (when (get-char-property (match-beginning 0) 'invisible)
20740 (throw 'exit t))))
20741 nil))))
20743 (defun org-metaup (&optional _arg)
20744 "Move subtree up or move table row up.
20745 Calls `org-move-subtree-up' or `org-table-move-row' or
20746 `org-move-item-up', depending on context. See the individual commands
20747 for more information."
20748 (interactive "P")
20749 (cond
20750 ((run-hook-with-args-until-success 'org-metaup-hook))
20751 ((org-region-active-p)
20752 (let* ((a (min (region-beginning) (region-end)))
20753 (b (1- (max (region-beginning) (region-end))))
20754 (c (save-excursion (goto-char a)
20755 (move-beginning-of-line 0)))
20756 (d (save-excursion (goto-char a)
20757 (move-end-of-line 0) (point))))
20758 (transpose-regions a b c d)
20759 (goto-char c)))
20760 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20761 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20762 ((org-at-item-p) (call-interactively 'org-move-item-up))
20763 (t (org-drag-element-backward))))
20765 (defun org-metadown (&optional _arg)
20766 "Move subtree down or move table row down.
20767 Calls `org-move-subtree-down' or `org-table-move-row' or
20768 `org-move-item-down', depending on context. See the individual
20769 commands for more information."
20770 (interactive "P")
20771 (cond
20772 ((run-hook-with-args-until-success 'org-metadown-hook))
20773 ((org-region-active-p)
20774 (let* ((a (min (region-beginning) (region-end)))
20775 (b (max (region-beginning) (region-end)))
20776 (c (save-excursion (goto-char b)
20777 (move-beginning-of-line 1)))
20778 (d (save-excursion (goto-char b)
20779 (move-end-of-line 1) (1+ (point)))))
20780 (transpose-regions a b c d)
20781 (goto-char d)))
20782 ((org-at-table-p) (call-interactively 'org-table-move-row))
20783 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20784 ((org-at-item-p) (call-interactively 'org-move-item-down))
20785 (t (org-drag-element-forward))))
20787 (defun org-shiftup (&optional arg)
20788 "Increase item in timestamp or increase priority of current headline.
20789 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20790 depending on context. See the individual commands for more information."
20791 (interactive "P")
20792 (cond
20793 ((run-hook-with-args-until-success 'org-shiftup-hook))
20794 ((and org-support-shift-select (org-region-active-p))
20795 (org-call-for-shift-select 'previous-line))
20796 ((org-at-timestamp-p t)
20797 (call-interactively (if org-edit-timestamp-down-means-later
20798 'org-timestamp-down 'org-timestamp-up)))
20799 ((and (not (eq org-support-shift-select 'always))
20800 org-enable-priority-commands
20801 (org-at-heading-p))
20802 (call-interactively 'org-priority-up))
20803 ((and (not org-support-shift-select) (org-at-item-p))
20804 (call-interactively 'org-previous-item))
20805 ((org-clocktable-try-shift 'up arg))
20806 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20807 (org-support-shift-select
20808 (org-call-for-shift-select 'previous-line))
20809 (t (org-shiftselect-error))))
20811 (defun org-shiftdown (&optional arg)
20812 "Decrease item in timestamp or decrease priority of current headline.
20813 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20814 depending on context. See the individual commands for more information."
20815 (interactive "P")
20816 (cond
20817 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20818 ((and org-support-shift-select (org-region-active-p))
20819 (org-call-for-shift-select 'next-line))
20820 ((org-at-timestamp-p t)
20821 (call-interactively (if org-edit-timestamp-down-means-later
20822 'org-timestamp-up 'org-timestamp-down)))
20823 ((and (not (eq org-support-shift-select 'always))
20824 org-enable-priority-commands
20825 (org-at-heading-p))
20826 (call-interactively 'org-priority-down))
20827 ((and (not org-support-shift-select) (org-at-item-p))
20828 (call-interactively 'org-next-item))
20829 ((org-clocktable-try-shift 'down arg))
20830 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20831 (org-support-shift-select
20832 (org-call-for-shift-select 'next-line))
20833 (t (org-shiftselect-error))))
20835 (defun org-shiftright (&optional arg)
20836 "Cycle the thing at point or in the current line, depending on context.
20837 Depending on context, this does one of the following:
20839 - switch a timestamp at point one day into the future
20840 - on a headline, switch to the next TODO keyword.
20841 - on an item, switch entire list to the next bullet type
20842 - on a property line, switch to the next allowed value
20843 - on a clocktable definition line, move time block into the future"
20844 (interactive "P")
20845 (cond
20846 ((run-hook-with-args-until-success 'org-shiftright-hook))
20847 ((and org-support-shift-select (org-region-active-p))
20848 (org-call-for-shift-select 'forward-char))
20849 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20850 ((and (not (eq org-support-shift-select 'always))
20851 (org-at-heading-p))
20852 (let ((org-inhibit-logging
20853 (not org-treat-S-cursor-todo-selection-as-state-change))
20854 (org-inhibit-blocking
20855 (not org-treat-S-cursor-todo-selection-as-state-change)))
20856 (org-call-with-arg 'org-todo 'right)))
20857 ((or (and org-support-shift-select
20858 (not (eq org-support-shift-select 'always))
20859 (org-at-item-bullet-p))
20860 (and (not org-support-shift-select) (org-at-item-p)))
20861 (org-call-with-arg 'org-cycle-list-bullet nil))
20862 ((and (not (eq org-support-shift-select 'always))
20863 (org-at-property-p))
20864 (call-interactively 'org-property-next-allowed-value))
20865 ((org-clocktable-try-shift 'right arg))
20866 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20867 (org-support-shift-select
20868 (org-call-for-shift-select 'forward-char))
20869 (t (org-shiftselect-error))))
20871 (defun org-shiftleft (&optional arg)
20872 "Cycle the thing at point or in the current line, depending on context.
20873 Depending on context, this does one of the following:
20875 - switch a timestamp at point one day into the past
20876 - on a headline, switch to the previous TODO keyword.
20877 - on an item, switch entire list to the previous bullet type
20878 - on a property line, switch to the previous allowed value
20879 - on a clocktable definition line, move time block into the past"
20880 (interactive "P")
20881 (cond
20882 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20883 ((and org-support-shift-select (org-region-active-p))
20884 (org-call-for-shift-select 'backward-char))
20885 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20886 ((and (not (eq org-support-shift-select 'always))
20887 (org-at-heading-p))
20888 (let ((org-inhibit-logging
20889 (not org-treat-S-cursor-todo-selection-as-state-change))
20890 (org-inhibit-blocking
20891 (not org-treat-S-cursor-todo-selection-as-state-change)))
20892 (org-call-with-arg 'org-todo 'left)))
20893 ((or (and org-support-shift-select
20894 (not (eq org-support-shift-select 'always))
20895 (org-at-item-bullet-p))
20896 (and (not org-support-shift-select) (org-at-item-p)))
20897 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20898 ((and (not (eq org-support-shift-select 'always))
20899 (org-at-property-p))
20900 (call-interactively 'org-property-previous-allowed-value))
20901 ((org-clocktable-try-shift 'left arg))
20902 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20903 (org-support-shift-select
20904 (org-call-for-shift-select 'backward-char))
20905 (t (org-shiftselect-error))))
20907 (defun org-shiftcontrolright ()
20908 "Switch to next TODO set."
20909 (interactive)
20910 (cond
20911 ((and org-support-shift-select (org-region-active-p))
20912 (org-call-for-shift-select 'forward-word))
20913 ((and (not (eq org-support-shift-select 'always))
20914 (org-at-heading-p))
20915 (org-call-with-arg 'org-todo 'nextset))
20916 (org-support-shift-select
20917 (org-call-for-shift-select 'forward-word))
20918 (t (org-shiftselect-error))))
20920 (defun org-shiftcontrolleft ()
20921 "Switch to previous TODO set."
20922 (interactive)
20923 (cond
20924 ((and org-support-shift-select (org-region-active-p))
20925 (org-call-for-shift-select 'backward-word))
20926 ((and (not (eq org-support-shift-select 'always))
20927 (org-at-heading-p))
20928 (org-call-with-arg 'org-todo 'previousset))
20929 (org-support-shift-select
20930 (org-call-for-shift-select 'backward-word))
20931 (t (org-shiftselect-error))))
20933 (defun org-shiftcontrolup (&optional n)
20934 "Change timestamps synchronously up in CLOCK log lines.
20935 Optional argument N tells to change by that many units."
20936 (interactive "P")
20937 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20938 (let (org-support-shift-select)
20939 (org-clock-timestamps-up n))
20940 (user-error "Not at a clock log")))
20942 (defun org-shiftcontroldown (&optional n)
20943 "Change timestamps synchronously down in CLOCK log lines.
20944 Optional argument N tells to change by that many units."
20945 (interactive "P")
20946 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20947 (let (org-support-shift-select)
20948 (org-clock-timestamps-down n))
20949 (user-error "Not at a clock log")))
20951 (defun org-increase-number-at-point (&optional inc)
20952 "Increment the number at point.
20953 With an optional prefix numeric argument INC, increment using
20954 this numeric value."
20955 (interactive "p")
20956 (if (not (number-at-point))
20957 (user-error "Not on a number")
20958 (unless inc (setq inc 1))
20959 (let ((pos (point))
20960 (beg (skip-chars-backward "-+^/*0-9eE."))
20961 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20962 (setq nap (buffer-substring-no-properties
20963 (+ pos beg) (+ pos beg end)))
20964 (delete-region (+ pos beg) (+ pos beg end))
20965 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20966 (when (org-at-table-p)
20967 (org-table-align)
20968 (org-table-end-of-field 1))))
20970 (defun org-decrease-number-at-point (&optional inc)
20971 "Decrement the number at point.
20972 With an optional prefix numeric argument INC, decrement using
20973 this numeric value."
20974 (interactive "p")
20975 (org-increase-number-at-point (- (or inc 1))))
20977 (defun org-ctrl-c-ret ()
20978 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20979 (interactive)
20980 (cond
20981 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20982 (t (call-interactively 'org-insert-heading))))
20984 (defun org-find-visible ()
20985 (let ((s (point)))
20986 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20987 (get-char-property s 'invisible)))
20989 (defun org-find-invisible ()
20990 (let ((s (point)))
20991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20992 (not (get-char-property s 'invisible))))
20995 (defun org-copy-visible (beg end)
20996 "Copy the visible parts of the region."
20997 (interactive "r")
20998 (let (snippets s)
20999 (save-excursion
21000 (save-restriction
21001 (narrow-to-region beg end)
21002 (setq s (goto-char (point-min)))
21003 (while (not (= (point) (point-max)))
21004 (goto-char (org-find-invisible))
21005 (push (buffer-substring s (point)) snippets)
21006 (setq s (goto-char (org-find-visible))))))
21007 (kill-new (apply 'concat (nreverse snippets)))))
21009 (defun org-copy-special ()
21010 "Copy region in table or copy current subtree.
21011 Calls `org-table-copy' or `org-copy-subtree', depending on context.
21012 See the individual commands for more information."
21013 (interactive)
21014 (call-interactively
21015 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
21017 (defun org-cut-special ()
21018 "Cut region in table or cut current subtree.
21019 Calls `org-table-copy' or `org-cut-subtree', depending on context.
21020 See the individual commands for more information."
21021 (interactive)
21022 (call-interactively
21023 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
21025 (defun org-paste-special (arg)
21026 "Paste rectangular region into table, or past subtree relative to level.
21027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21028 See the individual commands for more information."
21029 (interactive "P")
21030 (if (org-at-table-p)
21031 (org-table-paste-rectangle)
21032 (org-paste-subtree arg)))
21034 (defsubst org-in-fixed-width-region-p ()
21035 "Is point in a fixed-width region?"
21036 (save-match-data
21037 (eq 'fixed-width (org-element-type (org-element-at-point)))))
21039 (defun org-edit-special (&optional arg)
21040 "Call a special editor for the element at point.
21041 When at a table, call the formula editor with `org-table-edit-formulas'.
21042 When in a source code block, call `org-edit-src-code'.
21043 When in a fixed-width region, call `org-edit-fixed-width-region'.
21044 When in an export block, call `org-edit-export-block'.
21045 When at an #+INCLUDE keyword, visit the included file.
21046 When at a footnote reference, call `org-edit-footnote-reference'
21047 On a link, call `ffap' to visit the link at point.
21048 Otherwise, return a user error."
21049 (interactive "P")
21050 (let ((element (org-element-at-point)))
21051 (cl-assert (not buffer-read-only) nil
21052 "Buffer is read-only: %s" (buffer-name))
21053 (pcase (org-element-type element)
21054 (`src-block
21055 (if (not arg) (org-edit-src-code)
21056 (let* ((info (org-babel-get-src-block-info))
21057 (lang (nth 0 info))
21058 (params (nth 2 info))
21059 (session (cdr (assq :session params))))
21060 (if (not session) (org-edit-src-code)
21061 ;; At a src-block with a session and function called with
21062 ;; an ARG: switch to the buffer related to the inferior
21063 ;; process.
21064 (switch-to-buffer
21065 (funcall (intern (concat "org-babel-prep-session:" lang))
21066 session params))))))
21067 (`keyword
21068 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21069 (org-open-link-from-string
21070 (format "[[%s]]"
21071 (expand-file-name
21072 (let ((value (org-element-property :value element)))
21073 (cond ((not (org-string-nw-p value))
21074 (user-error "No file to edit"))
21075 ((string-match "\\`\"\\(.*?\\)\"" value)
21076 (match-string 1 value))
21077 ((string-match "\\`[^ \t\"]\\S-*" value)
21078 (match-string 0 value))
21079 (t (user-error "No valid file specified")))))))
21080 (user-error "No special environment to edit here")))
21081 (`table
21082 (if (eq (org-element-property :type element) 'table.el)
21083 (org-edit-table.el)
21084 (call-interactively 'org-table-edit-formulas)))
21085 ;; Only Org tables contain `table-row' type elements.
21086 (`table-row (call-interactively 'org-table-edit-formulas))
21087 (`example-block (org-edit-src-code))
21088 (`export-block (org-edit-export-block))
21089 (`fixed-width (org-edit-fixed-width-region))
21091 ;; No notable element at point. Though, we may be at a link or
21092 ;; a footnote reference, which are objects. Thus, scan deeper.
21093 (let ((context (org-element-context element)))
21094 (pcase (org-element-type context)
21095 (`footnote-reference (org-edit-footnote-reference))
21096 (`inline-src-block (org-edit-inline-src-code))
21097 (`link (call-interactively #'ffap))
21098 (_ (user-error "No special environment to edit here"))))))))
21100 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21101 (defun org-ctrl-c-ctrl-c (&optional arg)
21102 "Set tags in headline, or update according to changed information at point.
21104 This command does many different things, depending on context:
21106 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21107 this is what we do.
21109 - If the cursor is on a statistics cookie, update it.
21111 - If the cursor is in a headline, prompt for tags and insert them
21112 into the current line, aligned to `org-tags-column'. When called
21113 with prefix arg, realign all tags in the current buffer.
21115 - If the cursor is in one of the special #+KEYWORD lines, this
21116 triggers scanning the buffer for these lines and updating the
21117 information.
21119 - If the cursor is inside a table, realign the table. This command
21120 works even if the automatic table editor has been turned off.
21122 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21123 the entire table.
21125 - If the cursor is at a footnote reference or definition, jump to
21126 the corresponding definition or references, respectively.
21128 - If the cursor is a the beginning of a dynamic block, update it.
21130 - If the current buffer is a capture buffer, close note and file it.
21132 - If the cursor is on a <<<target>>>, update radio targets and
21133 corresponding links in this buffer.
21135 - If the cursor is on a numbered item in a plain list, renumber the
21136 ordered list.
21138 - If the cursor is on a checkbox, toggle it.
21140 - If the cursor is on a code block, evaluate it. The variable
21141 `org-confirm-babel-evaluate' can be used to control prompting
21142 before code block evaluation, by default every code block
21143 evaluation requires confirmation. Code block evaluation can be
21144 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21145 (interactive "P")
21146 (cond
21147 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21148 org-occur-highlights)
21149 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21150 (org-remove-occur-highlights)
21151 (message "Temporary highlights/overlays removed from current buffer"))
21152 ((and (local-variable-p 'org-finish-function (current-buffer))
21153 (fboundp org-finish-function))
21154 (funcall org-finish-function))
21155 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21157 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21158 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21159 (user-error "C-c C-c can do nothing useful at this location"))
21160 (let* ((context (org-element-context))
21161 (type (org-element-type context)))
21162 (cl-case type
21163 ;; When at a link, act according to the parent instead.
21164 (link (setq context (org-element-property :parent context))
21165 (setq type (org-element-type context)))
21166 ;; Unsupported object types: refer to the first supported
21167 ;; element or object containing it.
21168 ((bold code entity export-snippet inline-babel-call inline-src-block
21169 italic latex-fragment line-break macro strike-through subscript
21170 superscript underline verbatim)
21171 (setq context
21172 (org-element-lineage
21173 context '(radio-target paragraph verse-block table-cell)))))
21174 ;; For convenience: at the first line of a paragraph on the
21175 ;; same line as an item, apply function on that item instead.
21176 (when (eq type 'paragraph)
21177 (let ((parent (org-element-property :parent context)))
21178 (when (and (eq (org-element-type parent) 'item)
21179 (= (line-beginning-position)
21180 (org-element-property :begin parent)))
21181 (setq context parent type 'item))))
21182 ;; Act according to type of element or object at point.
21183 (cl-case type
21184 (clock (org-clock-update-time-maybe))
21185 (dynamic-block
21186 (save-excursion
21187 (goto-char (org-element-property :post-affiliated context))
21188 (org-update-dblock)))
21189 (footnote-definition
21190 (goto-char (org-element-property :post-affiliated context))
21191 (call-interactively 'org-footnote-action))
21192 (footnote-reference (call-interactively 'org-footnote-action))
21193 ((headline inlinetask)
21194 (save-excursion (goto-char (org-element-property :begin context))
21195 (call-interactively 'org-set-tags)))
21196 (item
21197 ;; At an item: a double C-u set checkbox to "[-]"
21198 ;; unconditionally, whereas a single one will toggle its
21199 ;; presence. Without a universal argument, if the item
21200 ;; has a checkbox, toggle it. Otherwise repair the list.
21201 (let* ((box (org-element-property :checkbox context))
21202 (struct (org-element-property :structure context))
21203 (old-struct (copy-tree struct))
21204 (parents (org-list-parents-alist struct))
21205 (prevs (org-list-prevs-alist struct))
21206 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21207 (org-list-set-checkbox
21208 (org-element-property :begin context) struct
21209 (cond ((equal arg '(16)) "[-]")
21210 ((and (not box) (equal arg '(4))) "[ ]")
21211 ((or (not box) (equal arg '(4))) nil)
21212 ((eq box 'on) "[ ]")
21213 (t "[X]")))
21214 ;; Mimic `org-list-write-struct' but with grabbing
21215 ;; a return value from `org-list-struct-fix-box'.
21216 (org-list-struct-fix-ind struct parents 2)
21217 (org-list-struct-fix-item-end struct)
21218 (org-list-struct-fix-bul struct prevs)
21219 (org-list-struct-fix-ind struct parents)
21220 (let ((block-item
21221 (org-list-struct-fix-box struct parents prevs orderedp)))
21222 (if (and box (equal struct old-struct))
21223 (if (equal arg '(16))
21224 (message "Checkboxes already reset")
21225 (user-error "Cannot toggle this checkbox: %s"
21226 (if (eq box 'on)
21227 "all subitems checked"
21228 "unchecked subitems")))
21229 (org-list-struct-apply-struct struct old-struct)
21230 (org-update-checkbox-count-maybe))
21231 (when block-item
21232 (message "Checkboxes were removed due to empty box at line %d"
21233 (org-current-line block-item))))))
21234 (keyword
21235 (let ((org-inhibit-startup-visibility-stuff t)
21236 (org-startup-align-all-tables nil))
21237 (when (boundp 'org-table-coordinate-overlays)
21238 (mapc #'delete-overlay org-table-coordinate-overlays)
21239 (setq org-table-coordinate-overlays nil))
21240 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21241 (message "Local setup has been refreshed"))
21242 (plain-list
21243 ;; At a plain list, with a double C-u argument, set
21244 ;; checkboxes of each item to "[-]", whereas a single one
21245 ;; will toggle their presence according to the state of the
21246 ;; first item in the list. Without an argument, repair the
21247 ;; list.
21248 (let* ((begin (org-element-property :contents-begin context))
21249 (beginm (move-marker (make-marker) begin))
21250 (struct (org-element-property :structure context))
21251 (old-struct (copy-tree struct))
21252 (first-box (save-excursion
21253 (goto-char begin)
21254 (looking-at org-list-full-item-re)
21255 (match-string-no-properties 3)))
21256 (new-box (cond ((equal arg '(16)) "[-]")
21257 ((equal arg '(4)) (unless first-box "[ ]"))
21258 ((equal first-box "[X]") "[ ]")
21259 (t "[X]"))))
21260 (cond
21261 (arg
21262 (dolist (pos
21263 (org-list-get-all-items
21264 begin struct (org-list-prevs-alist struct)))
21265 (org-list-set-checkbox pos struct new-box)))
21266 ((and first-box (eq (point) begin))
21267 ;; For convenience, when point is at bol on the first
21268 ;; item of the list and no argument is provided, simply
21269 ;; toggle checkbox of that item, if any.
21270 (org-list-set-checkbox begin struct new-box)))
21271 (org-list-write-struct
21272 struct (org-list-parents-alist struct) old-struct)
21273 (org-update-checkbox-count-maybe)
21274 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21275 ((property-drawer node-property)
21276 (call-interactively 'org-property-action))
21277 ((radio-target target)
21278 (call-interactively 'org-update-radio-target-regexp))
21279 (statistics-cookie
21280 (call-interactively 'org-update-statistics-cookies))
21281 ((table table-cell table-row)
21282 ;; At a table, recalculate every field and align it. Also
21283 ;; send the table if necessary. If the table has
21284 ;; a `table.el' type, just give up. At a table row or
21285 ;; cell, maybe recalculate line but always align table.
21286 (if (eq (org-element-property :type context) 'table.el)
21287 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21288 Use \\[org-edit-special] to edit table.el tables"))
21289 (let ((org-enable-table-editor t))
21290 (if (or (eq type 'table)
21291 ;; Check if point is at a TBLFM line.
21292 (and (eq type 'table-row)
21293 (= (point) (org-element-property :end context))))
21294 (save-excursion
21295 (if (org-at-TBLFM-p)
21296 (progn (require 'org-table)
21297 (org-table-calc-current-TBLFM))
21298 (goto-char (org-element-property :contents-begin context))
21299 (org-call-with-arg 'org-table-recalculate (or arg t))
21300 (orgtbl-send-table 'maybe)))
21301 (org-table-maybe-eval-formula)
21302 (cond (arg (call-interactively 'org-table-recalculate))
21303 ((org-table-maybe-recalculate-line))
21304 (t (org-table-align)))))))
21305 (timestamp (org-timestamp-change 0 'day))
21306 (otherwise
21307 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21308 (user-error
21309 "C-c C-c can do nothing useful at this location")))))))))
21311 (defun org-mode-restart ()
21312 (interactive)
21313 (let ((indent-status (bound-and-true-p org-indent-mode)))
21314 (funcall major-mode)
21315 (hack-local-variables)
21316 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21317 (org-indent-mode -1)))
21318 (message "%s restarted" major-mode))
21320 (defun org-kill-note-or-show-branches ()
21321 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21322 (interactive)
21323 (if (not org-finish-function)
21324 (progn
21325 (outline-hide-subtree)
21326 (call-interactively 'outline-show-branches))
21327 (let ((org-note-abort t))
21328 (funcall org-finish-function))))
21330 (defun org-delete-indentation (&optional ARG)
21331 "Join current line to previous and fix whitespace at join.
21333 If previous line is a headline add to headline title. Otherwise
21334 the function calls `delete-indentation'.
21336 With argument, join this line to following line."
21337 (interactive "*P")
21338 (if (save-excursion
21339 (if ARG (beginning-of-line)
21340 (forward-line -1))
21341 (looking-at org-complex-heading-regexp))
21342 ;; At headline.
21343 (let ((tags-column (when (match-beginning 5)
21344 (save-excursion (goto-char (match-beginning 5))
21345 (current-column))))
21346 (string (concat " " (progn (when ARG (forward-line 1))
21347 (org-trim (delete-and-extract-region
21348 (line-beginning-position)
21349 (line-end-position)))))))
21350 (unless (bobp) (delete-region (point) (1- (point))))
21351 (goto-char (or (match-end 4)
21352 (match-beginning 5)
21353 (match-end 0)))
21354 (skip-chars-backward " \t")
21355 (save-excursion (insert string))
21356 ;; Adjust alignment of tags.
21357 (when tags-column
21358 (org-align-tags-here (if org-auto-align-tags
21359 org-tags-column
21360 tags-column))))
21361 (delete-indentation ARG)))
21363 (defun org-open-line (n)
21364 "Insert a new row in tables, call `open-line' elsewhere.
21365 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21366 (interactive "*p")
21367 (cond
21368 ((not org-special-ctrl-o)
21369 (open-line n))
21370 ((org-at-table-p)
21371 (org-table-insert-row))
21373 (open-line n))))
21375 (defun org-return (&optional indent)
21376 "Goto next table row or insert a newline.
21378 Calls `org-table-next-row' or `newline', depending on context.
21380 When optional INDENT argument is non-nil, call
21381 `newline-and-indent' instead of `newline'.
21383 When `org-return-follows-link' is non-nil and point is on
21384 a timestamp or a link, call `org-open-at-point'. However, it
21385 will not happen if point is in a table or on a \"dead\"
21386 object (e.g., within a comment). In these case, you need to use
21387 `org-open-at-point' directly."
21388 (interactive)
21389 (let ((context (if org-return-follows-link (org-element-context)
21390 (org-element-at-point))))
21391 (cond
21392 ;; In a table, call `org-table-next-row'.
21393 ((or (and (eq (org-element-type context) 'table)
21394 (>= (point) (org-element-property :contents-begin context))
21395 (< (point) (org-element-property :contents-end context)))
21396 (org-element-lineage context '(table-row table-cell) t))
21397 (org-table-justify-field-maybe)
21398 (call-interactively #'org-table-next-row))
21399 ;; On a link or a timestamp, call `org-open-at-point' if
21400 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21401 ;; locations, e.g., in a comment, as `org-open-at-point'.
21402 ((and org-return-follows-link
21403 (or (org-in-regexp org-ts-regexp-both nil t)
21404 (org-in-regexp org-tsr-regexp-both nil t)
21405 (org-in-regexp org-any-link-re nil t)))
21406 (call-interactively #'org-open-at-point))
21407 ;; Insert newline in heading, but preserve tags.
21408 ((and (not (bolp))
21409 (save-excursion (beginning-of-line)
21410 (looking-at org-complex-heading-regexp)))
21411 ;; At headline. Split line. However, if point is on keyword,
21412 ;; priority cookie or tags, do not break any of them: add
21413 ;; a newline after the headline instead.
21414 (let ((tags-column (and (match-beginning 5)
21415 (save-excursion (goto-char (match-beginning 5))
21416 (current-column))))
21417 (string
21418 (when (and (match-end 4)
21419 (>= (point)
21420 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21421 (<= (point) (match-end 4)))
21422 (delete-and-extract-region (point) (match-end 4)))))
21423 (when (and tags-column string) ; Adjust tag alignment.
21424 (org-align-tags-here
21425 (if org-auto-align-tags org-tags-column tags-column)))
21426 (end-of-line)
21427 (org-show-entry)
21428 (if indent (newline-and-indent) (newline))
21429 (when string (save-excursion (insert (org-trim string))))))
21430 ;; In a list, make sure indenting keeps trailing text within.
21431 ((and indent
21432 (not (eolp))
21433 (org-element-lineage context '(item)))
21434 (let ((trailing-data
21435 (delete-and-extract-region (point) (line-end-position))))
21436 (newline-and-indent)
21437 (save-excursion (insert trailing-data))))
21438 (t (if indent (newline-and-indent) (newline))))))
21440 (defun org-return-indent ()
21441 "Goto next table row or insert a newline and indent.
21442 Calls `org-table-next-row' or `newline-and-indent', depending on
21443 context. See the individual commands for more information."
21444 (interactive)
21445 (org-return t))
21447 (defun org-ctrl-c-star ()
21448 "Compute table, or change heading status of lines.
21449 Calls `org-table-recalculate' or `org-toggle-heading',
21450 depending on context."
21451 (interactive)
21452 (cond
21453 ((org-at-table-p)
21454 (call-interactively 'org-table-recalculate))
21456 ;; Convert all lines in region to list items
21457 (call-interactively 'org-toggle-heading))))
21459 (defun org-ctrl-c-minus ()
21460 "Insert separator line in table or modify bullet status of line.
21461 Also turns a plain line or a region of lines into list items.
21462 Calls `org-table-insert-hline', `org-toggle-item', or
21463 `org-cycle-list-bullet', depending on context."
21464 (interactive)
21465 (cond
21466 ((org-at-table-p)
21467 (call-interactively 'org-table-insert-hline))
21468 ((org-region-active-p)
21469 (call-interactively 'org-toggle-item))
21470 ((org-in-item-p)
21471 (call-interactively 'org-cycle-list-bullet))
21473 (call-interactively 'org-toggle-item))))
21475 (defun org-toggle-heading (&optional nstars)
21476 "Convert headings to normal text, or items or text to headings.
21477 If there is no active region, only convert the current line.
21479 With a \\[universal-argument] prefix, convert the whole list at
21480 point into heading.
21482 In a region:
21484 - If the first non blank line is a headline, remove the stars
21485 from all headlines in the region.
21487 - If it is a normal line, turn each and every normal line (i.e.,
21488 not an heading or an item) in the region into headings. If you
21489 want to convert only the first line of this region, use one
21490 universal prefix argument.
21492 - If it is a plain list item, turn all plain list items into headings.
21494 When converting a line into a heading, the number of stars is chosen
21495 such that the lines become children of the current entry. However,
21496 when a numeric prefix argument is given, its value determines the
21497 number of stars to add."
21498 (interactive "P")
21499 (let ((skip-blanks
21500 (function
21501 ;; Return beginning of first non-blank line, starting from
21502 ;; line at POS.
21503 (lambda (pos)
21504 (save-excursion
21505 (goto-char pos)
21506 (while (org-at-comment-p) (forward-line))
21507 (skip-chars-forward " \r\t\n")
21508 (point-at-bol)))))
21509 beg end toggled)
21510 ;; Determine boundaries of changes. If a universal prefix has
21511 ;; been given, put the list in a region. If region ends at a bol,
21512 ;; do not consider the last line to be in the region.
21514 (when (and current-prefix-arg (org-at-item-p))
21515 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21516 (org-mark-element))
21518 (if (org-region-active-p)
21519 (setq beg (funcall skip-blanks (region-beginning))
21520 end (copy-marker (save-excursion
21521 (goto-char (region-end))
21522 (if (bolp) (point) (point-at-eol)))))
21523 (setq beg (funcall skip-blanks (point-at-bol))
21524 end (copy-marker (point-at-eol))))
21525 ;; Ensure inline tasks don't count as headings.
21526 (org-with-limited-levels
21527 (save-excursion
21528 (goto-char beg)
21529 (cond
21530 ;; Case 1. Started at an heading: de-star headings.
21531 ((org-at-heading-p)
21532 (while (< (point) end)
21533 (when (org-at-heading-p t)
21534 (looking-at org-outline-regexp) (replace-match "")
21535 (setq toggled t))
21536 (forward-line)))
21537 ;; Case 2. Started at an item: change items into headlines.
21538 ;; One star will be added by `org-list-to-subtree'.
21539 ((org-at-item-p)
21540 (while (< (point) end)
21541 (when (org-at-item-p)
21542 ;; Pay attention to cases when region ends before list.
21543 (let* ((struct (org-list-struct))
21544 (list-end
21545 (min (org-list-get-bottom-point struct) (1+ end))))
21546 (save-restriction
21547 (narrow-to-region (point) list-end)
21548 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21549 (setq toggled t))
21550 (forward-line)))
21551 ;; Case 3. Started at normal text: make every line an heading,
21552 ;; skipping headlines and items.
21553 (t (let* ((stars
21554 (make-string
21555 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21556 (add-stars
21557 (cond (nstars "") ; stars from prefix only
21558 ((equal stars "") "*") ; before first heading
21559 (org-odd-levels-only "**") ; inside heading, odd
21560 (t "*"))) ; inside heading, oddeven
21561 (rpl (concat stars add-stars " "))
21562 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21563 (while (< (point) (if (equal nstars '(4)) lend end))
21564 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21565 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21566 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21567 (forward-line)))))))
21568 (unless toggled (message "Cannot toggle heading from here"))))
21570 (defun org-meta-return (&optional _arg)
21571 "Insert a new heading or wrap a region in a table.
21572 Calls `org-insert-heading' or `org-table-wrap-region', depending
21573 on context. See the individual commands for more information."
21574 (interactive)
21575 (org-check-before-invisible-edit 'insert)
21576 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21577 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21578 #'org-insert-heading))))
21580 ;;; Menu entries
21582 (defsubst org-in-subtree-not-table-p ()
21583 "Are we in a subtree and not in a table?"
21584 (and (not (org-before-first-heading-p))
21585 (not (org-at-table-p))))
21587 ;; Define the Org-mode menus
21588 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21589 '("Tbl"
21590 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21591 ["Next Field" org-cycle (org-at-table-p)]
21592 ["Previous Field" org-shifttab (org-at-table-p)]
21593 ["Next Row" org-return (org-at-table-p)]
21594 "--"
21595 ["Blank Field" org-table-blank-field (org-at-table-p)]
21596 ["Edit Field" org-table-edit-field (org-at-table-p)]
21597 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21598 "--"
21599 ("Column"
21600 ["Move Column Left" org-metaleft (org-at-table-p)]
21601 ["Move Column Right" org-metaright (org-at-table-p)]
21602 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21603 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21604 ("Row"
21605 ["Move Row Up" org-metaup (org-at-table-p)]
21606 ["Move Row Down" org-metadown (org-at-table-p)]
21607 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21608 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21609 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21610 "--"
21611 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21612 ("Rectangle"
21613 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21614 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21615 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21616 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21617 "--"
21618 ("Calculate"
21619 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21620 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21621 ["Edit Formulas" org-edit-special (org-at-table-p)]
21622 "--"
21623 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21624 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21625 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21626 "--"
21627 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21628 "--"
21629 ["Sum Column/Rectangle" org-table-sum
21630 (or (org-at-table-p) (org-region-active-p))]
21631 ["Which Column?" org-table-current-column (org-at-table-p)])
21632 ["Debug Formulas"
21633 org-table-toggle-formula-debugger
21634 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21635 ["Show Col/Row Numbers"
21636 org-table-toggle-coordinate-overlays
21637 :style toggle
21638 :selected (bound-and-true-p org-table-overlay-coordinates)]
21639 "--"
21640 ["Create" org-table-create (and (not (org-at-table-p))
21641 org-enable-table-editor)]
21642 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21643 ["Import from File" org-table-import (not (org-at-table-p))]
21644 ["Export to File" org-table-export (org-at-table-p)]
21645 "--"
21646 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21647 "--"
21648 ("Plot"
21649 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21650 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21652 (easy-menu-define org-org-menu org-mode-map "Org menu"
21653 '("Org"
21654 ("Show/Hide"
21655 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21656 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21657 ["Sparse Tree..." org-sparse-tree t]
21658 ["Reveal Context" org-reveal t]
21659 ["Show All" outline-show-all t]
21660 "--"
21661 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21662 "--"
21663 ["New Heading" org-insert-heading t]
21664 ("Navigate Headings"
21665 ["Up" outline-up-heading t]
21666 ["Next" outline-next-visible-heading t]
21667 ["Previous" outline-previous-visible-heading t]
21668 ["Next Same Level" outline-forward-same-level t]
21669 ["Previous Same Level" outline-backward-same-level t]
21670 "--"
21671 ["Jump" org-goto t])
21672 ("Edit Structure"
21673 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21674 "--"
21675 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21676 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21677 "--"
21678 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21679 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21680 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21681 "--"
21682 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21683 "--"
21684 ["Copy visible text" org-copy-visible t]
21685 "--"
21686 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21687 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21688 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21689 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21690 "--"
21691 ["Sort Region/Children" org-sort t]
21692 "--"
21693 ["Convert to odd levels" org-convert-to-odd-levels t]
21694 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21695 ("Editing"
21696 ["Emphasis..." org-emphasize t]
21697 ["Edit Source Example" org-edit-special t]
21698 "--"
21699 ["Footnote new/jump" org-footnote-action t]
21700 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21701 ("Archive"
21702 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21703 "--"
21704 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21705 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21706 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21708 "--"
21709 ("Hyperlinks"
21710 ["Store Link (Global)" org-store-link t]
21711 ["Find existing link to here" org-occur-link-in-agenda-files t]
21712 ["Insert Link" org-insert-link t]
21713 ["Follow Link" org-open-at-point t]
21714 "--"
21715 ["Next link" org-next-link t]
21716 ["Previous link" org-previous-link t]
21717 "--"
21718 ["Descriptive Links"
21719 org-toggle-link-display
21720 :style radio
21721 :selected org-descriptive-links
21723 ["Literal Links"
21724 org-toggle-link-display
21725 :style radio
21726 :selected (not org-descriptive-links)])
21727 "--"
21728 ("TODO Lists"
21729 ["TODO/DONE/-" org-todo t]
21730 ("Select keyword"
21731 ["Next keyword" org-shiftright (org-at-heading-p)]
21732 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21733 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21734 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21735 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21736 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21737 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21738 "--"
21739 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21740 :selected org-enforce-todo-dependencies :style toggle :active t]
21741 "Settings for tree at point"
21742 ["Do Children sequentially" org-toggle-ordered-property :style radio
21743 :selected (org-entry-get nil "ORDERED")
21744 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21745 ["Do Children parallel" org-toggle-ordered-property :style radio
21746 :selected (not (org-entry-get nil "ORDERED"))
21747 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21748 "--"
21749 ["Set Priority" org-priority t]
21750 ["Priority Up" org-shiftup t]
21751 ["Priority Down" org-shiftdown t]
21752 "--"
21753 ["Get news from all feeds" org-feed-update-all t]
21754 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21755 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21756 ("TAGS and Properties"
21757 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21758 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21759 "--"
21760 ["Set property" org-set-property (not (org-before-first-heading-p))]
21761 ["Column view of properties" org-columns t]
21762 ["Insert Column View DBlock" org-columns-insert-dblock t])
21763 ("Dates and Scheduling"
21764 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21765 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21766 ("Change Date"
21767 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21768 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21769 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21770 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21771 ["Compute Time Range" org-evaluate-time-range t]
21772 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21773 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21774 "--"
21775 ["Custom time format" org-toggle-time-stamp-overlays
21776 :style radio :selected org-display-custom-times]
21777 "--"
21778 ["Goto Calendar" org-goto-calendar t]
21779 ["Date from Calendar" org-date-from-calendar t]
21780 "--"
21781 ["Start/Restart Timer" org-timer-start t]
21782 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21783 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21784 ["Insert Timer String" org-timer t]
21785 ["Insert Timer Item" org-timer-item t])
21786 ("Logging work"
21787 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21788 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21789 ["Clock out" org-clock-out t]
21790 ["Clock cancel" org-clock-cancel t]
21791 "--"
21792 ["Mark as default task" org-clock-mark-default-task t]
21793 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21794 ["Goto running clock" org-clock-goto t]
21795 "--"
21796 ["Display times" org-clock-display t]
21797 ["Create clock table" org-clock-report t]
21798 "--"
21799 ["Record DONE time"
21800 (progn (setq org-log-done (not org-log-done))
21801 (message "Switching to %s will %s record a timestamp"
21802 (car org-done-keywords)
21803 (if org-log-done "automatically" "not")))
21804 :style toggle :selected org-log-done])
21805 "--"
21806 ["Agenda Command..." org-agenda t]
21807 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21808 ("File List for Agenda")
21809 ("Special views current file"
21810 ["TODO Tree" org-show-todo-tree t]
21811 ["Check Deadlines" org-check-deadlines t]
21812 ["Timeline" org-timeline t]
21813 ["Tags/Property tree" org-match-sparse-tree t])
21814 "--"
21815 ["Export/Publish..." org-export-dispatch t]
21816 ("LaTeX"
21817 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21818 :selected org-cdlatex-mode]
21819 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21820 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21821 ["Modify math symbol" org-cdlatex-math-modify
21822 (org-inside-LaTeX-fragment-p)]
21823 ["Insert citation" org-reftex-citation t])
21824 "--"
21825 ("MobileOrg"
21826 ["Push Files and Views" org-mobile-push t]
21827 ["Get Captured and Flagged" org-mobile-pull t]
21828 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21829 "--"
21830 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21831 "--"
21832 ("Documentation"
21833 ["Show Version" org-version t]
21834 ["Info Documentation" org-info t])
21835 ("Customize"
21836 ["Browse Org Group" org-customize t]
21837 "--"
21838 ["Expand This Menu" org-create-customize-menu
21839 (fboundp 'customize-menu-create)])
21840 ["Send bug report" org-submit-bug-report t]
21841 "--"
21842 ("Refresh/Reload"
21843 ["Refresh setup current buffer" org-mode-restart t]
21844 ["Reload Org (after update)" org-reload t]
21845 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21848 (defun org-info (&optional node)
21849 "Read documentation for Org-mode in the info system.
21850 With optional NODE, go directly to that node."
21851 (interactive)
21852 (info (format "(org)%s" (or node ""))))
21854 ;;;###autoload
21855 (defun org-submit-bug-report ()
21856 "Submit a bug report on Org-mode via mail.
21858 Don't hesitate to report any problems or inaccurate documentation.
21860 If you don't have setup sending mail from (X)Emacs, please copy the
21861 output buffer into your mail program, as it gives us important
21862 information about your Org-mode version and configuration."
21863 (interactive)
21864 (require 'reporter)
21865 (defvar reporter-prompt-for-summary-p)
21866 (org-load-modules-maybe)
21867 (org-require-autoloaded-modules)
21868 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21869 (reporter-submit-bug-report
21870 "emacs-orgmode@gnu.org"
21871 (org-version nil 'full)
21872 (let (list)
21873 (save-window-excursion
21874 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21875 (delete-other-windows)
21876 (erase-buffer)
21877 (insert "You are about to submit a bug report to the Org-mode mailing list.
21879 We would like to add your full Org-mode and Outline configuration to the
21880 bug report. This greatly simplifies the work of the maintainer and
21881 other experts on the mailing list.
21883 HOWEVER, some variables you have customized may contain private
21884 information. The names of customers, colleagues, or friends, might
21885 appear in the form of file names, tags, todo states, or search strings.
21886 If you answer yes to the prompt, you might want to check and remove
21887 such private information before sending the email.")
21888 (add-text-properties (point-min) (point-max) '(face org-warning))
21889 (when (yes-or-no-p "Include your Org-mode configuration ")
21890 (mapatoms
21891 (lambda (v)
21892 (and (boundp v)
21893 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21894 (or (and (symbol-value v)
21895 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21896 (and
21897 (get v 'custom-type) (get v 'standard-value)
21898 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21899 (push v list)))))
21900 (kill-buffer (get-buffer "*Warn about privacy*"))
21901 list))
21902 nil nil
21903 "Remember to cover the basics, that is, what you expected to happen and
21904 what in fact did happen. You don't know how to make a good report? See
21906 http://orgmode.org/manual/Feedback.html#Feedback
21908 Your bug report will be posted to the Org-mode mailing list.
21909 ------------------------------------------------------------------------")
21910 (save-excursion
21911 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21912 (replace-match "\\1Bug: \\3 [\\2]")))))
21915 (defun org-install-agenda-files-menu ()
21916 (let ((bl (buffer-list)))
21917 (save-excursion
21918 (while bl
21919 (set-buffer (pop bl))
21920 (when (derived-mode-p 'org-mode) (setq bl nil)))
21921 (when (derived-mode-p 'org-mode)
21922 (easy-menu-change
21923 '("Org") "File List for Agenda"
21924 (append
21925 (list
21926 ["Edit File List" (org-edit-agenda-file-list) t]
21927 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21928 ["Remove Current File from List" org-remove-file t]
21929 ["Cycle through agenda files" org-cycle-agenda-files t]
21930 ["Occur in all agenda files" org-occur-in-agenda-files t]
21931 "--")
21932 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21934 ;;;; Documentation
21936 (defun org-require-autoloaded-modules ()
21937 (interactive)
21938 (mapc #'require
21939 '(org-agenda org-archive org-attach org-clock org-colview org-id
21940 org-table org-timer)))
21942 ;;;###autoload
21943 (defun org-reload (&optional uncompiled)
21944 "Reload all org lisp files.
21945 With prefix arg UNCOMPILED, load the uncompiled versions."
21946 (interactive "P")
21947 (require 'loadhist)
21948 (let* ((org-dir (org-find-library-dir "org"))
21949 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21950 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21951 (remove-re (format "\\`%s\\'"
21952 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21953 (feats (delete-dups
21954 (mapcar 'file-name-sans-extension
21955 (mapcar 'file-name-nondirectory
21956 (delq nil
21957 (mapcar 'feature-file
21958 features))))))
21959 (lfeat (append
21960 (sort
21961 (setq feats
21962 (delq nil (mapcar
21963 (lambda (f)
21964 (if (and (string-match feature-re f)
21965 (not (string-match remove-re f)))
21966 f nil))
21967 feats)))
21968 'string-lessp)
21969 (list "org-version" "org")))
21970 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21971 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21972 load-uncore load-misses)
21973 (setq load-misses
21974 (delq 't
21975 (mapcar (lambda (f)
21976 (or (org-load-noerror-mustsuffix (concat org-dir f))
21977 (and (string= org-dir contrib-dir)
21978 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21979 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21980 (add-to-list 'load-uncore f 'append)
21983 lfeat)))
21984 (when load-uncore
21985 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21986 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21987 (if load-misses
21988 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21989 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21990 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21992 ;;;###autoload
21993 (defun org-customize ()
21994 "Call the customize function with org as argument."
21995 (interactive)
21996 (org-load-modules-maybe)
21997 (org-require-autoloaded-modules)
21998 (customize-browse 'org))
22000 (defun org-create-customize-menu ()
22001 "Create a full customization menu for Org-mode, insert it into the menu."
22002 (interactive)
22003 (org-load-modules-maybe)
22004 (org-require-autoloaded-modules)
22005 (if (fboundp 'customize-menu-create)
22006 (progn
22007 (easy-menu-change
22008 '("Org") "Customize"
22009 `(["Browse Org group" org-customize t]
22010 "--"
22011 ,(customize-menu-create 'org)
22012 ["Set" Custom-set t]
22013 ["Save" Custom-save t]
22014 ["Reset to Current" Custom-reset-current t]
22015 ["Reset to Saved" Custom-reset-saved t]
22016 ["Reset to Standard Settings" Custom-reset-standard t]))
22017 (message "\"Org\"-menu now contains full customization menu"))
22018 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22020 ;;;; Miscellaneous stuff
22022 ;;; Generally useful functions
22024 (defun org-get-at-eol (property n)
22025 "Get text property PROPERTY at the end of line less N characters."
22026 (get-text-property (- (point-at-eol) n) property))
22028 (defun org-find-text-property-in-string (prop s)
22029 "Return the first non-nil value of property PROP in string S."
22030 (or (get-text-property 0 prop s)
22031 (get-text-property (or (next-single-property-change 0 prop s) 0)
22032 prop s)))
22034 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22035 "Display the given MESSAGE as a warning."
22036 (if (fboundp 'display-warning)
22037 (display-warning 'org message :warning)
22038 (let ((buf (get-buffer-create "*Org warnings*")))
22039 (with-current-buffer buf
22040 (goto-char (point-max))
22041 (insert "Warning (Org): " message)
22042 (unless (bolp)
22043 (newline)))
22044 (display-buffer buf)
22045 (sit-for 0))))
22047 (defun org-eval (form)
22048 "Eval FORM and return result."
22049 (condition-case error
22050 (eval form)
22051 (error (format "%%![Error: %s]" error))))
22053 (defun org-in-clocktable-p ()
22054 "Check if the cursor is in a clocktable."
22055 (let ((pos (point)) start)
22056 (save-excursion
22057 (end-of-line 1)
22058 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22059 (setq start (match-beginning 0))
22060 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22061 (>= (match-end 0) pos)
22062 start))))
22064 (defun org-in-verbatim-emphasis ()
22065 (save-match-data
22066 (and (org-in-regexp org-emph-re 2)
22067 (>= (point) (match-beginning 3))
22068 (<= (point) (match-end 4))
22069 (member (match-string 3) '("=" "~")))))
22071 (defun org-overlay-display (ovl text &optional face evap)
22072 "Make overlay OVL display TEXT with face FACE."
22073 (overlay-put ovl 'display text)
22074 (if face (overlay-put ovl 'face face))
22075 (if evap (overlay-put ovl 'evaporate t)))
22077 (defun org-overlay-before-string (ovl text &optional face evap)
22078 "Make overlay OVL display TEXT with face FACE."
22079 (if face (org-add-props text nil 'face face))
22080 (overlay-put ovl 'before-string text)
22081 (if evap (overlay-put ovl 'evaporate t)))
22083 (defun org-find-overlays (prop &optional pos delete)
22084 "Find all overlays specifying PROP at POS or point.
22085 If DELETE is non-nil, delete all those overlays."
22086 (let (found)
22087 (dolist (ov (overlays-at (or pos (point))) found)
22088 (cond ((not (overlay-get ov prop)))
22089 (delete (delete-overlay ov))
22090 (t (push ov found))))))
22092 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22093 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22094 (if (and marker (marker-buffer marker)
22095 (buffer-live-p (marker-buffer marker)))
22096 (progn
22097 (pop-to-buffer-same-window (marker-buffer marker))
22098 (when (or (> marker (point-max)) (< marker (point-min)))
22099 (widen))
22100 (goto-char marker)
22101 (org-show-context 'org-goto))
22102 (if bookmark
22103 (bookmark-jump bookmark)
22104 (error "Cannot find location"))))
22106 (defun org-quote-csv-field (s)
22107 "Quote field for inclusion in CSV material."
22108 (if (string-match "[\",]" s)
22109 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22112 (defun org-force-self-insert (N)
22113 "Needed to enforce self-insert under remapping."
22114 (interactive "p")
22115 (self-insert-command N))
22117 (defun org-string-width (s)
22118 "Compute width of string, ignoring invisible characters.
22119 This ignores character with invisibility property `org-link', and also
22120 characters with property `org-cwidth', because these will become invisible
22121 upon the next fontification round."
22122 (let (b l)
22123 (when (or (eq t buffer-invisibility-spec)
22124 (assq 'org-link buffer-invisibility-spec))
22125 (while (setq b (text-property-any 0 (length s)
22126 'invisible 'org-link s))
22127 (setq s (concat (substring s 0 b)
22128 (substring s (or (next-single-property-change
22129 b 'invisible s)
22130 (length s)))))))
22131 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22132 (setq s (concat (substring s 0 b)
22133 (substring s (or (next-single-property-change
22134 b 'org-cwidth s)
22135 (length s))))))
22136 (setq l (string-width s) b -1)
22137 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22138 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22141 (defun org-shorten-string (s maxlength)
22142 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22143 If the string is shorter or has length MAXLENGTH, just return the
22144 original string. If it is longer, the functions finds a space in the
22145 string, breaks this string off at that locations and adds three dots
22146 as ellipsis. Including the ellipsis, the string will not be longer
22147 than MAXLENGTH. If finding a good breaking point in the string does
22148 not work, the string is just chopped off in the middle of a word
22149 if necessary."
22150 (if (<= (length s) maxlength)
22152 (let* ((n (max (- maxlength 4) 1))
22153 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22154 (if (string-match re s)
22155 (concat (match-string 1 s) "...")
22156 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22158 (defun org-get-indentation (&optional line)
22159 "Get the indentation of the current line, interpreting tabs.
22160 When LINE is given, assume it represents a line and compute its indentation."
22161 (if line
22162 (when (string-match "^ *" (org-remove-tabs line))
22163 (match-end 0))
22164 (save-excursion
22165 (beginning-of-line 1)
22166 (skip-chars-forward " \t")
22167 (current-column))))
22169 (defun org-get-string-indentation (s)
22170 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22171 (let ((n -1) (i 0) (w tab-width) c)
22172 (catch 'exit
22173 (while (< (setq n (1+ n)) (length s))
22174 (setq c (aref s n))
22175 (cond ((= c ?\ ) (setq i (1+ i)))
22176 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22177 (t (throw 'exit t)))))
22180 (defun org-remove-tabs (s &optional width)
22181 "Replace tabulators in S with spaces.
22182 Assumes that s is a single line, starting in column 0."
22183 (setq width (or width tab-width))
22184 (while (string-match "\t" s)
22185 (setq s (replace-match
22186 (make-string
22187 (- (* width (/ (+ (match-beginning 0) width) width))
22188 (match-beginning 0)) ?\ )
22189 t t s)))
22192 (defun org-fix-indentation (line ind)
22193 "Fix indentation in LINE.
22194 IND is a cons cell with target and minimum indentation.
22195 If the current indentation in LINE is smaller than the minimum,
22196 leave it alone. If it is larger than ind, set it to the target."
22197 (let* ((l (org-remove-tabs line))
22198 (i (org-get-indentation l))
22199 (i1 (car ind)) (i2 (cdr ind)))
22200 (when (>= i i2) (setq l (substring line i2)))
22201 (if (> i1 0)
22202 (concat (make-string i1 ?\ ) l)
22203 l)))
22205 (defun org-remove-indentation (code &optional n)
22206 "Remove maximum common indentation in string CODE and return it.
22207 N may optionally be the number of columns to remove. Return CODE
22208 as-is if removal failed."
22209 (with-temp-buffer
22210 (insert code)
22211 (if (org-do-remove-indentation n) (buffer-string) code)))
22213 (defun org-do-remove-indentation (&optional n)
22214 "Remove the maximum common indentation from the buffer.
22215 When optional argument N is a positive integer, remove exactly
22216 that much characters from indentation, if possible. Return nil
22217 if it fails."
22218 (catch :exit
22219 (goto-char (point-min))
22220 ;; Find maximum common indentation, if not specified.
22221 (let ((n (or n
22222 (let ((min-ind (point-max)))
22223 (save-excursion
22224 (while (re-search-forward "^[ \t]*\\S-" nil t)
22225 (let ((ind (1- (current-column))))
22226 (if (zerop ind) (throw :exit nil)
22227 (setq min-ind (min min-ind ind))))))
22228 min-ind))))
22229 (if (zerop n) (throw :exit nil)
22230 ;; Remove exactly N indentation, but give up if not possible.
22231 (while (not (eobp))
22232 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22233 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22234 ((< ind n) (throw :exit nil))
22235 (t (indent-line-to (- ind n))))
22236 (forward-line)))
22237 ;; Signal success.
22238 t))))
22240 (defun org-fill-template (template alist)
22241 "Find each %key of ALIST in TEMPLATE and replace it."
22242 (let ((case-fold-search nil))
22243 (dolist (entry (sort (copy-sequence alist)
22244 (lambda (a b) (< (length (car a)) (length (car b))))))
22245 (setq template
22246 (replace-regexp-in-string
22247 (concat "%" (regexp-quote (car entry)))
22248 (or (cdr entry) "") template t t)))
22249 template))
22251 (defun org-base-buffer (buffer)
22252 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22253 (if (not buffer)
22254 buffer
22255 (or (buffer-base-buffer buffer)
22256 buffer)))
22258 (defun org-wrap (string &optional width lines)
22259 "Wrap string to either a number of lines, or a width in characters.
22260 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22261 that costs. If there is a word longer than WIDTH, the text is actually
22262 wrapped to the length of that word.
22263 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22264 many lines, whatever width that takes.
22265 The return value is a list of lines, without newlines at the end."
22266 (let* ((words (org-split-string string "[ \t\n]+"))
22267 (maxword (apply 'max (mapcar 'org-string-width words)))
22268 w ll)
22269 (cond (width
22270 (org-do-wrap words (max maxword width)))
22271 (lines
22272 (setq w maxword)
22273 (setq ll (org-do-wrap words maxword))
22274 (if (<= (length ll) lines)
22276 (setq ll words)
22277 (while (> (length ll) lines)
22278 (setq w (1+ w))
22279 (setq ll (org-do-wrap words w)))
22280 ll))
22281 (t (error "Cannot wrap this")))))
22283 (defun org-do-wrap (words width)
22284 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22285 (let (lines line)
22286 (while words
22287 (setq line (pop words))
22288 (while (and words (< (+ (length line) (length (car words))) width))
22289 (setq line (concat line " " (pop words))))
22290 (setq lines (push line lines)))
22291 (nreverse lines)))
22293 (defun org-split-string (string &optional separators)
22294 "Splits STRING into substrings at SEPARATORS.
22295 SEPARATORS is a regular expression.
22296 No empty strings are returned if there are matches at the beginning
22297 and end of string."
22298 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22299 (let ((start 0) notfirst list)
22300 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22301 (if (and notfirst
22302 (= start (match-beginning 0))
22303 (< start (length string)))
22304 (1+ start) start))
22305 (< (match-beginning 0) (length string)))
22306 (setq notfirst t)
22307 (or (eq (match-beginning 0) 0)
22308 (and (eq (match-beginning 0) (match-end 0))
22309 (eq (match-beginning 0) start))
22310 (push (substring string start (match-beginning 0)) list))
22311 (setq start (match-end 0)))
22312 (or (eq start (length string))
22313 (push (substring string start) list))
22314 (nreverse list)))
22316 (defun org-quote-vert (s)
22317 "Replace \"|\" with \"\\vert\"."
22318 (while (string-match "|" s)
22319 (setq s (replace-match "\\vert" t t s)))
22322 (defun org-uuidgen-p (s)
22323 "Is S an ID created by UUIDGEN?"
22324 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22326 (defun org-in-src-block-p (&optional inside)
22327 "Whether point is in a code source block.
22328 When INSIDE is non-nil, don't consider we are within a src block
22329 when point is at #+BEGIN_SRC or #+END_SRC."
22330 (let ((case-fold-search t))
22331 (or (and (eq (get-char-property (point) 'src-block) t))
22332 (and (not inside)
22333 (save-match-data
22334 (save-excursion
22335 (beginning-of-line)
22336 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22338 (defun org-context ()
22339 "Return a list of contexts of the current cursor position.
22340 If several contexts apply, all are returned.
22341 Each context entry is a list with a symbol naming the context, and
22342 two positions indicating start and end of the context. Possible
22343 contexts are:
22345 :headline anywhere in a headline
22346 :headline-stars on the leading stars in a headline
22347 :todo-keyword on a TODO keyword (including DONE) in a headline
22348 :tags on the TAGS in a headline
22349 :priority on the priority cookie in a headline
22350 :item on the first line of a plain list item
22351 :item-bullet on the bullet/number of a plain list item
22352 :checkbox on the checkbox in a plain list item
22353 :table in an org-mode table
22354 :table-special on a special filed in a table
22355 :table-table in a table.el table
22356 :clocktable in a clocktable
22357 :src-block in a source block
22358 :link on a hyperlink
22359 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22360 :target on a <<target>>
22361 :radio-target on a <<<radio-target>>>
22362 :latex-fragment on a LaTeX fragment
22363 :latex-preview on a LaTeX fragment with overlaid preview image
22365 This function expects the position to be visible because it uses font-lock
22366 faces as a help to recognize the following contexts: :table-special, :link,
22367 and :keyword."
22368 (let* ((f (get-text-property (point) 'face))
22369 (faces (if (listp f) f (list f)))
22370 (case-fold-search t)
22371 (p (point)) clist o)
22372 ;; First the large context
22373 (cond
22374 ((org-at-heading-p t)
22375 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22376 (when (progn
22377 (beginning-of-line 1)
22378 (looking-at org-todo-line-tags-regexp))
22379 (push (org-point-in-group p 1 :headline-stars) clist)
22380 (push (org-point-in-group p 2 :todo-keyword) clist)
22381 (push (org-point-in-group p 4 :tags) clist))
22382 (goto-char p)
22383 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22384 (when (looking-at "\\[#[A-Z0-9]\\]")
22385 (push (org-point-in-group p 0 :priority) clist)))
22387 ((org-at-item-p)
22388 (push (org-point-in-group p 2 :item-bullet) clist)
22389 (push (list :item (point-at-bol)
22390 (save-excursion (org-end-of-item) (point)))
22391 clist)
22392 (and (org-at-item-checkbox-p)
22393 (push (org-point-in-group p 0 :checkbox) clist)))
22395 ((org-at-table-p)
22396 (push (list :table (org-table-begin) (org-table-end)) clist)
22397 (when (memq 'org-formula faces)
22398 (push (list :table-special
22399 (previous-single-property-change p 'face)
22400 (next-single-property-change p 'face)) clist)))
22401 ((org-at-table-p 'any)
22402 (push (list :table-table) clist)))
22403 (goto-char p)
22405 (let ((case-fold-search t))
22406 ;; New the "medium" contexts: clocktables, source blocks
22407 (cond ((org-in-clocktable-p)
22408 (push (list :clocktable
22409 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22410 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22411 (match-beginning 1))
22412 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22413 (match-end 0))) clist))
22414 ((org-in-src-block-p)
22415 (push (list :src-block
22416 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22417 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22418 (match-beginning 1))
22419 (and (search-forward "#+END_SRC" nil t)
22420 (match-beginning 0))) clist))))
22421 (goto-char p)
22423 ;; Now the small context
22424 (cond
22425 ((org-at-timestamp-p)
22426 (push (org-point-in-group p 0 :timestamp) clist))
22427 ((memq 'org-link faces)
22428 (push (list :link
22429 (previous-single-property-change p 'face)
22430 (next-single-property-change p 'face)) clist))
22431 ((memq 'org-special-keyword faces)
22432 (push (list :keyword
22433 (previous-single-property-change p 'face)
22434 (next-single-property-change p 'face)) clist))
22435 ((org-at-target-p)
22436 (push (org-point-in-group p 0 :target) clist)
22437 (goto-char (1- (match-beginning 0)))
22438 (when (looking-at org-radio-target-regexp)
22439 (push (org-point-in-group p 0 :radio-target) clist))
22440 (goto-char p))
22441 ((setq o (cl-some
22442 (lambda (o)
22443 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22445 (overlays-at (point))))
22446 (push (list :latex-fragment
22447 (overlay-start o) (overlay-end o)) clist)
22448 (push (list :latex-preview
22449 (overlay-start o) (overlay-end o)) clist))
22450 ((org-inside-LaTeX-fragment-p)
22451 ;; FIXME: positions wrong.
22452 (push (list :latex-fragment (point) (point)) clist)))
22454 (setq clist (nreverse (delq nil clist)))
22455 clist))
22457 (defun org-in-regexp (regexp &optional nlines visually)
22458 "Check if point is inside a match of REGEXP.
22460 Normally only the current line is checked, but you can include
22461 NLINES extra lines around point into the search. If VISUALLY is
22462 set, require that the cursor is not after the match but really
22463 on, so that the block visually is on the match.
22465 Return nil or a cons cell (BEG . END) where BEG and END are,
22466 respectively, the positions at the beginning and the end of the
22467 match."
22468 (catch :exit
22469 (let ((pos (point))
22470 (eol (line-end-position (if nlines (1+ nlines) 1))))
22471 (save-excursion
22472 (beginning-of-line (- 1 (or nlines 0)))
22473 (while (and (re-search-forward regexp eol t)
22474 (<= (match-beginning 0) pos))
22475 (let ((end (match-end 0)))
22476 (when (or (> end pos) (and (= end pos) (not visually)))
22477 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22479 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22480 "Non-nil when point is between matches of START-RE and END-RE.
22482 Also return a non-nil value when point is on one of the matches.
22484 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22485 buffer positions. Default values are the positions of headlines
22486 surrounding the point.
22488 The functions returns a cons cell whose car (resp. cdr) is the
22489 position before START-RE (resp. after END-RE)."
22490 (save-match-data
22491 (let ((pos (point))
22492 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22493 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22494 beg end)
22495 (save-excursion
22496 ;; Point is on a block when on START-RE or if START-RE can be
22497 ;; found before it...
22498 (and (or (org-in-regexp start-re)
22499 (re-search-backward start-re limit-up t))
22500 (setq beg (match-beginning 0))
22501 ;; ... and END-RE after it...
22502 (goto-char (match-end 0))
22503 (re-search-forward end-re limit-down t)
22504 (> (setq end (match-end 0)) pos)
22505 ;; ... without another START-RE in-between.
22506 (goto-char (match-beginning 0))
22507 (not (re-search-backward start-re (1+ beg) t))
22508 ;; Return value.
22509 (cons beg end))))))
22511 (defun org-in-block-p (names)
22512 "Non-nil when point belongs to a block whose name belongs to NAMES.
22514 NAMES is a list of strings containing names of blocks.
22516 Return first block name matched, or nil. Beware that in case of
22517 nested blocks, the returned name may not belong to the closest
22518 block from point."
22519 (save-match-data
22520 (catch 'exit
22521 (let ((case-fold-search t)
22522 (lim-up (save-excursion (outline-previous-heading)))
22523 (lim-down (save-excursion (outline-next-heading))))
22524 (dolist (name names)
22525 (let ((n (regexp-quote name)))
22526 (when (org-between-regexps-p
22527 (concat "^[ \t]*#\\+begin_" n)
22528 (concat "^[ \t]*#\\+end_" n)
22529 lim-up lim-down)
22530 (throw 'exit n)))))
22531 nil)))
22533 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22534 "Call `multi-occur' with buffers for all agenda files."
22535 (interactive "sOrg-files matching: ")
22536 (let* ((files (org-agenda-files))
22537 (tnames (mapcar #'file-truename files))
22538 (extra org-agenda-text-search-extra-files))
22539 (when (eq (car extra) 'agenda-archives)
22540 (setq extra (cdr extra))
22541 (setq files (org-add-archive-files files)))
22542 (dolist (f extra)
22543 (unless (member (file-truename f) tnames)
22544 (unless (member f files) (setq files (append files (list f))))
22545 (setq tnames (append tnames (list (file-truename f))))))
22546 (multi-occur
22547 (mapcar (lambda (x)
22548 (with-current-buffer
22549 ;; FIXME: Why not just (find-file-noselect x)?
22550 ;; Is it to avoid the "revert buffer" prompt?
22551 (or (get-file-buffer x) (find-file-noselect x))
22552 (widen)
22553 (current-buffer)))
22554 files)
22555 regexp)))
22557 (add-hook 'occur-mode-find-occurrence-hook
22558 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22560 (defun org-occur-link-in-agenda-files ()
22561 "Create a link and search for it in the agendas.
22562 The link is not stored in `org-stored-links', it is just created
22563 for the search purpose."
22564 (interactive)
22565 (let ((link (condition-case nil
22566 (org-store-link nil)
22567 (error "Unable to create a link to here"))))
22568 (org-occur-in-agenda-files (regexp-quote link))))
22570 (defun org-reverse-string (string)
22571 "Return the reverse of STRING."
22572 (apply 'string (reverse (string-to-list string))))
22574 ;; defsubst org-uniquify must be defined before first use
22576 (defun org-uniquify-alist (alist)
22577 "Merge elements of ALIST with the same key.
22579 For example, in this alist:
22581 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22582 => \\='((a 1 3) (b 2))
22584 merge (a 1) and (a 3) into (a 1 3).
22586 The function returns the new ALIST."
22587 (let (rtn)
22588 (dolist (e alist rtn)
22589 (let (n)
22590 (if (not (assoc (car e) rtn))
22591 (push e rtn)
22592 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22593 (setq rtn (assq-delete-all (car e) rtn))
22594 (push n rtn))))))
22596 (defun org-delete-all (elts list)
22597 "Remove all elements in ELTS from LIST.
22598 Comparison is done with `equal'. It is a destructive operation
22599 that may remove elements by altering the list structure."
22600 (while elts
22601 (setq list (delete (pop elts) list)))
22602 list)
22604 (defun org-back-over-empty-lines ()
22605 "Move backwards over whitespace, to the beginning of the first empty line.
22606 Returns the number of empty lines passed."
22607 (let ((pos (point)))
22608 (if (cdr (assoc 'heading org-blank-before-new-entry))
22609 (skip-chars-backward " \t\n\r")
22610 (unless (eobp)
22611 (forward-line -1)))
22612 (beginning-of-line 2)
22613 (goto-char (min (point) pos))
22614 (count-lines (point) pos)))
22616 (defun org-skip-whitespace ()
22617 (skip-chars-forward " \t\n\r"))
22619 (defun org-point-in-group (point group &optional context)
22620 "Check if POINT is in match-group GROUP.
22621 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22622 match. If the match group does not exist or point is not inside it,
22623 return nil."
22624 (and (match-beginning group)
22625 (>= point (match-beginning group))
22626 (<= point (match-end group))
22627 (if context
22628 (list context (match-beginning group) (match-end group))
22629 t)))
22631 (defun org-switch-to-buffer-other-window (&rest args)
22632 "Switch to buffer in a second window on the current frame.
22633 In particular, do not allow pop-up frames.
22634 Returns the newly created buffer."
22635 (org-no-popups
22636 (apply 'switch-to-buffer-other-window args)))
22638 (defun org-combine-plists (&rest plists)
22639 "Create a single property list from all plists in PLISTS.
22640 The process starts by copying the first list, and then setting properties
22641 from the other lists. Settings in the last list are the most significant
22642 ones and overrule settings in the other lists."
22643 (let ((rtn (copy-sequence (pop plists)))
22644 p v ls)
22645 (while plists
22646 (setq ls (pop plists))
22647 (while ls
22648 (setq p (pop ls) v (pop ls))
22649 (setq rtn (plist-put rtn p v))))
22650 rtn))
22652 (defun org-replace-escapes (string table)
22653 "Replace %-escapes in STRING with values in TABLE.
22654 TABLE is an association list with keys like \"%a\" and string values.
22655 The sequences in STRING may contain normal field width and padding information,
22656 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22657 so values can contain further %-escapes if they are define later in TABLE."
22658 (let ((tbl (copy-alist table))
22659 (case-fold-search nil)
22660 (pchg 0)
22661 re rpl)
22662 (dolist (e tbl)
22663 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22664 (when (and (cdr e) (string-match re (cdr e)))
22665 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22666 (safe "SREF"))
22667 (add-text-properties 0 3 (list 'sref sref) safe)
22668 (setcdr e (replace-match safe t t (cdr e)))))
22669 (while (string-match re string)
22670 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22671 (cdr e)))
22672 (setq string (replace-match rpl t t string))))
22673 (while (setq pchg (next-property-change pchg string))
22674 (let ((sref (get-text-property pchg 'sref string)))
22675 (when (and sref (string-match "SREF" string pchg))
22676 (setq string (replace-match sref t t string)))))
22677 string))
22679 (defun org-sublist (list start end)
22680 "Return a section of LIST, from START to END.
22682 Counting starts at 1."
22683 (cl-subseq list (1- start) end))
22684 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22686 (defun org-find-base-buffer-visiting (file)
22687 "Like `find-buffer-visiting' but always return the base buffer and
22688 not an indirect buffer."
22689 (let ((buf (or (get-file-buffer file)
22690 (find-buffer-visiting file))))
22691 (if buf
22692 (or (buffer-base-buffer buf) buf)
22693 nil)))
22695 ;;; TODO: Only called once, from ox-odt which should probably use
22696 ;;; org-export-inline-image-p or something.
22697 (defun org-file-image-p (file)
22698 "Return non-nil if FILE is an image."
22699 (save-match-data
22700 (string-match (image-file-name-regexp) file)))
22702 (defun org-get-cursor-date (&optional with-time)
22703 "Return the date at cursor in as a time.
22704 This works in the calendar and in the agenda, anywhere else it just
22705 returns the current time.
22706 If WITH-TIME is non-nil, returns the time of the event at point (in
22707 the agenda) or the current time of the day."
22708 (let (date day defd tp hod mod)
22709 (when with-time
22710 (setq tp (get-text-property (point) 'time))
22711 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22712 (setq hod (string-to-number (match-string 1 tp))
22713 mod (string-to-number (match-string 2 tp))))
22714 (or tp (let ((now (decode-time)))
22715 (setq hod (nth 2 now)
22716 mod (nth 1 now)))))
22717 (cond
22718 ((eq major-mode 'calendar-mode)
22719 (setq date (calendar-cursor-to-date)
22720 defd (encode-time 0 (or mod 0) (or hod 0)
22721 (nth 1 date) (nth 0 date) (nth 2 date))))
22722 ((eq major-mode 'org-agenda-mode)
22723 (setq day (get-text-property (point) 'day))
22724 (when day
22725 (setq date (calendar-gregorian-from-absolute day)
22726 defd (encode-time 0 (or mod 0) (or hod 0)
22727 (nth 1 date) (nth 0 date) (nth 2 date))))))
22728 (or defd (current-time))))
22730 (defun org-mark-subtree (&optional up)
22731 "Mark the current subtree.
22732 This puts point at the start of the current subtree, and mark at
22733 the end. If a numeric prefix UP is given, move up into the
22734 hierarchy of headlines by UP levels before marking the subtree."
22735 (interactive "P")
22736 (org-with-limited-levels
22737 (cond ((org-at-heading-p) (beginning-of-line))
22738 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22739 (t (outline-previous-visible-heading 1))))
22740 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22741 (if (called-interactively-p 'any)
22742 (call-interactively 'org-mark-element)
22743 (org-mark-element)))
22745 (defun org-file-newer-than-p (file time)
22746 "Non-nil if FILE is newer than TIME.
22747 FILE is a filename, as a string, TIME is a list of integers, as
22748 returned by, e.g., `current-time'."
22749 (and (file-exists-p file)
22750 ;; Only compare times up to whole seconds as some file-systems
22751 ;; (e.g. HFS+) do not retain any finer granularity. As
22752 ;; a consequence, make sure we return non-nil when the two
22753 ;; times are equal.
22754 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22755 (cl-subseq time 0 2)))))
22757 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22758 "Compile a SOURCE file using PROCESS.
22760 PROCESS is either a function or a list of shell commands, as
22761 strings. EXT is a file extension, without the leading dot, as
22762 a string. It is used to check if the process actually succeeded.
22764 PROCESS must create a file with the same base name and directory
22765 as SOURCE, but ending with EXT. The function then returns its
22766 filename. Otherwise, it raises an error. The error message can
22767 then be refined by providing string ERR-MSG, which is appended to
22768 the standard message.
22770 If PROCESS is a function, it is called with a single argument:
22771 the SOURCE file.
22773 If it is a list of commands, each of them is called using
22774 `shell-command'. By default, in each command, %b, %f, %F and %o
22775 are replaced with, respectively, SOURCE base name, name, full
22776 name and directory. It is possible, however, to use more
22777 place-holders by specifying them in optional argument SPEC, as an
22778 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22780 When PROCESS is a list of commands, optional argument LOG-BUF can
22781 be set to a buffer or a buffer name. `shell-command' then uses
22782 it for output.
22784 `default-directory' is set to SOURCE directory during the whole
22785 process."
22786 (let* ((source-name (file-name-nondirectory source))
22787 (base-name (file-name-sans-extension source-name))
22788 (full-name (file-truename source))
22789 (out-dir (file-name-directory source))
22790 (time (current-time))
22791 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22792 (save-window-excursion
22793 (let ((default-directory (file-name-directory full-name)))
22794 (pcase process
22795 ((pred functionp) (funcall process (shell-quote-argument source)))
22796 ((pred consp)
22797 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22798 (spec (append spec
22799 `((?b . ,(shell-quote-argument base-name))
22800 (?f . ,(shell-quote-argument source-name))
22801 (?F . ,(shell-quote-argument full-name))
22802 (?o . ,(shell-quote-argument out-dir))))))
22803 (dolist (command process)
22804 (shell-command (format-spec command spec) log-buf))))
22805 (_ (error "No valid command to process %S%s" source err-msg)))))
22806 ;; Check for process failure.
22807 (let ((output (concat out-dir base-name "." ext)))
22808 (unless (org-file-newer-than-p output time)
22809 (error (format "File %S wasn't produced%s" output err-msg)))
22810 output)))
22812 ;;; Indentation
22814 (defun org--get-expected-indentation (element contentsp)
22815 "Expected indentation column for current line, according to ELEMENT.
22816 ELEMENT is an element containing point. CONTENTSP is non-nil
22817 when indentation is to be computed according to contents of
22818 ELEMENT."
22819 (let ((type (org-element-type element))
22820 (start (org-element-property :begin element))
22821 (post-affiliated (org-element-property :post-affiliated element)))
22822 (org-with-wide-buffer
22823 (cond
22824 (contentsp
22825 (cl-case type
22826 ((diary-sexp footnote-definition) 0)
22827 ((headline inlinetask nil)
22828 (if (not org-adapt-indentation) 0
22829 (let ((level (org-current-level)))
22830 (if level (1+ level) 0))))
22831 ((item plain-list) (org-list-item-body-column post-affiliated))
22833 (goto-char start)
22834 (org-get-indentation))))
22835 ((memq type '(headline inlinetask nil))
22836 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22837 (org--get-expected-indentation element t)
22839 ((memq type '(diary-sexp footnote-definition)) 0)
22840 ;; First paragraph of a footnote definition or an item.
22841 ;; Indent like parent.
22842 ((< (line-beginning-position) start)
22843 (org--get-expected-indentation
22844 (org-element-property :parent element) t))
22845 ;; At first line: indent according to previous sibling, if any,
22846 ;; ignoring footnote definitions and inline tasks, or parent's
22847 ;; contents.
22848 ((= (line-beginning-position) start)
22849 (catch 'exit
22850 (while t
22851 (if (= (point-min) start) (throw 'exit 0)
22852 (goto-char (1- start))
22853 (let* ((previous (org-element-at-point))
22854 (parent previous))
22855 (while (and parent (<= (org-element-property :end parent) start))
22856 (setq previous parent
22857 parent (org-element-property :parent parent)))
22858 (cond
22859 ((not previous) (throw 'exit 0))
22860 ((> (org-element-property :end previous) start)
22861 (throw 'exit (org--get-expected-indentation previous t)))
22862 ((memq (org-element-type previous)
22863 '(footnote-definition inlinetask))
22864 (setq start (org-element-property :begin previous)))
22865 (t (goto-char (org-element-property :begin previous))
22866 (throw 'exit
22867 (if (bolp) (org-get-indentation)
22868 ;; At first paragraph in an item or
22869 ;; a footnote definition.
22870 (org--get-expected-indentation
22871 (org-element-property :parent previous) t))))))))))
22872 ;; Otherwise, move to the first non-blank line above.
22874 (beginning-of-line)
22875 (let ((pos (point)))
22876 (skip-chars-backward " \r\t\n")
22877 (cond
22878 ;; Two blank lines end a footnote definition or a plain
22879 ;; list. When we indent an empty line after them, the
22880 ;; containing list or footnote definition is over, so it
22881 ;; qualifies as a previous sibling. Therefore, we indent
22882 ;; like its first line.
22883 ((and (memq type '(footnote-definition plain-list))
22884 (> (count-lines (point) pos) 2))
22885 (goto-char start)
22886 (org-get-indentation))
22887 ;; Line above is the first one of a paragraph at the
22888 ;; beginning of an item or a footnote definition. Indent
22889 ;; like parent.
22890 ((< (line-beginning-position) start)
22891 (org--get-expected-indentation
22892 (org-element-property :parent element) t))
22893 ;; Line above is the beginning of an element, i.e., point
22894 ;; was originally on the blank lines between element's start
22895 ;; and contents.
22896 ((= (line-beginning-position) post-affiliated)
22897 (org--get-expected-indentation element t))
22898 ;; POS is after contents in a greater element. Indent like
22899 ;; the beginning of the element.
22901 ;; As a special case, if point is at the end of a footnote
22902 ;; definition or an item, indent like the very last element
22903 ;; within. If that last element is an item, indent like its
22904 ;; contents.
22905 ((and (not (eq type 'paragraph))
22906 (let ((cend (org-element-property :contents-end element)))
22907 (and cend (<= cend pos))))
22908 (if (memq type '(footnote-definition item plain-list))
22909 (let ((last (org-element-at-point)))
22910 (org--get-expected-indentation
22911 last (eq (org-element-type last) 'item)))
22912 (goto-char start)
22913 (org-get-indentation)))
22914 ;; In any other case, indent like the current line.
22915 (t (org-get-indentation)))))))))
22917 (defun org--align-node-property ()
22918 "Align node property at point.
22919 Alignment is done according to `org-property-format', which see."
22920 (when (save-excursion
22921 (beginning-of-line)
22922 (looking-at org-property-re))
22923 (replace-match
22924 (concat (match-string 4)
22925 (org-trim
22926 (format org-property-format (match-string 1) (match-string 3))))
22927 t t)))
22929 (defun org-indent-line ()
22930 "Indent line depending on context.
22932 Indentation is done according to the following rules:
22934 - Footnote definitions, diary sexps, headlines and inline tasks
22935 have to start at column 0.
22937 - On the very first line of an element, consider, in order, the
22938 next rules until one matches:
22940 1. If there's a sibling element before, ignoring footnote
22941 definitions and inline tasks, indent like its first line.
22943 2. If element has a parent, indent like its contents. More
22944 precisely, if parent is an item, indent after the
22945 description part, if any, or the bullet (see
22946 `org-list-description-max-indent'). Else, indent like
22947 parent's first line.
22949 3. Otherwise, indent relatively to current level, if
22950 `org-adapt-indentation' is non-nil, or to left margin.
22952 - On a blank line at the end of an element, indent according to
22953 the type of the element. More precisely
22955 1. If element is a plain list, an item, or a footnote
22956 definition, indent like the very last element within.
22958 2. If element is a paragraph, indent like its last non blank
22959 line.
22961 3. Otherwise, indent like its very first line.
22963 - In the code part of a source block, use language major mode
22964 to indent current line if `org-src-tab-acts-natively' is
22965 non-nil. If it is nil, do nothing.
22967 - Otherwise, indent like the first non-blank line above.
22969 The function doesn't indent an item as it could break the whole
22970 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22971 \\[org-shiftmetaright].
22973 Also align node properties according to `org-property-format'."
22974 (interactive)
22975 (cond
22976 (orgstruct-is-++
22977 (let ((indent-line-function
22978 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22979 (indent-according-to-mode)))
22980 ((org-at-heading-p) 'noindent)
22982 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22983 (type (org-element-type element)))
22984 (cond ((and (memq type '(plain-list item))
22985 (= (line-beginning-position)
22986 (org-element-property :post-affiliated element)))
22987 'noindent)
22988 ((and (eq type 'src-block)
22989 org-src-tab-acts-natively
22990 (> (line-beginning-position)
22991 (org-element-property :post-affiliated element))
22992 (< (line-beginning-position)
22993 (org-with-wide-buffer
22994 (goto-char (org-element-property :end element))
22995 (skip-chars-backward " \r\t\n")
22996 (line-beginning-position))))
22997 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22999 (let ((column (org--get-expected-indentation element nil)))
23000 ;; Preserve current column.
23001 (if (<= (current-column) (current-indentation))
23002 (indent-line-to column)
23003 (save-excursion (indent-line-to column))))
23004 ;; Align node property. Also preserve current column.
23005 (when (eq type 'node-property)
23006 (let ((column (current-column)))
23007 (org--align-node-property)
23008 (org-move-to-column column)))))))))
23010 (defun org-indent-region (start end)
23011 "Indent each non-blank line in the region.
23012 Called from a program, START and END specify the region to
23013 indent. The function will not indent contents of example blocks,
23014 verse blocks and export blocks as leading white spaces are
23015 assumed to be significant there."
23016 (interactive "r")
23017 (save-excursion
23018 (goto-char start)
23019 (skip-chars-forward " \r\t\n")
23020 (unless (eobp) (beginning-of-line))
23021 (let ((indent-to
23022 (lambda (ind pos)
23023 ;; Set IND as indentation for all lines between point and
23024 ;; POS. Blank lines are ignored. Leave point after POS
23025 ;; once done.
23026 (let ((limit (copy-marker pos)))
23027 (while (< (point) limit)
23028 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23029 (forward-line))
23030 (set-marker limit nil))))
23031 (end (copy-marker end)))
23032 (while (< (point) end)
23033 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23034 (let* ((element (org-element-at-point))
23035 (type (org-element-type element))
23036 (element-end (copy-marker (org-element-property :end element)))
23037 (ind (org--get-expected-indentation element nil)))
23038 (cond
23039 ((or (memq type '(paragraph table table-row))
23040 (not (or (org-element-property :contents-begin element)
23041 (memq type
23042 '(example-block export-block src-block)))))
23043 ;; Elements here are indented as a single block. Also
23044 ;; align node properties.
23045 (when (eq type 'node-property)
23046 (org--align-node-property)
23047 (beginning-of-line))
23048 (funcall indent-to ind (min element-end end)))
23050 ;; Elements in this category consist of three parts:
23051 ;; before the contents, the contents, and after the
23052 ;; contents. The contents are treated specially,
23053 ;; according to the element type, or not indented at
23054 ;; all. Other parts are indented as a single block.
23055 (let* ((post (copy-marker
23056 (org-element-property :post-affiliated element)))
23057 (cbeg
23058 (copy-marker
23059 (cond
23060 ((not (org-element-property :contents-begin element))
23061 ;; Fake contents for source blocks.
23062 (org-with-wide-buffer
23063 (goto-char post)
23064 (forward-line)
23065 (point)))
23066 ((memq type '(footnote-definition item plain-list))
23067 ;; Contents in these elements could start on
23068 ;; the same line as the beginning of the
23069 ;; element. Make sure we start indenting
23070 ;; from the second line.
23071 (org-with-wide-buffer
23072 (goto-char post)
23073 (end-of-line)
23074 (skip-chars-forward " \r\t\n")
23075 (if (eobp) (point) (line-beginning-position))))
23076 (t (org-element-property :contents-begin element)))))
23077 (cend (copy-marker
23078 (or (org-element-property :contents-end element)
23079 ;; Fake contents for source blocks.
23080 (org-with-wide-buffer
23081 (goto-char element-end)
23082 (skip-chars-backward " \r\t\n")
23083 (line-beginning-position)))
23084 t)))
23085 ;; Do not change items indentation individually as it
23086 ;; might break the list as a whole. On the other
23087 ;; hand, when at a plain list, indent it as a whole.
23088 (cond ((eq type 'plain-list)
23089 (let ((offset (- ind (org-get-indentation))))
23090 (unless (zerop offset)
23091 (indent-rigidly (org-element-property :begin element)
23092 (org-element-property :end element)
23093 offset))
23094 (goto-char cbeg)))
23095 ((eq type 'item) (goto-char cbeg))
23096 (t (funcall indent-to ind (min cbeg end))))
23097 (when (< (point) end)
23098 (cl-case type
23099 ((example-block export-block verse-block))
23100 (src-block
23101 ;; In a source block, indent source code
23102 ;; according to language major mode, but only if
23103 ;; `org-src-tab-acts-natively' is non-nil.
23104 (when (and (< (point) end) org-src-tab-acts-natively)
23105 (ignore-errors
23106 (org-babel-do-in-edit-buffer
23107 (indent-region (point-min) (point-max))))))
23108 (t (org-indent-region (point) (min cend end))))
23109 (goto-char (min cend end))
23110 (when (< (point) end)
23111 (funcall indent-to ind (min element-end end))))
23112 (set-marker post nil)
23113 (set-marker cbeg nil)
23114 (set-marker cend nil))))
23115 (set-marker element-end nil))))
23116 (set-marker end nil))))
23118 (defun org-indent-drawer ()
23119 "Indent the drawer at point."
23120 (interactive)
23121 (unless (save-excursion
23122 (beginning-of-line)
23123 (looking-at-p org-drawer-regexp))
23124 (user-error "Not at a drawer"))
23125 (let ((element (org-element-at-point)))
23126 (unless (memq (org-element-type element) '(drawer property-drawer))
23127 (user-error "Not at a drawer"))
23128 (org-with-wide-buffer
23129 (org-indent-region (org-element-property :begin element)
23130 (org-element-property :end element))))
23131 (message "Drawer at point indented"))
23133 (defun org-indent-block ()
23134 "Indent the block at point."
23135 (interactive)
23136 (unless (save-excursion
23137 (beginning-of-line)
23138 (let ((case-fold-search t))
23139 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23140 (user-error "Not at a block"))
23141 (let ((element (org-element-at-point)))
23142 (unless (memq (org-element-type element)
23143 '(comment-block center-block dynamic-block example-block
23144 export-block quote-block special-block
23145 src-block verse-block))
23146 (user-error "Not at a block"))
23147 (org-with-wide-buffer
23148 (org-indent-region (org-element-property :begin element)
23149 (org-element-property :end element))))
23150 (message "Block at point indented"))
23153 ;;; Filling
23155 ;; We use our own fill-paragraph and auto-fill functions.
23157 ;; `org-fill-paragraph' relies on adaptive filling and context
23158 ;; checking. Appropriate `fill-prefix' is computed with
23159 ;; `org-adaptive-fill-function'.
23161 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23162 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23163 ;; `org-adaptive-fill-function' value. Internally,
23164 ;; `org-comment-line-break-function' breaks the line.
23166 ;; `org-setup-filling' installs filling and auto-filling related
23167 ;; variables during `org-mode' initialization.
23169 (defvar org-element-paragraph-separate) ; org-element.el
23170 (defun org-setup-filling ()
23171 (require 'org-element)
23172 ;; Prevent auto-fill from inserting unwanted new items.
23173 (when (boundp 'fill-nobreak-predicate)
23174 (setq-local
23175 fill-nobreak-predicate
23176 (org-uniquify
23177 (append fill-nobreak-predicate
23178 '(org-fill-line-break-nobreak-p
23179 org-fill-paragraph-with-timestamp-nobreak-p)))))
23180 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23181 (setq-local paragraph-start paragraph-ending)
23182 (setq-local paragraph-separate paragraph-ending))
23183 (setq-local fill-paragraph-function 'org-fill-paragraph)
23184 (setq-local auto-fill-inhibit-regexp nil)
23185 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23186 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23187 (setq-local comment-line-break-function 'org-comment-line-break-function))
23189 (defun org-fill-line-break-nobreak-p ()
23190 "Non-nil when a new line at point would create an Org line break."
23191 (save-excursion
23192 (skip-chars-backward "[ \t]")
23193 (skip-chars-backward "\\\\")
23194 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23196 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23197 "Non-nil when a new line at point would split a timestamp."
23198 (and (org-at-timestamp-p t)
23199 (not (looking-at org-ts-regexp-both))))
23201 (declare-function message-in-body-p "message" ())
23202 (defvar orgtbl-line-start-regexp) ; From org-table.el
23203 (defun org-adaptive-fill-function ()
23204 "Compute a fill prefix for the current line.
23205 Return fill prefix, as a string, or nil if current line isn't
23206 meant to be filled. For convenience, if `adaptive-fill-regexp'
23207 matches in paragraphs or comments, use it."
23208 (catch 'exit
23209 (when (derived-mode-p 'message-mode)
23210 (save-excursion
23211 (beginning-of-line)
23212 (cond ((not (message-in-body-p)) (throw 'exit nil))
23213 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23214 ((looking-at message-cite-prefix-regexp)
23215 (throw 'exit (match-string-no-properties 0)))
23216 ((looking-at org-outline-regexp)
23217 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23218 (org-with-wide-buffer
23219 (unless (org-at-heading-p)
23220 (let* ((p (line-beginning-position))
23221 (element (save-excursion
23222 (beginning-of-line)
23223 (org-element-at-point)))
23224 (type (org-element-type element))
23225 (post-affiliated (org-element-property :post-affiliated element)))
23226 (unless (< p post-affiliated)
23227 (cl-case type
23228 (comment
23229 (save-excursion
23230 (beginning-of-line)
23231 (looking-at "[ \t]*")
23232 (concat (match-string 0) "# ")))
23233 (footnote-definition "")
23234 ((item plain-list)
23235 (make-string (org-list-item-body-column post-affiliated) ?\s))
23236 (paragraph
23237 ;; Fill prefix is usually the same as the current line,
23238 ;; unless the paragraph is at the beginning of an item.
23239 (let ((parent (org-element-property :parent element)))
23240 (save-excursion
23241 (beginning-of-line)
23242 (cond ((eq (org-element-type parent) 'item)
23243 (make-string (org-list-item-body-column
23244 (org-element-property :begin parent))
23245 ?\s))
23246 ((and adaptive-fill-regexp
23247 ;; Locally disable
23248 ;; `adaptive-fill-function' to let
23249 ;; `fill-context-prefix' handle
23250 ;; `adaptive-fill-regexp' variable.
23251 (let (adaptive-fill-function)
23252 (fill-context-prefix
23253 post-affiliated
23254 (org-element-property :end element)))))
23255 ((looking-at "[ \t]+") (match-string 0))
23256 (t "")))))
23257 (comment-block
23258 ;; Only fill contents if P is within block boundaries.
23259 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23260 (forward-line)
23261 (point)))
23262 (cend (save-excursion
23263 (goto-char (org-element-property :end element))
23264 (skip-chars-backward " \r\t\n")
23265 (line-beginning-position))))
23266 (when (and (>= p cbeg) (< p cend))
23267 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23268 (match-string 0)
23269 "")))))))))))
23271 (declare-function message-goto-body "message" ())
23272 (defvar message-cite-prefix-regexp) ; From message.el
23273 (defun org-fill-paragraph (&optional justify)
23274 "Fill element at point, when applicable.
23276 This function only applies to comment blocks, comments, example
23277 blocks and paragraphs. Also, as a special case, re-align table
23278 when point is at one.
23280 If JUSTIFY is non-nil (interactively, with prefix argument),
23281 justify as well. If `sentence-end-double-space' is non-nil, then
23282 period followed by one space does not end a sentence, so don't
23283 break a line there. The variable `fill-column' controls the
23284 width for filling.
23286 For convenience, when point is at a plain list, an item or
23287 a footnote definition, try to fill the first paragraph within."
23288 (interactive)
23289 (if (and (derived-mode-p 'message-mode)
23290 (or (not (message-in-body-p))
23291 (save-excursion (move-beginning-of-line 1)
23292 (looking-at message-cite-prefix-regexp))))
23293 ;; First ensure filling is correct in message-mode.
23294 (let ((fill-paragraph-function
23295 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23296 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23297 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23298 (paragraph-separate
23299 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23300 (fill-paragraph nil))
23301 (with-syntax-table org-mode-transpose-word-syntax-table
23302 ;; Move to end of line in order to get the first paragraph
23303 ;; within a plain list or a footnote definition.
23304 (let ((element (save-excursion
23305 (end-of-line)
23306 (or (ignore-errors (org-element-at-point))
23307 (user-error "An element cannot be parsed line %d"
23308 (line-number-at-pos (point)))))))
23309 ;; First check if point is in a blank line at the beginning of
23310 ;; the buffer. In that case, ignore filling.
23311 (cl-case (org-element-type element)
23312 ;; Use major mode filling function is src blocks.
23313 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23314 ;; Align Org tables, leave table.el tables as-is.
23315 (table-row (org-table-align) t)
23316 (table
23317 (when (eq (org-element-property :type element) 'org)
23318 (save-excursion
23319 (goto-char (org-element-property :post-affiliated element))
23320 (org-table-align)))
23322 (paragraph
23323 ;; Paragraphs may contain `line-break' type objects.
23324 (let ((beg (max (point-min)
23325 (org-element-property :contents-begin element)))
23326 (end (min (point-max)
23327 (org-element-property :contents-end element))))
23328 ;; Do nothing if point is at an affiliated keyword.
23329 (if (< (line-end-position) beg) t
23330 (when (derived-mode-p 'message-mode)
23331 ;; In `message-mode', do not fill following citation
23332 ;; in current paragraph nor text before message body.
23333 (let ((body-start (save-excursion (message-goto-body))))
23334 (when body-start (setq beg (max body-start beg))))
23335 (when (save-excursion
23336 (re-search-forward
23337 (concat "^" message-cite-prefix-regexp) end t))
23338 (setq end (match-beginning 0))))
23339 ;; Fill paragraph, taking line breaks into account.
23340 (save-excursion
23341 (goto-char beg)
23342 (let ((cuts (list beg)))
23343 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23344 (when (eq 'line-break
23345 (org-element-type
23346 (save-excursion (backward-char)
23347 (org-element-context))))
23348 (push (point) cuts)))
23349 (dolist (c (delq end cuts))
23350 (fill-region-as-paragraph c end justify)
23351 (setq end c))))
23352 t)))
23353 ;; Contents of `comment-block' type elements should be
23354 ;; filled as plain text, but only if point is within block
23355 ;; markers.
23356 (comment-block
23357 (let* ((case-fold-search t)
23358 (beg (save-excursion
23359 (goto-char (org-element-property :begin element))
23360 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23361 (forward-line)
23362 (point)))
23363 (end (save-excursion
23364 (goto-char (org-element-property :end element))
23365 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23366 (line-beginning-position))))
23367 (if (or (< (point) beg) (> (point) end)) t
23368 (fill-region-as-paragraph
23369 (save-excursion (end-of-line)
23370 (re-search-backward "^[ \t]*$" beg 'move)
23371 (line-beginning-position))
23372 (save-excursion (beginning-of-line)
23373 (re-search-forward "^[ \t]*$" end 'move)
23374 (line-beginning-position))
23375 justify))))
23376 ;; Fill comments.
23377 (comment
23378 (let ((begin (org-element-property :post-affiliated element))
23379 (end (org-element-property :end element)))
23380 (when (and (>= (point) begin) (<= (point) end))
23381 (let ((begin (save-excursion
23382 (end-of-line)
23383 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23384 (progn (forward-line) (point))
23385 begin)))
23386 (end (save-excursion
23387 (end-of-line)
23388 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23389 (1- (line-beginning-position))
23390 (skip-chars-backward " \r\t\n")
23391 (line-end-position)))))
23392 ;; Do not fill comments when at a blank line.
23393 (when (> end begin)
23394 (let ((fill-prefix
23395 (save-excursion
23396 (beginning-of-line)
23397 (looking-at "[ \t]*#")
23398 (let ((comment-prefix (match-string 0)))
23399 (goto-char (match-end 0))
23400 (if (looking-at adaptive-fill-regexp)
23401 (concat comment-prefix (match-string 0))
23402 (concat comment-prefix " "))))))
23403 (save-excursion
23404 (fill-region-as-paragraph begin end justify))))))
23406 ;; Ignore every other element.
23407 (otherwise t))))))
23409 (defun org-auto-fill-function ()
23410 "Auto-fill function."
23411 ;; Check if auto-filling is meaningful.
23412 (let ((fc (current-fill-column)))
23413 (when (and fc (> (current-column) fc))
23414 (let* ((fill-prefix (org-adaptive-fill-function))
23415 ;; Enforce empty fill prefix, if required. Otherwise, it
23416 ;; will be computed again.
23417 (adaptive-fill-mode (not (equal fill-prefix ""))))
23418 (when fill-prefix (do-auto-fill))))))
23420 (defun org-comment-line-break-function (&optional soft)
23421 "Break line at point and indent, continuing comment if within one.
23422 The inserted newline is marked hard if variable
23423 `use-hard-newlines' is true, unless optional argument SOFT is
23424 non-nil."
23425 (if soft (insert-and-inherit ?\n) (newline 1))
23426 (save-excursion (forward-char -1) (delete-horizontal-space))
23427 (delete-horizontal-space)
23428 (indent-to-left-margin)
23429 (insert-before-markers-and-inherit fill-prefix))
23432 ;;; Fixed Width Areas
23434 (defun org-toggle-fixed-width ()
23435 "Toggle fixed-width markup.
23437 Add or remove fixed-width markup on current line, whenever it
23438 makes sense. Return an error otherwise.
23440 If a region is active and if it contains only fixed-width areas
23441 or blank lines, remove all fixed-width markup in it. If the
23442 region contains anything else, convert all non-fixed-width lines
23443 to fixed-width ones.
23445 Blank lines at the end of the region are ignored unless the
23446 region only contains such lines."
23447 (interactive)
23448 (if (not (org-region-active-p))
23449 ;; No region:
23451 ;; Remove fixed width marker only in a fixed-with element.
23453 ;; Add fixed width maker in paragraphs, in blank lines after
23454 ;; elements or at the beginning of a headline or an inlinetask,
23455 ;; and before any one-line elements (e.g., a clock).
23456 (progn
23457 (beginning-of-line)
23458 (let* ((element (org-element-at-point))
23459 (type (org-element-type element)))
23460 (cond
23461 ((and (eq type 'fixed-width)
23462 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23463 (replace-match
23464 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23465 ((and (memq type '(babel-call clock comment diary-sexp headline
23466 horizontal-rule keyword paragraph
23467 planning))
23468 (<= (org-element-property :post-affiliated element) (point)))
23469 (skip-chars-forward " \t")
23470 (insert ": "))
23471 ((and (looking-at-p "[ \t]*$")
23472 (or (eq type 'inlinetask)
23473 (save-excursion
23474 (skip-chars-forward " \r\t\n")
23475 (<= (org-element-property :end element) (point)))))
23476 (delete-region (point) (line-end-position))
23477 (org-indent-line)
23478 (insert ": "))
23479 (t (user-error "Cannot insert a fixed-width line here")))))
23480 ;; Region active.
23481 (let* ((begin (save-excursion
23482 (goto-char (region-beginning))
23483 (line-beginning-position)))
23484 (end (copy-marker
23485 (save-excursion
23486 (goto-char (region-end))
23487 (unless (eolp) (beginning-of-line))
23488 (if (save-excursion (re-search-backward "\\S-" begin t))
23489 (progn (skip-chars-backward " \r\t\n") (point))
23490 (point)))))
23491 (all-fixed-width-p
23492 (catch 'not-all-p
23493 (save-excursion
23494 (goto-char begin)
23495 (skip-chars-forward " \r\t\n")
23496 (when (eobp) (throw 'not-all-p nil))
23497 (while (< (point) end)
23498 (let ((element (org-element-at-point)))
23499 (if (eq (org-element-type element) 'fixed-width)
23500 (goto-char (org-element-property :end element))
23501 (throw 'not-all-p nil))))
23502 t))))
23503 (if all-fixed-width-p
23504 (save-excursion
23505 (goto-char begin)
23506 (while (< (point) end)
23507 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23508 (replace-match
23509 "" nil nil nil
23510 (if (= (line-end-position) (match-end 0)) 0 1)))
23511 (forward-line)))
23512 (let ((min-ind (point-max)))
23513 ;; Find minimum indentation across all lines.
23514 (save-excursion
23515 (goto-char begin)
23516 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23517 (setq min-ind 0)
23518 (catch 'zerop
23519 (while (< (point) end)
23520 (unless (looking-at-p "[ \t]*$")
23521 (let ((ind (org-get-indentation)))
23522 (setq min-ind (min min-ind ind))
23523 (when (zerop ind) (throw 'zerop t))))
23524 (forward-line)))))
23525 ;; Loop over all lines and add fixed-width markup everywhere
23526 ;; but in fixed-width lines.
23527 (save-excursion
23528 (goto-char begin)
23529 (while (< (point) end)
23530 (cond
23531 ((org-at-heading-p)
23532 (insert ": ")
23533 (forward-line)
23534 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23535 (insert ":")
23536 (forward-line)))
23537 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23538 (let* ((element (org-element-at-point))
23539 (element-end (org-element-property :end element)))
23540 (if (eq (org-element-type element) 'fixed-width)
23541 (progn (goto-char element-end)
23542 (skip-chars-backward " \r\t\n")
23543 (forward-line))
23544 (let ((limit (min end element-end)))
23545 (while (< (point) limit)
23546 (org-move-to-column min-ind t)
23547 (insert ": ")
23548 (forward-line))))))
23550 (org-move-to-column min-ind t)
23551 (insert ": ")
23552 (forward-line)))))))
23553 (set-marker end nil))))
23556 ;;; Comments
23558 ;; Org comments syntax is quite complex. It requires the entire line
23559 ;; to be just a comment. Also, even with the right syntax at the
23560 ;; beginning of line, some some elements (i.e. verse-block or
23561 ;; example-block) don't accept comments. Usual Emacs comment commands
23562 ;; cannot cope with those requirements. Therefore, Org replaces them.
23564 ;; Org still relies on `comment-dwim', but cannot trust
23565 ;; `comment-only-p'. So, `comment-region-function' and
23566 ;; `uncomment-region-function' both point
23567 ;; to`org-comment-or-uncomment-region'. Eventually,
23568 ;; `org-insert-comment' takes care of insertion of comments at the
23569 ;; beginning of line.
23571 ;; `org-setup-comments-handling' install comments related variables
23572 ;; during `org-mode' initialization.
23574 (defun org-setup-comments-handling ()
23575 (interactive)
23576 (setq-local comment-use-syntax nil)
23577 (setq-local comment-start "# ")
23578 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23579 (setq-local comment-insert-comment-function 'org-insert-comment)
23580 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23581 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23583 (defun org-insert-comment ()
23584 "Insert an empty comment above current line.
23585 If the line is empty, insert comment at its beginning. When
23586 point is within a source block, comment according to the related
23587 major mode."
23588 (if (let ((element (org-element-at-point)))
23589 (and (eq (org-element-type element) 'src-block)
23590 (< (save-excursion
23591 (goto-char (org-element-property :post-affiliated element))
23592 (line-end-position))
23593 (point))
23594 (> (save-excursion
23595 (goto-char (org-element-property :end element))
23596 (skip-chars-backward " \r\t\n")
23597 (line-beginning-position))
23598 (point))))
23599 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23600 (beginning-of-line)
23601 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23602 (open-line 1))
23603 (org-indent-line)
23604 (insert "# ")))
23606 (defvar comment-empty-lines) ; From newcomment.el.
23607 (defun org-comment-or-uncomment-region (beg end &rest _)
23608 "Comment or uncomment each non-blank line in the region.
23609 Uncomment each non-blank line between BEG and END if it only
23610 contains commented lines. Otherwise, comment them. If region is
23611 strictly within a source block, use appropriate comment syntax."
23612 (if (let ((element (org-element-at-point)))
23613 (and (eq (org-element-type element) 'src-block)
23614 (< (save-excursion
23615 (goto-char (org-element-property :post-affiliated element))
23616 (line-end-position))
23617 beg)
23618 (>= (save-excursion
23619 (goto-char (org-element-property :end element))
23620 (skip-chars-backward " \r\t\n")
23621 (line-beginning-position))
23622 end)))
23623 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23624 (save-restriction
23625 ;; Restrict region
23626 (narrow-to-region (save-excursion (goto-char beg)
23627 (skip-chars-forward " \r\t\n" end)
23628 (line-beginning-position))
23629 (save-excursion (goto-char end)
23630 (skip-chars-backward " \r\t\n" beg)
23631 (line-end-position)))
23632 (let ((uncommentp
23633 ;; UNCOMMENTP is non-nil when every non blank line between
23634 ;; BEG and END is a comment.
23635 (save-excursion
23636 (goto-char (point-min))
23637 (while (and (not (eobp))
23638 (let ((element (org-element-at-point)))
23639 (and (eq (org-element-type element) 'comment)
23640 (goto-char (min (point-max)
23641 (org-element-property
23642 :end element)))))))
23643 (eobp))))
23644 (if uncommentp
23645 ;; Only blank lines and comments in region: uncomment it.
23646 (save-excursion
23647 (goto-char (point-min))
23648 (while (not (eobp))
23649 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23650 (replace-match "" nil nil nil 1))
23651 (forward-line)))
23652 ;; Comment each line in region.
23653 (let ((min-indent (point-max)))
23654 ;; First find the minimum indentation across all lines.
23655 (save-excursion
23656 (goto-char (point-min))
23657 (while (and (not (eobp)) (not (zerop min-indent)))
23658 (unless (looking-at "[ \t]*$")
23659 (setq min-indent (min min-indent (current-indentation))))
23660 (forward-line)))
23661 ;; Then loop over all lines.
23662 (save-excursion
23663 (goto-char (point-min))
23664 (while (not (eobp))
23665 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23666 ;; Don't get fooled by invisible text (e.g. link path)
23667 ;; when moving to column MIN-INDENT.
23668 (let ((buffer-invisibility-spec nil))
23669 (org-move-to-column min-indent t))
23670 (insert comment-start))
23671 (forward-line)))))))))
23673 (defun org-comment-dwim (_arg)
23674 "Call `comment-dwim' within a source edit buffer if needed."
23675 (interactive "*P")
23676 (if (org-in-src-block-p)
23677 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23678 (call-interactively 'comment-dwim)))
23681 ;;; Timestamps API
23683 ;; This section contains tools to operate on timestamp objects, as
23684 ;; returned by, e.g. `org-element-context'.
23686 (defun org-timestamp--to-internal-time (timestamp &optional end)
23687 "Encode TIMESTAMP object into Emacs internal time.
23688 Use end of date range or time range when END is non-nil."
23689 (apply #'encode-time
23690 (cons 0
23691 (mapcar
23692 (lambda (prop) (or (org-element-property prop timestamp) 0))
23693 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23694 '(:minute-start :hour-start :day-start :month-start
23695 :year-start))))))
23697 (defun org-timestamp-has-time-p (timestamp)
23698 "Non-nil when TIMESTAMP has a time specified."
23699 (org-element-property :hour-start timestamp))
23701 (defun org-timestamp-format (timestamp format &optional end utc)
23702 "Format a TIMESTAMP object into a string.
23704 FORMAT is a format specifier to be passed to
23705 `format-time-string'.
23707 When optional argument END is non-nil, use end of date-range or
23708 time-range, if possible.
23710 When optional argument UTC is non-nil, time will be expressed as
23711 Universal Time."
23712 (format-time-string
23713 format (org-timestamp--to-internal-time timestamp end)
23714 (and utc t)))
23716 (defun org-timestamp-split-range (timestamp &optional end)
23717 "Extract a TIMESTAMP object from a date or time range.
23719 END, when non-nil, means extract the end of the range.
23720 Otherwise, extract its start.
23722 Return a new timestamp object."
23723 (let ((type (org-element-property :type timestamp)))
23724 (if (memq type '(active inactive diary)) timestamp
23725 (let ((split-ts (org-element-copy timestamp)))
23726 ;; Set new type.
23727 (org-element-put-property
23728 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23729 ;; Copy start properties over end properties if END is
23730 ;; non-nil. Otherwise, copy end properties over `start' ones.
23731 (let ((p-alist '((:minute-start . :minute-end)
23732 (:hour-start . :hour-end)
23733 (:day-start . :day-end)
23734 (:month-start . :month-end)
23735 (:year-start . :year-end))))
23736 (dolist (p-cell p-alist)
23737 (org-element-put-property
23738 split-ts
23739 (funcall (if end #'car #'cdr) p-cell)
23740 (org-element-property
23741 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23742 ;; Eventually refresh `:raw-value'.
23743 (org-element-put-property split-ts :raw-value nil)
23744 (org-element-put-property
23745 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23747 (defun org-timestamp-translate (timestamp &optional boundary)
23748 "Translate TIMESTAMP object to custom format.
23750 Format string is defined in `org-time-stamp-custom-formats',
23751 which see.
23753 When optional argument BOUNDARY is non-nil, it is either the
23754 symbol `start' or `end'. In this case, only translate the
23755 starting or ending part of TIMESTAMP if it is a date or time
23756 range. Otherwise, translate both parts.
23758 Return timestamp as-is if `org-display-custom-times' is nil or if
23759 it has a `diary' type."
23760 (let ((type (org-element-property :type timestamp)))
23761 (if (or (not org-display-custom-times) (eq type 'diary))
23762 (org-element-interpret-data timestamp)
23763 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23764 org-time-stamp-custom-formats)))
23765 (if (and (not boundary) (memq type '(active-range inactive-range)))
23766 (concat (org-timestamp-format timestamp fmt)
23767 "--"
23768 (org-timestamp-format timestamp fmt t))
23769 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23773 ;;; Other stuff.
23775 (defvar reftex-docstruct-symbol)
23776 (defvar reftex-cite-format)
23777 (defvar org--rds)
23779 (defun org-reftex-citation ()
23780 "Use reftex-citation to insert a citation into the buffer.
23781 This looks for a line like
23783 #+BIBLIOGRAPHY: foo plain option:-d
23785 and derives from it that foo.bib is the bibliography file relevant
23786 for this document. It then installs the necessary environment for RefTeX
23787 to work in this buffer and calls `reftex-citation' to insert a citation
23788 into the buffer.
23790 Export of such citations to both LaTeX and HTML is handled by the contributed
23791 package ox-bibtex by Taru Karttunen."
23792 (interactive)
23793 (let ((reftex-docstruct-symbol 'org--rds)
23794 (reftex-cite-format "\\cite{%l}")
23795 org--rds bib)
23796 (save-excursion
23797 (save-restriction
23798 (widen)
23799 (let ((case-fold-search t)
23800 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23801 (if (not (save-excursion
23802 (or (re-search-forward re nil t)
23803 (re-search-backward re nil t))))
23804 (user-error "No bibliography defined in file")
23805 (setq bib (concat (match-string 1) ".bib")
23806 org--rds (list (list 'bib bib)))))))
23807 (call-interactively 'reftex-citation)))
23809 ;;;; Functions extending outline functionality
23811 (defun org-beginning-of-line (&optional arg)
23812 "Go to the beginning of the current line. If that is invisible, continue
23813 to a visible line beginning. This makes the function of C-a more intuitive.
23814 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23815 first attempt, and only move to after the tags when the cursor is already
23816 beyond the end of the headline."
23817 (interactive "P")
23818 (let ((pos (point))
23819 (special (if (consp org-special-ctrl-a/e)
23820 (car org-special-ctrl-a/e)
23821 org-special-ctrl-a/e))
23822 deactivate-mark refpos)
23823 (call-interactively (if (bound-and-true-p visual-line-mode)
23824 #'beginning-of-visual-line
23825 #'move-beginning-of-line))
23826 (cond
23827 ((or arg (not special)))
23828 ((and (looking-at org-complex-heading-regexp)
23829 (eq (char-after (match-end 1)) ?\s))
23830 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23831 (point-at-eol)))
23832 (goto-char
23833 (if (eq special t)
23834 (cond ((> pos refpos) refpos)
23835 ((= pos (point)) refpos)
23836 (t (point)))
23837 (cond ((> pos (point)) (point))
23838 ((not (eq last-command this-command)) (point))
23839 (t refpos)))))
23840 ((org-at-item-p)
23841 ;; Being at an item and not looking at an the item means point
23842 ;; was previously moved to beginning of a visual line, which
23843 ;; doesn't contain the item. Therefore, do nothing special,
23844 ;; just stay here.
23845 (when (looking-at org-list-full-item-re)
23846 ;; Set special position at first white space character after
23847 ;; bullet, and check-box, if any.
23848 (let ((after-bullet
23849 (let ((box (match-end 3)))
23850 (if (not box) (match-end 1)
23851 (let ((after (char-after box)))
23852 (if (and after (= after ? )) (1+ box) box))))))
23853 ;; Special case: Move point to special position when
23854 ;; currently after it or at beginning of line.
23855 (if (eq special t)
23856 (when (or (> pos after-bullet) (= (point) pos))
23857 (goto-char after-bullet))
23858 ;; Reversed case: Move point to special position when
23859 ;; point was already at beginning of line and command is
23860 ;; repeated.
23861 (when (and (= (point) pos) (eq last-command this-command))
23862 (goto-char after-bullet))))))))
23863 (setq disable-point-adjustment
23864 (or (not (invisible-p (point)))
23865 (not (invisible-p (max (point-min) (1- (point))))))))
23867 (defun org-end-of-line (&optional arg)
23868 "Go to the end of the line.
23869 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23870 tags on the first attempt, and only move to after the tags when
23871 the cursor is already beyond the end of the headline."
23872 (interactive "P")
23873 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23874 org-special-ctrl-a/e))
23875 (move-fun (cond ((bound-and-true-p visual-line-mode)
23876 'end-of-visual-line)
23877 ((fboundp 'move-end-of-line) 'move-end-of-line)
23878 (t 'end-of-line)))
23879 deactivate-mark)
23880 (if (or (not special) arg) (call-interactively move-fun)
23881 (let* ((element (save-excursion (beginning-of-line)
23882 (org-element-at-point)))
23883 (type (org-element-type element)))
23884 (cond
23885 ((memq type '(headline inlinetask))
23886 (let ((pos (point)))
23887 (beginning-of-line 1)
23888 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23889 (if (eq special t)
23890 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23891 (goto-char (match-beginning 1))
23892 (goto-char (match-end 0)))
23893 (if (or (< pos (match-end 0))
23894 (not (eq this-command last-command)))
23895 (goto-char (match-end 0))
23896 (goto-char (match-beginning 1))))
23897 (call-interactively move-fun))))
23898 ((outline-invisible-p (line-end-position))
23899 ;; If element is hidden, `move-end-of-line' would put point
23900 ;; after it. Use `end-of-line' to stay on current line.
23901 (call-interactively 'end-of-line))
23902 (t (call-interactively move-fun))))))
23903 (setq disable-point-adjustment
23904 (or (not (invisible-p (point)))
23905 (not (invisible-p (max (point-min) (1- (point))))))))
23907 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23908 (define-key org-mode-map "\C-e" 'org-end-of-line)
23910 (defun org-backward-sentence (&optional _arg)
23911 "Go to beginning of sentence, or beginning of table field.
23912 This will call `backward-sentence' or `org-table-beginning-of-field',
23913 depending on context."
23914 (interactive)
23915 (let* ((element (org-element-at-point))
23916 (contents-begin (org-element-property :contents-begin element))
23917 (table (org-element-lineage element '(table) t)))
23918 (if (and table
23919 (> (point) contents-begin)
23920 (<= (point) (org-element-property :contents-end table)))
23921 (call-interactively #'org-table-beginning-of-field)
23922 (save-restriction
23923 (when (and contents-begin
23924 (< (point-min) contents-begin)
23925 (> (point) contents-begin))
23926 (narrow-to-region contents-begin
23927 (org-element-property :contents-end element)))
23928 (call-interactively #'backward-sentence)))))
23930 (defun org-forward-sentence (&optional _arg)
23931 "Go to end of sentence, or end of table field.
23932 This will call `forward-sentence' or `org-table-end-of-field',
23933 depending on context."
23934 (interactive)
23935 (let* ((element (org-element-at-point))
23936 (contents-end (org-element-property :contents-end element))
23937 (table (org-element-lineage element '(table) t)))
23938 (if (and table
23939 (>= (point) (org-element-property :contents-begin table))
23940 (< (point) contents-end))
23941 (call-interactively #'org-table-end-of-field)
23942 (save-restriction
23943 (when (and contents-end
23944 (> (point-max) contents-end)
23945 ;; Skip blank lines between elements.
23946 (< (org-element-property :end element)
23947 (save-excursion (goto-char contents-end)
23948 (skip-chars-forward " \r\t\n"))))
23949 (narrow-to-region (org-element-property :contents-begin element)
23950 contents-end))
23951 (call-interactively #'forward-sentence)))))
23953 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23954 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23956 (defun org-kill-line (&optional _arg)
23957 "Kill line, to tags or end of line."
23958 (interactive)
23959 (cond
23960 ((or (not org-special-ctrl-k)
23961 (bolp)
23962 (not (org-at-heading-p)))
23963 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23964 org-ctrl-k-protect-subtree
23965 (or (eq org-ctrl-k-protect-subtree 'error)
23966 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23967 (user-error "C-k aborted as it would kill a hidden subtree"))
23968 (call-interactively
23969 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23970 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23971 (kill-region (point) (match-beginning 1))
23972 (org-set-tags nil t))
23973 (t (kill-region (point) (point-at-eol)))))
23975 (define-key org-mode-map "\C-k" 'org-kill-line)
23977 (defun org-yank (&optional arg)
23978 "Yank. If the kill is a subtree, treat it specially.
23979 This command will look at the current kill and check if is a single
23980 subtree, or a series of subtrees[1]. If it passes the test, and if the
23981 cursor is at the beginning of a line or after the stars of a currently
23982 empty headline, then the yank is handled specially. How exactly depends
23983 on the value of the following variables.
23985 `org-yank-folded-subtrees'
23986 By default, this variable is non-nil, which results in subtree(s)
23987 being folded after insertion, but only if doing so would now
23988 swallow text after the yanked text.
23990 `org-yank-adjusted-subtrees'
23991 When non-nil (the default value is nil), the subtree will be
23992 promoted or demoted in order to fit into the local outline tree
23993 structure, which means that the level will be adjusted so that it
23994 becomes the smaller one of the two *visible* surrounding headings.
23996 Any prefix to this command will cause `yank' to be called directly with
23997 no special treatment. In particular, a simple \\[universal-argument] prefix \
23998 will just
23999 plainly yank the text as it is.
24001 \[1] The test checks if the first non-white line is a heading
24002 and if there are no other headings with fewer stars."
24003 (interactive "P")
24004 (org-yank-generic 'yank arg))
24006 (defun org-yank-generic (command arg)
24007 "Perform some yank-like command.
24009 This function implements the behavior described in the `org-yank'
24010 documentation. However, it has been generalized to work for any
24011 interactive command with similar behavior."
24013 ;; pretend to be command COMMAND
24014 (setq this-command command)
24016 (if arg
24017 (call-interactively command)
24019 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24020 (and (org-kill-is-subtree-p)
24021 (or (bolp)
24022 (and (looking-at "[ \t]*$")
24023 (string-match
24024 "\\`\\*+\\'"
24025 (buffer-substring (point-at-bol) (point)))))))
24026 swallowp)
24027 (cond
24028 ((and subtreep org-yank-folded-subtrees)
24029 (let ((beg (point))
24030 end)
24031 (if (and subtreep org-yank-adjusted-subtrees)
24032 (org-paste-subtree nil nil 'for-yank)
24033 (call-interactively command))
24035 (setq end (point))
24036 (goto-char beg)
24037 (when (and (bolp) subtreep
24038 (not (setq swallowp
24039 (org-yank-folding-would-swallow-text beg end))))
24040 (org-with-limited-levels
24041 (or (looking-at org-outline-regexp)
24042 (re-search-forward org-outline-regexp-bol end t))
24043 (while (and (< (point) end) (looking-at org-outline-regexp))
24044 (outline-hide-subtree)
24045 (org-cycle-show-empty-lines 'folded)
24046 (condition-case nil
24047 (outline-forward-same-level 1)
24048 (error (goto-char end))))))
24049 (when swallowp
24050 (message
24051 "Inserted text not folded because that would swallow text"))
24053 (goto-char end)
24054 (skip-chars-forward " \t\n\r")
24055 (beginning-of-line 1)
24056 (push-mark beg 'nomsg)))
24057 ((and subtreep org-yank-adjusted-subtrees)
24058 (let ((beg (point-at-bol)))
24059 (org-paste-subtree nil nil 'for-yank)
24060 (push-mark beg 'nomsg)))
24062 (call-interactively command))))))
24064 (defun org-yank-folding-would-swallow-text (beg end)
24065 "Would hide-subtree at BEG swallow any text after END?"
24066 (let (level)
24067 (org-with-limited-levels
24068 (save-excursion
24069 (goto-char beg)
24070 (when (or (looking-at org-outline-regexp)
24071 (re-search-forward org-outline-regexp-bol end t))
24072 (setq level (org-outline-level)))
24073 (goto-char end)
24074 (skip-chars-forward " \t\r\n\v\f")
24075 (not (or (eobp)
24076 (and (bolp) (looking-at-p org-outline-regexp)
24077 (<= (org-outline-level) level))))))))
24079 (define-key org-mode-map "\C-y" 'org-yank)
24081 (defun org-truely-invisible-p ()
24082 "Check if point is at a character currently not visible.
24083 This version does not only check the character property, but also
24084 `visible-mode'."
24085 ;; Early versions of noutline don't have `outline-invisible-p'.
24086 (unless (bound-and-true-p visible-mode)
24087 (outline-invisible-p)))
24089 (defun org-invisible-p2 ()
24090 "Check if point is at a character currently not visible."
24091 (save-excursion
24092 (when (and (eolp) (not (bobp))) (backward-char 1))
24093 ;; Early versions of noutline don't have `outline-invisible-p'.
24094 (outline-invisible-p)))
24096 (defun org-back-to-heading (&optional invisible-ok)
24097 "Call `outline-back-to-heading', but provide a better error message."
24098 (condition-case nil
24099 (outline-back-to-heading invisible-ok)
24100 (error (error "Before first headline at position %d in buffer %s"
24101 (point) (current-buffer)))))
24103 (defun org-before-first-heading-p ()
24104 "Before first heading?"
24105 (save-excursion
24106 (end-of-line)
24107 (null (re-search-backward org-outline-regexp-bol nil t))))
24109 (defun org-at-heading-p (&optional ignored)
24110 (outline-on-heading-p t))
24112 (defun org-in-commented-heading-p (&optional no-inheritance)
24113 "Non-nil if point is under a commented heading.
24114 This function also checks ancestors of the current headline,
24115 unless optional argument NO-INHERITANCE is non-nil."
24116 (cond
24117 ((org-before-first-heading-p) nil)
24118 ((let ((headline (nth 4 (org-heading-components))))
24119 (and headline
24120 (let ((case-fold-search nil))
24121 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24122 headline)))))
24123 (no-inheritance nil)
24125 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24127 (defun org-at-comment-p nil
24128 "Is cursor in a commented line?"
24129 (save-excursion
24130 (save-match-data
24131 (beginning-of-line)
24132 (looking-at "^[ \t]*# "))))
24134 (defun org-at-drawer-p nil
24135 "Is cursor at a drawer keyword?"
24136 (save-excursion
24137 (move-beginning-of-line 1)
24138 (looking-at org-drawer-regexp)))
24140 (defun org-at-block-p nil
24141 "Is cursor at a block keyword?"
24142 (save-excursion
24143 (move-beginning-of-line 1)
24144 (looking-at org-block-regexp)))
24146 (defun org-point-at-end-of-empty-headline ()
24147 "If point is at the end of an empty headline, return t, else nil.
24148 If the heading only contains a TODO keyword, it is still still considered
24149 empty."
24150 (and (looking-at "[ \t]*$")
24151 (when org-todo-line-regexp
24152 (save-excursion
24153 (beginning-of-line 1)
24154 (let ((case-fold-search nil))
24155 (looking-at org-todo-line-regexp)
24156 (string= (match-string 3) ""))))))
24158 (defun org-at-heading-or-item-p ()
24159 (or (org-at-heading-p) (org-at-item-p)))
24161 (defun org-at-target-p ()
24162 (or (org-in-regexp org-radio-target-regexp)
24163 (org-in-regexp org-target-regexp)))
24164 ;; Compatibility alias with Org versions < 7.8.03
24165 (defalias 'org-on-target-p 'org-at-target-p)
24167 (defun org-up-heading-all (arg)
24168 "Move to the heading line of which the present line is a subheading.
24169 This function considers both visible and invisible heading lines.
24170 With argument, move up ARG levels."
24171 (outline-up-heading arg t))
24173 (defun org-up-heading-safe ()
24174 "Move to the heading line of which the present line is a subheading.
24175 This version will not throw an error. It will return the level of the
24176 headline found, or nil if no higher level is found.
24178 Also, this function will be a lot faster than `outline-up-heading',
24179 because it relies on stars being the outline starters. This can really
24180 make a significant difference in outlines with very many siblings."
24181 (when (ignore-errors (org-back-to-heading t))
24182 (let ((level-up (1- (funcall outline-level))))
24183 (and (> level-up 0)
24184 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24185 (funcall outline-level)))))
24187 (defun org-first-sibling-p ()
24188 "Is this heading the first child of its parents?"
24189 (interactive)
24190 (let ((re org-outline-regexp-bol)
24191 level l)
24192 (unless (org-at-heading-p t)
24193 (user-error "Not at a heading"))
24194 (setq level (funcall outline-level))
24195 (save-excursion
24196 (if (not (re-search-backward re nil t))
24198 (setq l (funcall outline-level))
24199 (< l level)))))
24201 (defun org-goto-sibling (&optional previous)
24202 "Goto the next sibling, even if it is invisible.
24203 When PREVIOUS is set, go to the previous sibling instead. Returns t
24204 when a sibling was found. When none is found, return nil and don't
24205 move point."
24206 (let ((fun (if previous 're-search-backward 're-search-forward))
24207 (pos (point))
24208 (re org-outline-regexp-bol)
24209 level l)
24210 (when (ignore-errors (org-back-to-heading t))
24211 (setq level (funcall outline-level))
24212 (catch 'exit
24213 (or previous (forward-char 1))
24214 (while (funcall fun re nil t)
24215 (setq l (funcall outline-level))
24216 (when (< l level) (goto-char pos) (throw 'exit nil))
24217 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24218 (goto-char pos)
24219 nil))))
24221 (defun org-show-siblings ()
24222 "Show all siblings of the current headline."
24223 (save-excursion
24224 (while (org-goto-sibling) (org-flag-heading nil)))
24225 (save-excursion
24226 (while (org-goto-sibling 'previous)
24227 (org-flag-heading nil))))
24229 (defun org-goto-first-child ()
24230 "Goto the first child, even if it is invisible.
24231 Return t when a child was found. Otherwise don't move point and
24232 return nil."
24233 (let (level (pos (point)) (re org-outline-regexp-bol))
24234 (when (ignore-errors (org-back-to-heading t))
24235 (setq level (outline-level))
24236 (forward-char 1)
24237 (if (and (re-search-forward re nil t) (> (outline-level) level))
24238 (progn (goto-char (match-beginning 0)) t)
24239 (goto-char pos) nil))))
24241 (defun org-show-hidden-entry ()
24242 "Show an entry where even the heading is hidden."
24243 (save-excursion
24244 (org-show-entry)))
24246 (defun org-flag-heading (flag &optional entry)
24247 "Flag the current heading. FLAG non-nil means make invisible.
24248 When ENTRY is non-nil, show the entire entry."
24249 (save-excursion
24250 (org-back-to-heading t)
24251 ;; Check if we should show the entire entry
24252 (if entry
24253 (progn
24254 (org-show-entry)
24255 (save-excursion
24256 (and (outline-next-heading)
24257 (org-flag-heading nil))))
24258 (outline-flag-region (max (point-min) (1- (point)))
24259 (save-excursion (outline-end-of-heading) (point))
24260 flag))))
24262 (defun org-get-next-sibling ()
24263 "Move to next heading of the same level, and return point.
24264 If there is no such heading, return nil.
24265 This is like outline-next-sibling, but invisible headings are ok."
24266 (let ((level (funcall outline-level)))
24267 (outline-next-heading)
24268 (while (and (not (eobp)) (> (funcall outline-level) level))
24269 (outline-next-heading))
24270 (unless (or (eobp) (< (funcall outline-level) level))
24271 (point))))
24273 (defun org-get-last-sibling ()
24274 "Move to previous heading of the same level, and return point.
24275 If there is no such heading, return nil."
24276 (let ((opoint (point))
24277 (level (funcall outline-level)))
24278 (outline-previous-heading)
24279 (when (and (/= (point) opoint) (outline-on-heading-p t))
24280 (while (and (> (funcall outline-level) level)
24281 (not (bobp)))
24282 (outline-previous-heading))
24283 (unless (< (funcall outline-level) level)
24284 (point)))))
24286 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24287 "Goto to the end of a subtree."
24288 ;; This contains an exact copy of the original function, but it uses
24289 ;; `org-back-to-heading', to make it work also in invisible
24290 ;; trees. And is uses an invisible-ok argument.
24291 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24292 ;; Furthermore, when used inside Org, finding the end of a large subtree
24293 ;; with many children and grandchildren etc, this can be much faster
24294 ;; than the outline version.
24295 (org-back-to-heading invisible-ok)
24296 (let ((first t)
24297 (level (funcall outline-level)))
24298 (if (and (derived-mode-p 'org-mode) (< level 1000))
24299 ;; A true heading (not a plain list item), in Org-mode
24300 ;; This means we can easily find the end by looking
24301 ;; only for the right number of stars. Using a regexp to do
24302 ;; this is so much faster than using a Lisp loop.
24303 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24304 (forward-char 1)
24305 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24306 ;; something else, do it the slow way
24307 (while (and (not (eobp))
24308 (or first (> (funcall outline-level) level)))
24309 (setq first nil)
24310 (outline-next-heading)))
24311 (unless to-heading
24312 (when (memq (preceding-char) '(?\n ?\^M))
24313 ;; Go to end of line before heading
24314 (forward-char -1)
24315 (when (memq (preceding-char) '(?\n ?\^M))
24316 ;; leave blank line before heading
24317 (forward-char -1)))))
24318 (point))
24320 (defun org-end-of-meta-data (&optional full)
24321 "Skip planning line and properties drawer in current entry.
24322 When optional argument FULL is non-nil, also skip empty lines,
24323 clocking lines and regular drawers at the beginning of the
24324 entry."
24325 (org-back-to-heading t)
24326 (forward-line)
24327 (when (looking-at-p org-planning-line-re) (forward-line))
24328 (when (looking-at org-property-drawer-re)
24329 (goto-char (match-end 0))
24330 (forward-line))
24331 (when (and full (not (org-at-heading-p)))
24332 (catch 'exit
24333 (let ((end (save-excursion (outline-next-heading) (point)))
24334 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24335 (while (not (eobp))
24336 (cond ((looking-at-p org-drawer-regexp)
24337 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24338 (forward-line)
24339 (throw 'exit t)))
24340 ((looking-at-p re) (forward-line))
24341 (t (throw 'exit t))))))))
24343 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24344 "Move forward to the ARG'th subheading at same level as this one.
24345 Stop at the first and last subheadings of a superior heading.
24346 Normally this only looks at visible headings, but when INVISIBLE-OK is
24347 non-nil it will also look at invisible ones."
24348 (interactive "p")
24349 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24350 (if (and arg (< arg 0))
24351 (goto-char (point-min))
24352 (outline-next-heading))
24353 (org-at-heading-p)
24354 (let ((level (- (match-end 0) (match-beginning 0) 1))
24355 (f (if (and arg (< arg 0))
24356 're-search-backward
24357 're-search-forward))
24358 (count (if arg (abs arg) 1))
24359 (result (point)))
24360 (while (and (prog1 (> count 0)
24361 (forward-char (if (and arg (< arg 0)) -1 1)))
24362 (funcall f org-outline-regexp-bol nil 'move))
24363 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24364 (cond ((< l level) (setq count 0))
24365 ((and (= l level)
24366 (or invisible-ok
24367 (progn
24368 (goto-char (line-beginning-position))
24369 (not (outline-invisible-p)))))
24370 (setq count (1- count))
24371 (when (eq l level)
24372 (setq result (point)))))))
24373 (goto-char result))
24374 (beginning-of-line 1)))
24376 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24377 "Move backward to the ARG'th subheading at same level as this one.
24378 Stop at the first and last subheadings of a superior heading."
24379 (interactive "p")
24380 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24382 (defun org-next-visible-heading (arg)
24383 "Move to the next visible heading.
24385 This function wraps `outline-next-visible-heading' with
24386 `org-with-limited-levels' in order to skip over inline tasks and
24387 respect customization of `org-odd-levels-only'."
24388 (interactive "p")
24389 (org-with-limited-levels
24390 (outline-next-visible-heading arg)))
24392 (defun org-previous-visible-heading (arg)
24393 "Move to the previous visible heading.
24395 This function wraps `outline-previous-visible-heading' with
24396 `org-with-limited-levels' in order to skip over inline tasks and
24397 respect customization of `org-odd-levels-only'."
24398 (interactive "p")
24399 (org-with-limited-levels
24400 (outline-previous-visible-heading arg)))
24402 (defun org-next-block (arg &optional backward block-regexp)
24403 "Jump to the next block.
24405 With a prefix argument ARG, jump forward ARG many blocks.
24407 When BACKWARD is non-nil, jump to the previous block.
24409 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24410 Match data is set according to this regexp when the function
24411 returns.
24413 Return point at beginning of the opening line of found block.
24414 Throw an error if no block is found."
24415 (interactive "p")
24416 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24417 (case-fold-search t)
24418 (search-fn (if backward #'re-search-backward #'re-search-forward))
24419 (count (or arg 1))
24420 (origin (point))
24421 last-element)
24422 (if backward (beginning-of-line) (end-of-line))
24423 (while (and (> count 0) (funcall search-fn re nil t))
24424 (let ((element (save-excursion
24425 (goto-char (match-beginning 0))
24426 (save-match-data (org-element-at-point)))))
24427 (when (and (memq (org-element-type element)
24428 '(center-block comment-block dynamic-block
24429 example-block export-block quote-block
24430 special-block src-block verse-block))
24431 (<= (match-beginning 0)
24432 (org-element-property :post-affiliated element)))
24433 (setq last-element element)
24434 (cl-decf count))))
24435 (if (= count 0)
24436 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24437 (save-match-data (org-show-context)))
24438 (goto-char origin)
24439 (user-error "No %s code blocks" (if backward "previous" "further")))))
24441 (defun org-previous-block (arg &optional block-regexp)
24442 "Jump to the previous block.
24443 With a prefix argument ARG, jump backward ARG many source blocks.
24444 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24445 (interactive "p")
24446 (org-next-block arg t block-regexp))
24448 (defun org-forward-paragraph ()
24449 "Move forward to beginning of next paragraph or equivalent.
24451 The function moves point to the beginning of the next visible
24452 structural element, which can be a paragraph, a table, a list
24453 item, etc. It also provides some special moves for convenience:
24455 - On an affiliated keyword, jump to the beginning of the
24456 relative element.
24457 - On an item or a footnote definition, move to the second
24458 element inside, if any.
24459 - On a table or a property drawer, jump after it.
24460 - On a verse or source block, stop after blank lines."
24461 (interactive)
24462 (when (eobp) (user-error "Cannot move further down"))
24463 (let* ((deactivate-mark nil)
24464 (element (org-element-at-point))
24465 (type (org-element-type element))
24466 (post-affiliated (org-element-property :post-affiliated element))
24467 (contents-begin (org-element-property :contents-begin element))
24468 (contents-end (org-element-property :contents-end element))
24469 (end (let ((end (org-element-property :end element)) (parent element))
24470 (while (and (setq parent (org-element-property :parent parent))
24471 (= (org-element-property :contents-end parent) end))
24472 (setq end (org-element-property :end parent)))
24473 end)))
24474 (cond ((not element)
24475 (skip-chars-forward " \r\t\n")
24476 (or (eobp) (beginning-of-line)))
24477 ;; On affiliated keywords, move to element's beginning.
24478 ((< (point) post-affiliated)
24479 (goto-char post-affiliated))
24480 ;; At a table row, move to the end of the table. Similarly,
24481 ;; at a node property, move to the end of the property
24482 ;; drawer.
24483 ((memq type '(node-property table-row))
24484 (goto-char (org-element-property
24485 :end (org-element-property :parent element))))
24486 ((memq type '(property-drawer table)) (goto-char end))
24487 ;; Consider blank lines as separators in verse and source
24488 ;; blocks to ease editing.
24489 ((memq type '(src-block verse-block))
24490 (when (eq type 'src-block)
24491 (setq contents-end
24492 (save-excursion (goto-char end)
24493 (skip-chars-backward " \r\t\n")
24494 (line-beginning-position))))
24495 (beginning-of-line)
24496 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24497 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24498 (goto-char end)
24499 (skip-chars-forward " \r\t\n")
24500 (if (= (point) contents-end) (goto-char end)
24501 (beginning-of-line))))
24502 ;; With no contents, just skip element.
24503 ((not contents-begin) (goto-char end))
24504 ;; If contents are invisible, skip the element altogether.
24505 ((outline-invisible-p (line-end-position))
24506 (cl-case type
24507 (headline
24508 (org-with-limited-levels (outline-next-visible-heading 1)))
24509 ;; At a plain list, make sure we move to the next item
24510 ;; instead of skipping the whole list.
24511 (plain-list (forward-char)
24512 (org-forward-paragraph))
24513 (otherwise (goto-char end))))
24514 ((>= (point) contents-end) (goto-char end))
24515 ((>= (point) contents-begin)
24516 ;; This can only happen on paragraphs and plain lists.
24517 (cl-case type
24518 (paragraph (goto-char end))
24519 ;; At a plain list, try to move to second element in
24520 ;; first item, if possible.
24521 (plain-list (end-of-line)
24522 (org-forward-paragraph))))
24523 ;; When contents start on the middle of a line (e.g. in
24524 ;; items and footnote definitions), try to reach first
24525 ;; element starting after current line.
24526 ((> (line-end-position) contents-begin)
24527 (end-of-line)
24528 (org-forward-paragraph))
24529 (t (goto-char contents-begin)))))
24531 (defun org-backward-paragraph ()
24532 "Move backward to start of previous paragraph or equivalent.
24534 The function moves point to the beginning of the current
24535 structural element, which can be a paragraph, a table, a list
24536 item, etc., or to the beginning of the previous visible one if
24537 point is already there. It also provides some special moves for
24538 convenience:
24540 - On an affiliated keyword, jump to the first one.
24541 - On a table or a property drawer, move to its beginning.
24542 - On a verse or source block, stop before blank lines."
24543 (interactive)
24544 (when (bobp) (user-error "Cannot move further up"))
24545 (let* ((deactivate-mark nil)
24546 (element (org-element-at-point))
24547 (type (org-element-type element))
24548 (contents-begin (org-element-property :contents-begin element))
24549 (contents-end (org-element-property :contents-end element))
24550 (post-affiliated (org-element-property :post-affiliated element))
24551 (begin (org-element-property :begin element)))
24552 (cond
24553 ((not element) (goto-char (point-min)))
24554 ((= (point) begin)
24555 (backward-char)
24556 (org-backward-paragraph))
24557 ((<= (point) post-affiliated) (goto-char begin))
24558 ((memq type '(node-property table-row))
24559 (goto-char (org-element-property
24560 :post-affiliated (org-element-property :parent element))))
24561 ((memq type '(property-drawer table)) (goto-char begin))
24562 ((memq type '(src-block verse-block))
24563 (when (eq type 'src-block)
24564 (setq contents-begin
24565 (save-excursion (goto-char begin) (forward-line) (point))))
24566 (if (= (point) contents-begin) (goto-char post-affiliated)
24567 ;; Inside a verse block, see blank lines as paragraph
24568 ;; separators.
24569 (let ((origin (point)))
24570 (skip-chars-backward " \r\t\n" contents-begin)
24571 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24572 (skip-chars-forward " \r\t\n" origin)
24573 (if (= (point) origin) (goto-char contents-begin)
24574 (beginning-of-line))))))
24575 ((not contents-begin) (goto-char (or post-affiliated begin)))
24576 ((eq type 'paragraph)
24577 (goto-char contents-begin)
24578 ;; When at first paragraph in an item or a footnote definition,
24579 ;; move directly to beginning of line.
24580 (let ((parent-contents
24581 (org-element-property
24582 :contents-begin (org-element-property :parent element))))
24583 (when (and parent-contents (= parent-contents contents-begin))
24584 (beginning-of-line))))
24585 ;; At the end of a greater element, move to the beginning of the
24586 ;; last element within.
24587 ((>= (point) contents-end)
24588 (goto-char (1- contents-end))
24589 (org-backward-paragraph))
24590 (t (goto-char (or post-affiliated begin))))
24591 ;; Ensure we never leave point invisible.
24592 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24594 (defun org-forward-element ()
24595 "Move forward by one element.
24596 Move to the next element at the same level, when possible."
24597 (interactive)
24598 (cond ((eobp) (user-error "Cannot move further down"))
24599 ((org-with-limited-levels (org-at-heading-p))
24600 (let ((origin (point)))
24601 (goto-char (org-end-of-subtree nil t))
24602 (unless (org-with-limited-levels (org-at-heading-p))
24603 (goto-char origin)
24604 (user-error "Cannot move further down"))))
24606 (let* ((elem (org-element-at-point))
24607 (end (org-element-property :end elem))
24608 (parent (org-element-property :parent elem)))
24609 (cond ((and parent (= (org-element-property :contents-end parent) end))
24610 (goto-char (org-element-property :end parent)))
24611 ((integer-or-marker-p end) (goto-char end))
24612 (t (message "No element at point")))))))
24614 (defun org-backward-element ()
24615 "Move backward by one element.
24616 Move to the previous element at the same level, when possible."
24617 (interactive)
24618 (cond ((bobp) (user-error "Cannot move further up"))
24619 ((org-with-limited-levels (org-at-heading-p))
24620 ;; At a headline, move to the previous one, if any, or stay
24621 ;; here.
24622 (let ((origin (point)))
24623 (org-with-limited-levels (org-backward-heading-same-level 1))
24624 ;; When current headline has no sibling above, move to its
24625 ;; parent.
24626 (when (= (point) origin)
24627 (or (org-with-limited-levels (org-up-heading-safe))
24628 (progn (goto-char origin)
24629 (user-error "Cannot move further up"))))))
24631 (let* ((elem (org-element-at-point))
24632 (beg (org-element-property :begin elem)))
24633 (cond
24634 ;; Move to beginning of current element if point isn't
24635 ;; there already.
24636 ((null beg) (message "No element at point"))
24637 ((/= (point) beg) (goto-char beg))
24638 (t (goto-char beg)
24639 (skip-chars-backward " \r\t\n")
24640 (unless (bobp)
24641 (let ((prev (org-element-at-point)))
24642 (goto-char (org-element-property :begin prev))
24643 (while (and (setq prev (org-element-property :parent prev))
24644 (<= (org-element-property :end prev) beg))
24645 (goto-char (org-element-property :begin prev)))))))))))
24647 (defun org-up-element ()
24648 "Move to upper element."
24649 (interactive)
24650 (if (org-with-limited-levels (org-at-heading-p))
24651 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24652 (let* ((elem (org-element-at-point))
24653 (parent (org-element-property :parent elem)))
24654 (if parent (goto-char (org-element-property :begin parent))
24655 (if (org-with-limited-levels (org-before-first-heading-p))
24656 (user-error "No surrounding element")
24657 (org-with-limited-levels (org-back-to-heading)))))))
24659 (defvar org-element-greater-elements)
24660 (defun org-down-element ()
24661 "Move to inner element."
24662 (interactive)
24663 (let ((element (org-element-at-point)))
24664 (cond
24665 ((memq (org-element-type element) '(plain-list table))
24666 (goto-char (org-element-property :contents-begin element))
24667 (forward-char))
24668 ((memq (org-element-type element) org-element-greater-elements)
24669 ;; If contents are hidden, first disclose them.
24670 (when (outline-invisible-p (line-end-position)) (org-cycle))
24671 (goto-char (or (org-element-property :contents-begin element)
24672 (user-error "No content for this element"))))
24673 (t (user-error "No inner element")))))
24675 (defun org-drag-element-backward ()
24676 "Move backward element at point."
24677 (interactive)
24678 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24679 (let* ((elem (org-element-at-point))
24680 (prev-elem
24681 (save-excursion
24682 (goto-char (org-element-property :begin elem))
24683 (skip-chars-backward " \r\t\n")
24684 (unless (bobp)
24685 (let* ((beg (org-element-property :begin elem))
24686 (prev (org-element-at-point))
24687 (up prev))
24688 (while (and (setq up (org-element-property :parent up))
24689 (<= (org-element-property :end up) beg))
24690 (setq prev up))
24691 prev)))))
24692 ;; Error out if no previous element or previous element is
24693 ;; a parent of the current one.
24694 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24695 (user-error "Cannot drag element backward")
24696 (let ((pos (point)))
24697 (org-element-swap-A-B prev-elem elem)
24698 (goto-char (+ (org-element-property :begin prev-elem)
24699 (- pos (org-element-property :begin elem)))))))))
24701 (defun org-drag-element-forward ()
24702 "Move forward element at point."
24703 (interactive)
24704 (let* ((pos (point))
24705 (elem (org-element-at-point)))
24706 (when (= (point-max) (org-element-property :end elem))
24707 (user-error "Cannot drag element forward"))
24708 (goto-char (org-element-property :end elem))
24709 (let ((next-elem (org-element-at-point)))
24710 (when (or (org-element-nested-p elem next-elem)
24711 (and (eq (org-element-type next-elem) 'headline)
24712 (not (eq (org-element-type elem) 'headline))))
24713 (goto-char pos)
24714 (user-error "Cannot drag element forward"))
24715 ;; Compute new position of point: it's shifted by NEXT-ELEM
24716 ;; body's length (without final blanks) and by the length of
24717 ;; blanks between ELEM and NEXT-ELEM.
24718 (let ((size-next (- (save-excursion
24719 (goto-char (org-element-property :end next-elem))
24720 (skip-chars-backward " \r\t\n")
24721 (forward-line)
24722 ;; Small correction if buffer doesn't end
24723 ;; with a newline character.
24724 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24725 (org-element-property :begin next-elem)))
24726 (size-blank (- (org-element-property :end elem)
24727 (save-excursion
24728 (goto-char (org-element-property :end elem))
24729 (skip-chars-backward " \r\t\n")
24730 (forward-line)
24731 (point)))))
24732 (org-element-swap-A-B elem next-elem)
24733 (goto-char (+ pos size-next size-blank))))))
24735 (defun org-drag-line-forward (arg)
24736 "Drag the line at point ARG lines forward."
24737 (interactive "p")
24738 (dotimes (_ (abs arg))
24739 (let ((c (current-column)))
24740 (if (< 0 arg)
24741 (progn
24742 (beginning-of-line 2)
24743 (transpose-lines 1)
24744 (beginning-of-line 0))
24745 (transpose-lines 1)
24746 (beginning-of-line -1))
24747 (org-move-to-column c))))
24749 (defun org-drag-line-backward (arg)
24750 "Drag the line at point ARG lines backward."
24751 (interactive "p")
24752 (org-drag-line-forward (- arg)))
24754 (defun org-mark-element ()
24755 "Put point at beginning of this element, mark at end.
24757 Interactively, if this command is repeated or (in Transient Mark
24758 mode) if the mark is active, it marks the next element after the
24759 ones already marked."
24760 (interactive)
24761 (let (deactivate-mark)
24762 (if (and (called-interactively-p 'any)
24763 (or (and (eq last-command this-command) (mark t))
24764 (and transient-mark-mode mark-active)))
24765 (set-mark
24766 (save-excursion
24767 (goto-char (mark))
24768 (goto-char (org-element-property :end (org-element-at-point)))))
24769 (let ((element (org-element-at-point)))
24770 (end-of-line)
24771 (push-mark (org-element-property :end element) t t)
24772 (goto-char (org-element-property :begin element))))))
24774 (defun org-narrow-to-element ()
24775 "Narrow buffer to current element."
24776 (interactive)
24777 (let ((elem (org-element-at-point)))
24778 (cond
24779 ((eq (car elem) 'headline)
24780 (narrow-to-region
24781 (org-element-property :begin elem)
24782 (org-element-property :end elem)))
24783 ((memq (car elem) org-element-greater-elements)
24784 (narrow-to-region
24785 (org-element-property :contents-begin elem)
24786 (org-element-property :contents-end elem)))
24788 (narrow-to-region
24789 (org-element-property :begin elem)
24790 (org-element-property :end elem))))))
24792 (defun org-transpose-element ()
24793 "Transpose current and previous elements, keeping blank lines between.
24794 Point is moved after both elements."
24795 (interactive)
24796 (org-skip-whitespace)
24797 (let ((end (org-element-property :end (org-element-at-point))))
24798 (org-drag-element-backward)
24799 (goto-char end)))
24801 (defun org-unindent-buffer ()
24802 "Un-indent the visible part of the buffer.
24803 Relative indentation (between items, inside blocks, etc.) isn't
24804 modified."
24805 (interactive)
24806 (unless (eq major-mode 'org-mode)
24807 (user-error "Cannot un-indent a buffer not in Org mode"))
24808 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24809 (unindent-tree
24810 (lambda (contents)
24811 (dolist (element (reverse contents))
24812 (if (memq (org-element-type element) '(headline section))
24813 (funcall unindent-tree (org-element-contents element))
24814 (save-excursion
24815 (save-restriction
24816 (narrow-to-region
24817 (org-element-property :begin element)
24818 (org-element-property :end element))
24819 (org-do-remove-indentation))))))))
24820 (funcall unindent-tree (org-element-contents parse-tree))))
24822 (defun org-show-children (&optional level)
24823 "Show all direct subheadings of this heading.
24824 Prefix arg LEVEL is how many levels below the current level
24825 should be shown. Default is enough to cause the following
24826 heading to appear."
24827 (interactive "p")
24828 ;; If `orgstruct-mode' is active, use the slower version.
24829 (if orgstruct-mode (call-interactively #'outline-show-children)
24830 (save-excursion
24831 (org-back-to-heading t)
24832 (let* ((current-level (funcall outline-level))
24833 (max-level (org-get-valid-level
24834 current-level
24835 (if level (prefix-numeric-value level) 1)))
24836 (end (save-excursion (org-end-of-subtree t t)))
24837 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24838 (past-first-child nil)
24839 ;; Make sure to skip inlinetasks.
24840 (re (format regexp-fmt
24841 current-level
24842 (cond
24843 ((not (featurep 'org-inlinetask)) "")
24844 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24846 (t (1- org-inlinetask-min-level))))))
24847 ;; Display parent heading.
24848 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24849 (forward-line)
24850 ;; Display children. First child may be deeper than expected
24851 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24852 ;; MAX-LEVEL accordingly.
24853 (while (re-search-forward re end t)
24854 (unless past-first-child
24855 (setq re (format regexp-fmt
24856 current-level
24857 (max (funcall outline-level) max-level)))
24858 (setq past-first-child t))
24859 (outline-flag-region
24860 (line-end-position 0) (line-end-position) nil))))))
24862 (defun org-show-subtree ()
24863 "Show everything after this heading at deeper levels."
24864 (interactive)
24865 (outline-flag-region
24866 (point)
24867 (save-excursion
24868 (org-end-of-subtree t t))
24869 nil))
24871 (defun org-show-entry ()
24872 "Show the body directly following this heading.
24873 Show the heading too, if it is currently invisible."
24874 (interactive)
24875 (save-excursion
24876 (ignore-errors
24877 (org-back-to-heading t)
24878 (outline-flag-region
24879 (max (point-min) (1- (point)))
24880 (save-excursion
24881 (if (re-search-forward
24882 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24883 (match-beginning 1)
24884 (point-max)))
24885 nil)
24886 (org-cycle-hide-drawers 'children))))
24888 (defun org-make-options-regexp (kwds &optional extra)
24889 "Make a regular expression for keyword lines.
24890 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24891 when non-nil, is a regexp matching keywords names."
24892 (concat "^[ \t]*#\\+\\("
24893 (regexp-opt kwds)
24894 (and extra (concat (and kwds "\\|") extra))
24895 "\\):[ \t]*\\(.*\\)"))
24897 ;;;; Integration with and fixes for other packages
24899 ;;; Imenu support
24901 (defvar-local org-imenu-markers nil
24902 "All markers currently used by Imenu.")
24904 (defun org-imenu-new-marker (&optional pos)
24905 "Return a new marker for use by Imenu, and remember the marker."
24906 (let ((m (make-marker)))
24907 (move-marker m (or pos (point)))
24908 (push m org-imenu-markers)
24911 (defun org-imenu-get-tree ()
24912 "Produce the index for Imenu."
24913 (dolist (x org-imenu-markers) (move-marker x nil))
24914 (setq org-imenu-markers nil)
24915 (let* ((case-fold-search nil)
24916 (n org-imenu-depth)
24917 (re (concat "^" (org-get-limited-outline-regexp)))
24918 (subs (make-vector (1+ n) nil))
24919 (last-level 0)
24920 m level head0 head)
24921 (save-excursion
24922 (save-restriction
24923 (widen)
24924 (goto-char (point-max))
24925 (while (re-search-backward re nil t)
24926 (setq level (org-reduced-level (funcall outline-level)))
24927 (when (and (<= level n)
24928 (looking-at org-complex-heading-regexp)
24929 (setq head0 (match-string-no-properties 4)))
24930 (setq head (org-link-display-format head0)
24931 m (org-imenu-new-marker))
24932 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24933 (if (>= level last-level)
24934 (push (cons head m) (aref subs level))
24935 (push (cons head (aref subs (1+ level))) (aref subs level))
24936 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24937 (setq last-level level)))))
24938 (aref subs 1)))
24940 (eval-after-load "imenu"
24941 '(progn
24942 (add-hook 'imenu-after-jump-hook
24943 (lambda ()
24944 (when (derived-mode-p 'org-mode)
24945 (org-show-context 'org-goto))))))
24947 (defun org-link-display-format (s)
24948 "Replace links in string S with their description.
24949 If there is no description, use the link target."
24950 (save-match-data
24951 (replace-regexp-in-string
24952 org-bracket-link-analytic-regexp
24953 (lambda (m)
24954 (if (match-end 5) (match-string 5 m)
24955 (concat (match-string 1 m) (match-string 3 m))))
24956 s nil t)))
24958 (defun org-toggle-link-display ()
24959 "Toggle the literal or descriptive display of links."
24960 (interactive)
24961 (if org-descriptive-links
24962 (progn (org-remove-from-invisibility-spec '(org-link))
24963 (org-restart-font-lock)
24964 (setq org-descriptive-links nil))
24965 (progn (add-to-invisibility-spec '(org-link))
24966 (org-restart-font-lock)
24967 (setq org-descriptive-links t))))
24969 ;; Speedbar support
24971 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24972 "Overlay marking the agenda restriction line in speedbar.")
24973 (overlay-put org-speedbar-restriction-lock-overlay
24974 'face 'org-agenda-restriction-lock)
24975 (overlay-put org-speedbar-restriction-lock-overlay
24976 'help-echo "Agendas are currently limited to this item.")
24977 (delete-overlay org-speedbar-restriction-lock-overlay)
24979 (defun org-speedbar-set-agenda-restriction ()
24980 "Restrict future agenda commands to the location at point in speedbar.
24981 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24982 (interactive)
24983 (require 'org-agenda)
24984 (let (p m tp np dir txt)
24985 (cond
24986 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24987 'org-imenu t))
24988 (setq m (get-text-property p 'org-imenu-marker))
24989 (with-current-buffer (marker-buffer m)
24990 (goto-char m)
24991 (org-agenda-set-restriction-lock 'subtree)))
24992 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24993 'speedbar-function 'speedbar-find-file))
24994 (setq tp (previous-single-property-change
24995 (1+ p) 'speedbar-function)
24996 np (next-single-property-change
24997 tp 'speedbar-function)
24998 dir (speedbar-line-directory)
24999 txt (buffer-substring-no-properties (or tp (point-min))
25000 (or np (point-max))))
25001 (with-current-buffer (find-file-noselect
25002 (let ((default-directory dir))
25003 (expand-file-name txt)))
25004 (unless (derived-mode-p 'org-mode)
25005 (user-error "Cannot restrict to non-Org-mode file"))
25006 (org-agenda-set-restriction-lock 'file)))
25007 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25008 (move-overlay org-speedbar-restriction-lock-overlay
25009 (point-at-bol) (point-at-eol))
25010 (setq current-prefix-arg nil)
25011 (org-agenda-maybe-redo)))
25013 (defvar speedbar-file-key-map)
25014 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25015 (eval-after-load "speedbar"
25016 '(progn
25017 (speedbar-add-supported-extension ".org")
25018 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25019 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25020 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25021 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25022 (add-hook 'speedbar-visiting-tag-hook
25023 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25025 ;;; Fixes and Hacks for problems with other packages
25027 (defun org--flyspell-object-check-p (element)
25028 "Non-nil when Flyspell can check object at point.
25029 ELEMENT is the element at point."
25030 (let ((object (save-excursion
25031 (when (looking-at-p "\\>") (backward-char))
25032 (org-element-context element))))
25033 (cl-case (org-element-type object)
25034 ;; Prevent checks in links due to keybinding conflict with
25035 ;; Flyspell.
25036 ((code entity export-snippet inline-babel-call
25037 inline-src-block line-break latex-fragment link macro
25038 statistics-cookie target timestamp verbatim)
25039 nil)
25040 (footnote-reference
25041 ;; Only in inline footnotes, within the definition.
25042 (and (eq (org-element-property :type object) 'inline)
25043 (< (save-excursion
25044 (goto-char (org-element-property :begin object))
25045 (search-forward ":" nil t 2))
25046 (point))))
25047 (otherwise t))))
25049 (defun org-mode-flyspell-verify ()
25050 "Function used for `flyspell-generic-check-word-predicate'."
25051 (if (org-at-heading-p)
25052 ;; At a headline or an inlinetask, check title only. This is
25053 ;; faster than relying on `org-element-at-point'.
25054 (and (save-excursion (beginning-of-line)
25055 (and (let ((case-fold-search t))
25056 (not (looking-at "\\*+ END[ \t]*$")))
25057 (looking-at org-complex-heading-regexp)))
25058 (match-beginning 4)
25059 (>= (point) (match-beginning 4))
25060 (or (not (match-beginning 5))
25061 (< (point) (match-beginning 5))))
25062 (let* ((element (org-element-at-point))
25063 (post-affiliated (org-element-property :post-affiliated element)))
25064 (cond
25065 ;; Ignore checks in all affiliated keywords but captions.
25066 ((< (point) post-affiliated)
25067 (and (save-excursion
25068 (beginning-of-line)
25069 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25070 (> (point) (match-end 0))
25071 (org--flyspell-object-check-p element)))
25072 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25073 ((let ((log (org-log-into-drawer)))
25074 (and log
25075 (let ((drawer (org-element-lineage element '(drawer))))
25076 (and drawer
25077 (eq (compare-strings
25078 log nil nil
25079 (org-element-property :drawer-name drawer) nil nil t)
25080 t)))))
25081 nil)
25083 (cl-case (org-element-type element)
25084 ((comment quote-section) t)
25085 (comment-block
25086 ;; Allow checks between block markers, not on them.
25087 (and (> (line-beginning-position) post-affiliated)
25088 (save-excursion
25089 (end-of-line)
25090 (skip-chars-forward " \r\t\n")
25091 (< (point) (org-element-property :end element)))))
25092 ;; Arbitrary list of keywords where checks are meaningful.
25093 ;; Make sure point is on the value part of the element.
25094 (keyword
25095 (and (member (org-element-property :key element)
25096 '("DESCRIPTION" "TITLE"))
25097 (save-excursion
25098 (search-backward ":" (line-beginning-position) t))))
25099 ;; Check is globally allowed in paragraphs verse blocks and
25100 ;; table rows (after affiliated keywords) but some objects
25101 ;; must not be affected.
25102 ((paragraph table-row verse-block)
25103 (let ((cbeg (org-element-property :contents-begin element))
25104 (cend (org-element-property :contents-end element)))
25105 (and cbeg (>= (point) cbeg) (< (point) cend)
25106 (org--flyspell-object-check-p element))))))))))
25107 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25109 (defun org-remove-flyspell-overlays-in (beg end)
25110 "Remove flyspell overlays in region."
25111 (and (bound-and-true-p flyspell-mode)
25112 (fboundp 'flyspell-delete-region-overlays)
25113 (flyspell-delete-region-overlays beg end)))
25115 (defvar flyspell-delayed-commands)
25116 (eval-after-load "flyspell"
25117 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25119 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25120 (eval-after-load "bookmark"
25121 '(if (boundp 'bookmark-after-jump-hook)
25122 ;; We can use the hook
25123 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25124 ;; Hook not available, use advice
25125 (defadvice bookmark-jump (after org-make-visible activate)
25126 "Make the position visible."
25127 (org-bookmark-jump-unhide))))
25129 ;; Make sure saveplace shows the location if it was hidden
25130 (eval-after-load "saveplace"
25131 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25132 "Make the position visible."
25133 (org-bookmark-jump-unhide)))
25135 ;; Make sure ecb shows the location if it was hidden
25136 (eval-after-load "ecb"
25137 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25138 "Make hierarchy visible when jumping into location from ECB tree buffer."
25139 (when (derived-mode-p 'org-mode)
25140 (org-show-context))))
25142 (defun org-bookmark-jump-unhide ()
25143 "Unhide the current position, to show the bookmark location."
25144 (and (derived-mode-p 'org-mode)
25145 (or (outline-invisible-p)
25146 (save-excursion (goto-char (max (point-min) (1- (point))))
25147 (outline-invisible-p)))
25148 (org-show-context 'bookmark-jump)))
25150 (defun org-mark-jump-unhide ()
25151 "Make the point visible with `org-show-context' after jumping to the mark."
25152 (when (and (derived-mode-p 'org-mode)
25153 (outline-invisible-p))
25154 (org-show-context 'mark-goto)))
25156 (eval-after-load "simple"
25157 '(defadvice pop-to-mark-command (after org-make-visible activate)
25158 "Make the point visible with `org-show-context'."
25159 (org-mark-jump-unhide)))
25161 (eval-after-load "simple"
25162 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25163 "Make the point visible with `org-show-context'."
25164 (org-mark-jump-unhide)))
25166 (eval-after-load "simple"
25167 '(defadvice pop-global-mark (after org-make-visible activate)
25168 "Make the point visible with `org-show-context'."
25169 (org-mark-jump-unhide)))
25171 ;; Make session.el ignore our circular variable
25172 (defvar session-globals-exclude)
25173 (eval-after-load "session"
25174 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25176 ;;;; Finish up
25178 (provide 'org)
25180 (run-hooks 'org-load-hook)
25182 ;;; org.el ends here